-6

Possible Duplicate:
How do I compare strings in Java?

class StringTest {
public static void main(String[] args) {
String str1 = "Hi there";
String str2 = new String("Hi there");
System.out.println(str1 == str2);
System.out.println(str1.equals(str2));
}

The output is coming out:

                          False
                          true  

Why the first output is false even when the str1 and str2 appear to be equal?

Community
  • 1
  • 1
gpuguy
  • 4,607
  • 17
  • 67
  • 125

5 Answers5

6

== compares content of variables. (You know this very well from intA == intB.)

A String variable contains a reference to a String object, so == will compare references.

After

String str1 = "Hi there";
String str2 = new String("Hi there");

str1 and str2 will refer to different string objects, thus contain different references, so str1 == str2 will yield false.

str1.equals(str2) on the other hand will compare the objects that str1 and str2 refers to, which, as you have noted, yields true.

aioobe
  • 413,195
  • 112
  • 811
  • 826
1

Because if you use new operator it create a new reference in memory.

== compares references of both object which are not same.

use equals to compare contents.

Pramod Kumar
  • 7,914
  • 5
  • 28
  • 37
0

As an addition to aioobe's answer: you should actually compare objects using the equals method. The == operator on objects is going to compare if the reference of both objects points to the same memory address.

Kurt Du Bois
  • 7,550
  • 4
  • 25
  • 33
0

== compares object reference contents i.e. str1 and str2 and not object contents while equals() does compare object contents i.e (objects pointed by str1 and str2)

Also check this :

String str1 = "Hi there";
String str3 = "Hi there";

str1 == str3 => true

This is because JVM handles string literals in different way. Check here

Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
0

In java when you create objects with new keyword they are created in heap at some location .

Even if you create third reference variable str3 with new then also it will give you false if compare reference with str2

String str1 = "Hi there";
String str2 = new String("Hi there");
String str3 = new String("Hi there");

 str2==str3 gives you false

So when you compare the values of objects use equals rather than reference .

amicngh
  • 7,831
  • 3
  • 35
  • 54