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.
当使用文字进行初始化时, String
StringPool
使用new
关键字进行初始化具有优先级,这是因为JVM优化了,并且因为JVM直接在StringPool
分配了使用文字进行初始化的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");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.