Foundation
08 โ Strings
Previous: 07 Arrays ยท Next: 09 User Input
โถ๏ธ java pkg1core/core9StringsDemo.java
Strings are immutable
1String s = "hello";2s.toUpperCase(); // returns "HELLO"3System.out.println(s); // still "hello"Every "change" creates a new String object.
๐ก Why immutable? Thread-safe, safe as HashMap keys, string pool caching.
String pool
1String a = "hello";2String b = "hello"; // same pooled object3String c = new String("hello"); // new heap object4 5a == b; // true (same reference)6a == c; // false7a.equals(c); // true (same content)โ ๏ธ Always use .equals() for content comparison, not ==.
Essential methods
1s.length();2s.charAt(0);3s.substring(1, 4);4s.indexOf('l');5s.replace("old", "new");6s.split(",");7s.toUpperCase();8s.strip(); // Java 11+ (Unicode-aware trim)9s.isBlank();10"ab".repeat(3); // "ababab"StringBuilder โ efficient building
1StringBuilder sb = new StringBuilder();2for (int i = 1; i <= 5; i++) sb.append(i).append(',');3System.out.println(sb.toString());Use in loops โ + concatenation in a loop is O(nยฒ).
Text blocks (Java 15+)
1String json = """2 {3 "name": "Java",4 "version": 215 }6 """;Formatting
1String msg = String.format("Hello, %s! Score: %d", name, score);2String msg2 = "Score: %d".formatted(score); // Java 15+Deep dive โ 09 Strings & Performance
Next โ 09 User Input
Source named in this chapter
- core9StringsDemopkg1core/core9StringsDemo.java