0

when i am comparing a string that is concatinated and comparing the objects of the concatinated string and normal string its showing false. I thought that the Strig literal "kalyansreekar" is already present in String constant pool. can soomeone explain me why this is happening and also the implementation code of string concatination. Thank you.

String a="kalyan";
String b=a+"sreekar";
String c="kalyansreekar";
System.out.println(b==c);

"I expect the result to be true, but the actual output is false"

George Z.
  • 6,643
  • 4
  • 27
  • 47

2 Answers2

0

Here b==c compares the reference of the string not the content of the string.
If you want to compare value of string then use b.equals(c) instead of b==c

sandip
  • 129
  • 5
  • i don't want to compare values. I thought both the references b and c will point to same string literal "kalyansreekar" string in constant pool and so the output should be true but its not. – Kalyan Sreekar Jhade Sep 05 '19 at 13:06
  • @KalyanSreekarJhade well then you just tested it and saw it was not the case. Use `intern()` to make it so. – Matthieu Sep 05 '19 at 18:52
  • 1
    But that doesn't mean they're pointing to the same place in memory, they are separate objects. – Richard Barker Sep 05 '19 at 18:52
0

The + on String internally uses a StringBuilder that returns a new String instance (on Java <= 8) or uses invokedynamic (on Java >= 9).

Code constants like "kaylan", "sreekar" and "kalyansreekar" are interned in the JVM String pool. If you really want to compare using references, then try:

String a="kalyan";
String b=a+"sreekar";
b=b.intern(); // Puts it in the String pool
String c="kalyansreekar";
System.out.println(b==c); // true
Matthieu
  • 2,736
  • 4
  • 57
  • 87