I just failed a code review without any reason given due to my writing, for a function where s
(of type String) is passed as a parameter
if (s == null){
s = new String();
}
Said I should use s = "";
instead. Why?
I just failed a code review without any reason given due to my writing, for a function where s
(of type String) is passed as a parameter
if (s == null){
s = new String();
}
Said I should use s = "";
instead. Why?
You could always clarify with the reviewer?
new String();
always creates a new string. (Isn't the Java syntax self-explantory?)
s = ""
; will set the reference to an interned string and is therefore preferred.
There is a preference in the String
class when initialized with literals over initialization with the new
keyword, this is because of the JVM optimizations, and because the JVM allocates strings initialized with literals directly in the StringPool
.
Both s = new String();s = "";
expressions give a string object but there is a clear difference between the two. s=new String()
will create a new object in the heap memory whereas if we create object using string literal s = "";
it may return an existing object from String pool(a cache of string objects) if it already exists.
Example will make it more clear:
String a= "banana";
String b= "banana";
Here both a and b refer to the same object and hence a==b
is true
String a =new String("banana")
String b= new String("banana")
Here both a and b refer to two different objects and hence a==b
is false
JVM handle it differently if you call:
You can find the full answer in the link bebow: http://o7planning.org/web/fe/default/en/document/19529/string-stringbuffer-and-stringbuilder-tutorial
Example:
public static void main(String[] args) {
String str1 = "apple";
String str2 = "apple";
if(str1 == str2) {
System.out.println("str1, str2: same object");
} else {
System.out.println("str1, str2: different object");
}
String str3 = new String("apple");
String str4 = new String("apple");
if(str3 == str4) {
System.out.println("str3, str4: same object");
} else {
System.out.println("str3, str4: different object");
}
}