Java traps · Java

Java: "hi" == "hi" is FALSE?!FREE

Watch the video

== checks if two Strings are the SAME OBJECT, not the same text. Run it to see the false, then the .equals() fix.

// "hi" == "hi" is FALSE ?!  — == checks if it's the SAME OBJECT, not the same text.
public class Main {
    public static void main(String[] args) {
        String a = "hi";
        String b = new String("hi");   // same text, a new object

        System.out.println(a == b);        // false ?!
        System.out.println(a.equals(b));   // true ✓  (compares the text)

        // Strings built at runtime are new objects too:
        String c = "h";
        String d = c + "i";
        System.out.println(a == d);        // false ?!
        System.out.println(a.equals(d));   // true ✓
    }
+ 2 more lines in the app
Open code J1 in Pocket Compiler Download the Pocket Compiler app — free

No app yet? Install it, then open the app and type the code J1 in Code Library.