-2
public class SubString1
{
public static void main(String[] args)
{
String s="Sachin";
String sb=s+"Tendulkar";
String sbc="SachinTendulkar";
System.out.println(sb==sbc);
}
}

Output : false.

Please Explain how the output is false??

I couldn't understand the logic behind this type of object creation. According to me both should refer to same instance and Answer should have been true. Please Explain.

  • How do you understand about Object memory? – LHA Jan 16 '15 at 22:45
  • 1
    Maybe [this](http://stackoverflow.com/questions/15427599/a-confusion-about-java-string-literal-pool-and-strings-concatenation) is a better duplicate. – Sotirios Delimanolis Jan 16 '15 at 22:45
  • Note that if you say `final String s="Sachin";` the result becomes `true`. But you should still never use `==` to compare strings. – ajb Jan 16 '15 at 22:50
  • Sure. I never compare string using ==. This question was asked in an interview. So I need explanation for it. – Randhish kumar Jan 16 '15 at 22:52
  • The String `"SachinTendulkar"` is an object. The String created by concatenating "Sachin" and "Tendulkar" is a different object. They incidentally have the same value, but that has nothing to do with their "objectness", and `==` is comparing object addresses. – Hot Licks Jan 16 '15 at 22:57

1 Answers1

0

They are different object references. Strings in Java are immutable.

If you want to compare the actual content of the Strings, use the .equals method.

Michael Krause
  • 4,689
  • 1
  • 21
  • 25
  • I want to understand the logic behind it. I agree with you that strings should be compared with equals() method. – Randhish kumar Jan 16 '15 at 22:53
  • Please Explain the logic, how it is happening in java??? – Randhish kumar Jan 16 '15 at 22:53
  • @Randhishkumar The logic is that the code gets executed exactly as you see. There is no occult mechanism behind the scenes that causes `sb` to magically equal `sbc` when compared with the == operator. If you think there is, tell us what you think it is. It's a poorly phrased interview question, and not one that exhibits great competence or genuine interest on the part of the interviewer. – user207421 Jan 16 '15 at 23:13