ramoh
ramoh

Reputation: 153

Why I am getting different result in different JVM for following code

String s="hel"+"lo"

if(s == "hello")
 {
    //print true 

}
else
{
 //print false 
}

Sun jvm = true Ibm jvm = false

Why this discrepancy ?

Upvotes: 0

Views: 136

Answers (5)

Jonathan Drapeau
Jonathan Drapeau

Reputation: 2610

I would point out that Java 7 and 6 behave differently with the interned Strings, see this answer

If you are using sun Java 7, maybe the IBM jvm is still working as Java 6.

Upvotes: 1

The == only succeedes if the string is interned after construction. I believe the crucial point is if javac optimizes the + at compile time or not, i.e. if the JVM sees

String s = "hello"

or

String s = "hell" + "lo".

(by the way, this must be a copy paste error - there will be three l's in the concatenated value)

Upvotes: 2

Rohan
Rohan

Reputation: 3078

== is used to check if both object are referring to same object. Use if(object1.equals(object)) to check if contents of both object are equal

Upvotes: 1

noamik
noamik

Reputation: 827

While not answering your question: doing == on strings is most likely not what you wanted in the first place.

    if(s.equals("hello")) {

might be what you really wanted to do ...

Edit: since "==" compares references, depending on their implementation of how new strings are created both jvms could be right with their results at the same time! "==" is NOT a valid operator to check the equality of strings in Java.

Upvotes: 0

Ajay George
Ajay George

Reputation: 11875

== is for reference comparison.

For the Sun JVM this behaviour is most likely due to String pool.
For IBM JVM it could be a different implemenation.

If you need object comparison use equals

Upvotes: 7

Related Questions