class Test{
public static void main(String s[]){
String s1="welcome",s2="come";
System.out.println(s1==("wel"+"come")); //prints : true
System.out.println(s1==("wel"+s2)); //prints : false
}
}
I want to know why both the println methods are giving different results. Please explain in details.
==
always compares the references themselves.
In the first comparison, the constant string expression "wel" + "come"
is evaluated at compile-time, and so you end up with the same interned reference as for the literal used to initialize s1
.
In the second case, the concatenation is performed at execution time, creating a new string.
To compare two strings for equality of contents (rather than checking whether two references refer to the same object) use equals
:
System.out.println(s1.equals("wel" + "come"));
System.out.println(s1.equals("wel" + s2));
String s1="welcome",s2="come";
System.out.println(s1==("wel"+"come")); //prints : true
These are compile-time constants, so the compiler can inline the code to
System.out.println(s1==("welcome")); //prints : true
Here, the second part is not a compile-time constant, so the compiler can't optimize, hence a new String object is created at runtime:
System.out.println(s1==("wel"+s2)); //prints : false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With