Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

+ Operator in String Class [duplicate]

Tags:

java

string

This is regarding the difference in the result returned by '+' operator. Result varies for String literal and String Object.

String str="ab";
String str1="c";
String str2 = "ab"+"c"; // Line 3
String str3 = "abc";
String str4 = str+str1;  // Line 5

System.out.println(str2==str3);  // True
System.out.println(str2==str4);  // False

With the result we can deduce that with literal, already available object from the string pool is returned as in case of line 3 and with string object new object is returned, as in line 5. Why is it so?

like image 744
Prashant Avatar asked Jun 25 '13 06:06

Prashant


1 Answers

The + oprator for Strings is handled differently depending on the time when the expression can be evaluated.

When the expression can be evaluated at compile time (as in line 3) the compiler will create a String containing only the concatenation. Therefore in line 3 only the String "abc" will be created and this String will be put in the .class file. Therefore str3 and str4 will be exactly the same and will be interned.

When using a concatenation that can be evaluated only at runtime (as in line 5) the resulting String is a new String which must be compared wth equals() as it is a new object.

like image 136
Uwe Plonus Avatar answered Oct 02 '22 13:10

Uwe Plonus