Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Why can String equality be proven with ==?

Tags:

java

string

I learned that it is from the devil to test String equality with == instead of String.equals(), because every String was a reference to its own object.

But if i use something like

System.out.println("Hello" == "Hello");

it prints true.

Why?

like image 950
Zeemee Avatar asked Dec 07 '09 08:12

Zeemee


2 Answers

It doesn't. It's still a bad thing to do - you'll still be testing reference equality instead of value equality.

public class Test
{
    public static void main(String[] args)
    {
        String x = "hello";
        String y = new String(x);
        System.out.println(x == y); // Prints false
    }
}

If you're seeing == testing "work" now then it's because you genuinely have equal references. The most common reason for seeing this would probably be due to interning of String literals, but that's been in Java forever:

public class Test
{
    public static void main(String[] args)
    {
        String x = "hello";
        String y = "hel" + "lo"; // Concatenated at compile-time
        System.out.println(x == y); // Prints true
    }
}

This is guaranteed by section 3.10.5 of the Java Language Specification:

Each string literal is a reference (§4.3) to an instance (§4.3.1, §12.5) of class String (§4.3.3). String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are "interned" so as to share unique instances, using the method String.intern.

like image 117
Jon Skeet Avatar answered Oct 24 '22 15:10

Jon Skeet


It hasn't changed. However, the Java Compiler uses string.intern() to make sure that identical strings in source code compile to same String object. If however you load a String from a File or Database it will not be the same object, unless you force this using String.intern() or some other method.

It is a bad idea, and you should still use .equals()

like image 44
Nick Fortescue Avatar answered Oct 24 '22 15:10

Nick Fortescue