Java Strings Lab
Explore Java String methods with a visual character-index grid. See exactly how substring, indexOf, charAt, and other methods work on real strings. Trace common String algorithms step by step.
Guided Experiment: String Indexing and Extraction
How does Java index characters in a String? What does it mean for substring's end index to be exclusive? What happens when you access an index that is out of bounds?
Write your hypothesis in the Lab Report panel, then click Next.
Controls
Returns characters from beginIndex (inclusive) to endIndex (exclusive).
Result
String str = "HelloWorld";
String sub = str.substring(0, 5); // "Hello"Data Table
(0 rows)| # | Mode | Method / Algorithm | Input | Arguments | Output | Steps |
|---|
Reference Guide
String Basics
Java Strings are 0-indexed sequences of characters. The first character is at index 0 and the last is at index length() - 1.
String s = "Hello";
s.length() // 5
s.charAt(0) // 'H'
s.charAt(4) // 'o'
s.isEmpty() // false
"".isEmpty() // true Strings in Java are immutable. Methods return new String objects, never modifying the original.
Searching and Comparing
Search for substrings with indexOf and contains. Compare strings with equals (case-sensitive) and compareTo (lexicographic ordering).
"banana".indexOf("an") // 1
"banana".lastIndexOf("an") // 3
"hello".contains("ell") // true
"apple".compareTo("banana") // negative
"hello".equals("Hello") // false Never use == to compare Strings in Java. Use equals() for content comparison.
Extracting and Modifying
Extract parts of a string with substring (begin inclusive, end exclusive). Transform with toUpperCase, toLowerCase, replace, and trim.
"HelloWorld".substring(0, 5) // "Hello"
"hello".toUpperCase() // "HELLO"
"hello".replace("l", "r") // "herro"
" hi ".trim() // "hi" substring(a, b) returns b - a characters. The character at index b is not included.
Common Algorithms
Classic String algorithms use character arrays and the two-pointer technique. Understanding these builds a foundation for AP Computer Science.
// Reverse with two pointers
char[] c = s.toCharArray();
int L = 0, R = c.length - 1;
while (L < R) {
char tmp = c[L];
c[L++] = c[R];
c[R--] = tmp;
} The Algorithm Tracer tab shows variable state at each step so you can follow the logic.