My question is simple. Whats the difference between -
s3=s1+s2
and s3="string"
?
I think I was very poor in explaining it.
I do understand the difference between ==
and .equals()
.
My question is simple. Whats the difference between -
s3=s1+s2
and s3="string"
?
I think I was very poor in explaining it.
I do understand the difference between ==
and .equals()
.
A new String
object will be created, when the concatenation of 2 objects take place. But if you concat 2 string literals, then a new object won't be created.
String s3=s1+s2; // new object created
System.out.println(s3=="string"); // false
String s4="str"+"ing"; // this will not create a new string object
System.out.println(s4=="string"); // true
When the compiler encounters String s4="str"+"ing";
, the compiler does a constant folding on the compile-time constants and puts it into just one string, since the concatenation happens at compile time itself, and the completed string therefore goes in the constant pool.
==
operator checks whether the references to the objects are equal.
equals()
method checks whether the values of the objects are equal.
For comparing strings use equals
System.out.println(s3.equals("string"));
s3
is a new String
object that is the concatenation of s1
and s2
==
will compare their memory addresses. not their literal values. use .equals()
== is used on primitive types. On object you should use compare or equals. Strings are treatenin a particular way. Because == on strings doesn't alsways work fine is due by the concatenating of them by the jvm. It takes only the reference to the strings, == checks the memory location.