String Class Methods
1. Must-Know Methods (beginner survival kit)
Strings are immutable — methods return new Strings, never change original! Index starts 0.
2. Table + Live Code (try each!)
String s = " Java Prog ";
System.out.println(s.length()); // 13 (includes spaces!)
System.out.println(s.charAt(2)); // 'J' (0:A 1:A? no — count: 0:' ' 1:' ' 2:'J')
System.out.println(s.trim().length()); // 9 ("Java Prog" — trim cuts ends!)
System.out.println("java".toUpperCase()); // JAVA
System.out.println("JAVA".toLowerCase()); // java
System.out.println("hello".substring(1, 4)); // ell (1 to 3, end EXCLUDED!)
System.out.println("hello".replace('l','x')); // hexxo (new string!)
System.out.println("a,b,c".split(",").length); // 3 (array!)
System.out.println("hi".concat("!")); // hi! (same as +)
| Method | Job | Example |
|---|---|---|
length() |
char count | "hi".length() → 2 |
charAt(i) |
char at i | "hi".charAt(0) → 'h' |
substring(a,b) |
slice a to b-1 | "hello".substring(1,4) → ell |
trim() |
cut end spaces | " a ".trim() → a |
split(d) |
cut by delimiter | "a,b".split(",") → [a,b] |
replace(a,b) |
swap chars | "ll" → xx |
3. Traps
s.trim();alone does NOTHING (returns new!). Musts = s.trim();.substring(1,4)ends at 3 (end excluded!).charAt(length)→ crash!+/concatin loops = slow (see StringBuilder!).
4. Exam Points
- Table + trim/substring/split program — 7 marks, very frequent.
- Immutability proof (
sunchanged) — 3 marks, frequent.