bhylu.com

Advertisements

Java Read and Compare Strings

A String is immutable text. Methods can return a new string or an answer about the existing one, but they do not rewrite the original object’s characters.

Understand the idea

Use equals for content equality and compareTo when a natural lexicographic order is actually the order you need. == checks whether references identify the same object; string interning can make incorrect == comparisons appear to work for some literals. Assign the result of a transformation if you want to keep it. Be explicit about whether a label comparison should ignore case, surrounding whitespace or neither.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

public class Main {
    public static void main(String[] args) {
        String entered = new String("Mosaic");
        String stored = "Mosaic";
        System.out.println(entered.equals(stored));
        System.out.println(entered == stored);
        System.out.println(stored.toUpperCase(java.util.Locale.ROOT));
        System.out.println(stored);
    }
}

Expected output

true
false
MOSAIC
Mosaic

new deliberately creates a distinct object so the reference comparison is false. equals compares the text instead. The uppercase result is printed without being assigned back, and the following output confirms that stored still contains its original text. Locale.ROOT makes this technical transformation independent of the machine’s display locale.

Check the official Java documentation for detailed contracts and supported options.