Core Java

core9StringsDemo

Path
pkg1core/core9StringsDemo.java
Package
pkg1core
Study order
8
Run
Single-file source launch
Command
java pkg1core/core9StringsDemo.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg1core/core9StringsDemo.java
1package pkg1core;2 3/*4 * core9StringsDemo.java5 * ----------------6 * String immutability, common methods, StringBuilder, text blocks, formatting.7 *8 * EXPLANATION:9 *  - Strings are immutable: every "modification" creates a new String.10 *  - Literals are interned in the string pool; `new String("x")` is a new object.11 *  - Use StringBuilder for repeated concatenation (avoids creating many objects).12 */13public class core9StringsDemo {14    public static void main(String[] args) {15        String s = "Java Mastery";16 17        // Common methods18        System.out.println("length: " + s.length());19        System.out.println("upper: " + s.toUpperCase());20        System.out.println("substring(5): " + s.substring(5));21        System.out.println("indexOf('M'): " + s.indexOf('M'));22        System.out.println("replace: " + s.replace("Java", "Pro"));23        System.out.println("split: " + java.util.Arrays.toString(s.split(" ")));24        System.out.println("repeat: " + "ab".repeat(3));25        System.out.println("strip/isBlank: [" + "  hi  ".strip() + "] " + "   ".isBlank());26 27        // Immutability proof28        String original = "abc";29        original.toUpperCase();         // result ignored -> original unchanged30        System.out.println("still lower: " + original);31 32        // == vs equals (pool vs new object)33        String a = "hello";34        String b = "hello";             // same pooled object35        String c = new String("hello"); // new heap object36        System.out.println("a == b : " + (a == b) + " (pooled)");37        System.out.println("a == c : " + (a == c) + " (different objects)");38        System.out.println("a.equals(c): " + a.equals(c) + " (value equality)");39 40        // StringBuilder for efficient building41        StringBuilder sb = new StringBuilder();42        for (int i = 1; i <= 5; i++) sb.append(i).append(',');43        sb.setLength(sb.length() - 1);  // drop trailing comma44        System.out.println("built: " + sb);45        System.out.println("reversed: " + sb.reverse());46 47        // Text block (Java 15+) and formatting48        String json = """49            {50              "name": "JavaMastery",51              "level": 2152            }""";53        System.out.println("text block:\n" + json);54        System.out.println("formatted: " + "Pi is approximately %.3f".formatted(Math.PI));55    }56}