Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If == compares references in Java, why does it evaluate to true with these Strings?

As it is stated the == operator compares object references to check if they are referring to the same object on a heap. If so why am I getting the "Equal" for this piece of code?

public class Salmon {
    public static void main(String[] args) {

        String str1 = "Str1";
        String str2 = "Str1";

        if (str1 == str2) {
            System.out.println("Equal");
        } else {
            System.out.println("Not equal");
        }
    }
}
like image 440
Eugene Avatar asked Oct 27 '10 13:10

Eugene


People also ask

Why does == work on strings in Java?

In String, the == operator is used to comparing the reference of the given strings, depending on if they are referring to the same objects. When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object. Otherwise, it will return false .

Why Java string equals vs ==?

equals() method in Java. Both equals() method and the == operator are used to compare two objects in Java. == is an operator and equals() is method. But == operator compares reference or memory location of objects in a heap, whether they point to the same location or not.

Can you compare strings with == in Java?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

When comparing strings Why is == not a good idea?

The == operator is one of the first operators learned when diving into a new language, typically for comparing primitive data types like int s. This is because the == operator doesn't check for equality. It checks for identity. In other words, it doesn't compares the String s value - it compares object references.

How to compare string in Java?

There are three ways to compare String in Java: The String class equals () method compares the original content of the string. It compares values of string for equality. String class provides the following two methods:

What is the use of comparetoignorecase () method in Java?

The compareToIgnoreCase () is similar to the previous method, except it ignores case: 3. String Comparison With Objects Class Objects is a utility class which contains a static equals () method, useful in this scenario – to compare two Strings.

What is referential equality in Java?

Referential Equality means two reference variable pointing to the same object in Java heap.Generally programmers use == to compare string values which is wrong.For comparing two string values equals () method is used. == operator is only used to check two string variable pointing to the same memory location.

How to compare values between two references in a string?

It only compares the values if the two references are not identical. The equals method and == and != operators test for equality/inequality, but do not provide a way to test for relative values. Some classes (eg, String and other classes with a natural ordering) implement the Comparable<T> interface, which defines a compareTo method.


3 Answers

The program will print Equal. (At least using the Sun Hotspot and suns Javac.) Here it is demonstrated on http://ideone.com/8UrRrk

This is due to the fact that string-literal constants are stored in a string pool and string references may be reused.

Further reading:

  • What is String literal pool?
  • String interning

This however:

public class Salmon {
    public static void main(String[] args) {

        String str1 = "Str1";
        String str2 = new String("Str1");

        if (str1 == str2) {
            System.out.println("Equal");
        } else {
            System.out.println("Not equal");
        }
    }
}

Will print Not equal since new is guaranteed to introduce a fresh reference.

So, rule of thumb: Always compare strings using the equals method.

like image 172
aioobe Avatar answered Oct 11 '22 00:10

aioobe


Java stores all Strings in a string table internally during a run. The references to the two strings are identical because in memory they're stored in the same place. Hence, Equal.

Your statement is right, that == compares object references. Try the same thing with any other class but Strings and you won't get the same result.

like image 3
James Cronen Avatar answered Oct 11 '22 00:10

James Cronen


This code won't print Equal.
But if the two strings were the same, this case would be special.

Now that you've updated your code, it is the case :

A simple (but not totally exact) explanation is that the compiler see that the two strings are the same and do something like :

String str1 = "Str1";
String str2 = str1;

What really happens here is that the compiler will see the literal string and put it in the "String literal pool".

As a String can't be modified (it's immutable) the literal values of Strings (those found during compilation) are put in a "pool".
This way, if two different literal strings which have the same content (like in this particular case), the memory isn't wasted to store "Str1" and "Str1" two times.

like image 3
Colin Hebert Avatar answered Oct 11 '22 02:10

Colin Hebert