AnyCompiler

Strings

A Java String is immutable — once created, it can never be changed. Concatenating with + doesn't modify the original string; it builds and returns a brand-new one, and .length() reports a string's character count.

public class Main {
    public static void main(String[] args) {
        String first = "Hello";
        String second = "World";
        String combined = first + ", " + second + "!";
        System.out.println(combined);
        System.out.println("length = " + combined.length());
    }
}
Output
Hello, World!
length = 13

== versus .equals()

== compares object references — whether two variables point at the exact same object in memory — while .equals() compares the actual contents. Two String objects created separately with new String(...) hold equal text but are different objects, which is why == can return false even when the strings look identical; comparing strings almost always means reaching for .equals().

public class Main {
    public static void main(String[] args) {
        String a = new String("java");
        String b = new String("java");
        System.out.println(a == b);
        System.out.println(a.equals(b));
    }
}
Output
false
true

Next: classes and objects — defining a class, fields, constructors, and creating instances.

Practice exercise

Given String s = "rust lang", use substring to extract just "rust" (the first 4 characters), then print it.