-3
     String str1 = "abc:5";
     String str2 = "abc:" + str1.length();
     String str3 = "abc:" + 5;


     System.out.println(str1==str2);
     System.out.println(str1==str3);

Output of the program is : false true

But I don't understand why?

user2014
  • 87
  • 1
  • 1
  • 8

3 Answers3

1

== operator will compare reference only

.equals() will compare the values.

in your case

str1==str2 // compares the two references, which are different.

had it been, str1.equals(str2), it would have compared the values, which will return true

The “==” operator

In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.The “==” operator compares the objects’ location(s) in memory

The “equals” method The Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory.

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
  • so here, str1 and str3 refers to same memory location?? – user2014 Dec 13 '14 at 16:17
  • @user2014 `"" + 5` here `5` is treated as String only, whereas `str.length()` will be considered as `int`, but hashcode of all the three are same. But not much sure as why the results are different, already upvoted for your question. – Ankur Singhal Dec 13 '14 at 16:45
0

Here str1 = "abc:5"; is located in constant pool of string and str2 is concatenated with 2 different object with new operator. So both str1 and str2 are referring to different object. That's the reason it is showing false.

RKP
  • 99
  • 6
0

The == operator is used for only reference variables in java. For example if you are comparing characters a1 and a2 you can use the == operator because the char type is highlighted in most IDEs in Java. To check if two Strings are equal to each other you can use .equals()or .equalsIgnoreCase() to compare the Strings. This is because Strings are objects, not primitives, and require their own method in the class to test if Strings are the same.

For the first System.out.println(); statement, you would use System.out.println(str1.equals(str2)); or System.out.println(str1.equalsIgnoreCase(str2));.

For the second System.out.println(); statement, you would use System.out.println(str1.equals(str3)); or System.out.println(str1.equalsIgnoreCase(str3));.

fedorp1
  • 23
  • 3