Foundation

08 โ€” Strings

Previous: 07 Arrays ยท Next: 09 User Input

โ–ถ๏ธ java pkg1core/core9StringsDemo.java


Strings are immutable

java
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

java
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

java
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

java
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+)

java
1String json = """2    {3      "name": "Java",4      "version": 215    }6    """;

Formatting

java
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