0
String string1="Hello Snehal";
String string2=new String("Hello Snehal");
String string3=string2.intern();


System.out.println("string1==string2  " +  string1==string2);  // false. OK.
System.out.println("string2==string3  " +  string2==string3);  // false. OK.
System.out.println("string1==string3  " +  string1==string3);  // false. why not TRUE?

When searched other questions for clarification, e.g. When should we use intern method of String on String constants, still not getting clue about 3rd case.

Community
  • 1
  • 1
Snehal Masne
  • 3,403
  • 3
  • 31
  • 51

2 Answers2

4

All of them are false, because what's happening are few checks whether:

  • "string1==string2 " + string1 refers to string2 (for the first statement)
  • "string2==string3 " + string2 refers to string3 (for the second one)
  • "string1==string3 " + string1 refers to string1 (for the last one).

You need to wrap the stringX == stringY pieces, because otherwise String concatenation will take place first (as you might already know, the statements in Java are evaluated from left to right and wrapping some of them with brackets () gives them priority).

So, having this:

System.out.println("string1==string2  " +  (string1==string2)); 
System.out.println("string2==string3  " +  (string2==string3));
System.out.println("string1==string3  " +  (string1==string3));

should behave differently and then you should be able to investigate the output.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
1

String.intern() on a string will ensure that all strings having same contents share same memory . Refer to javadoc for more detail.

Dark Knight
  • 8,218
  • 4
  • 39
  • 58