String Basics
Use core String methods: length(), charAt(i) (returns char, not String), substring(start, end) (end is EXCLUSIVE: substring(1,3) returns characters at indices 1 and 2), indexOf(str), equals(str), equalsIgnoreCase(str), compareTo(str), toUpperCase(), toLowerCase(), and concatenation with +. Understand that Strings are immutable: methods return new Strings and never modify the original. Master the critical distinction between == (reference equality, tests if same object in memory) and .equals() (value equality, tests if same characters). Using == on Strings is the most common and dangerous beginner mistake. Trace String expressions including mixed concatenation with numbers.
A lesson of AP Computer Science A, in Java Foundations, about 10 minutes.
String Methods in Java
By the end of this lesson, you will be able to use the most important String methods, correctly compare strings, and work with string indices.
Strings Are Immutable
String s = "Hello";
s = s + "!"; // creates a NEW string "Hello!"; the original "Hello" still exists in memory
A String in Java cannot be changed. Every "modification" creates a new String object.
String Length and Indexing
String s = "Hello";
s.length() // 5 (number of characters)
s.charAt(0) // 'H' (first character; index 0)
s.charAt(4) // 'o' (last character; index = length - 1)
s.charAt(5) // StringIndexOutOfBoundsException!
Indices run from 0 to length - 1. The most common string error is accessing index length (which is one past the end).
Key String Methods
String s = "Hello World";
s.length() // 11
s.substring(6) // "World" (from index 6 to end)
s.substring(0, 5) // "Hello" (indices 0 through 4; end is exclusive)
s.indexOf("o") // 4 (first 'o')
s.indexOf("o", 5) // 7 (first 'o' starting at index 5)
s.indexOf("xyz") // -1 (not found)
s.toLowerCase() // "hello world"
s.toUpperCase() // "HELLO WORLD"
s.equals("Hello World") // true
s.equalsIgnoreCase("hello world") // true
s.contains("World") // true
s.replace("World", "Java") // "Hello Java" (returns a NEW string)
Comparing Strings: Always Use .equals()
String s1 = "hello";
String s2 = "hello";
s1 == s2 // UNRELIABLE (tests reference equality; usually wrong)
s1.equals(s2) // TRUE (tests value equality; always correct)
== for strings compares memory addresses, not content. Always use .equals() or .equalsIgnoreCase().
String to int and int to String
// String to int:
int n = Integer.parseInt("42");
// int to String:
String s = String.valueOf(42); // "42"
// or:
String s = "" + 42; // "42" (concatenation trick)
// String to double:
double d = Double.parseDouble("3.14");