Using '==' with strings? (Java)

String str1 = new String("I love programming");
String str2 = new String("I love programming");
boolean boo = str1 == str2; // evaluates to false

String str1 = "I love programming";
String str2 = "I love programming";
boolean boo = str1 == str2; // evaluates to true

      

Why are you evaluating false first and second evaluating true?

And you can find more here: What is Java string pool and how is "s"? other than newline ("s")?

+3


source to share


4 answers


==

will return true if the objects themselves have the same address. For space and efficiency reasons, duplicate literals are optimized to use the same address. The second str1

and str2

are equal to the same address, so it ==

returns true.

In the first example, because you are explicitly declaring memory with a keyword new

, str1

and str2

do not have the same addresses. So it str1==str2

matters false

.



When testing for equality, use a function instead String.equals();

. Thus,str1.equals(str2); //true

+13


source


The equals () method compares the contents of the String and == compares the reference in Java.



+1


source


It's there in the Java Memory Model

The first equality statement returns false because you are comparing two different references of two different objects, because you used a keyword new

that allocates memory space inside the heap to two different memory addresses, seconds, the JVM will allocate memory space once "on the stack" ( from Java 7 they are on the heap too ) and the compiler optimizes memory usage by forcing the two variables to point to the same memory space, which explains that the result is equality true

.

Here's an interesting read about the heap, stack, etc. JVM Internals Blog

Greetings

+1


source


Not like C. (==) compares references to string variables java. It compares the two addresses where strings are stored. Two comparisons of them by value, you need to use string1.equals (string2).

0


source







All Articles