Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shouldn't I do `String s = new String("a new string");` in Java, even with automatic string interning?

Ok, this question is an extension of this question

Java Strings: "String s = new String("silly");"

The above question asked the same question as this one, but I have a new doubting point.

According to Effective Java and the answers of above question, we should not do String s = new String("a new string");, because that will create unnecessary object.

I am not sure about this conclusion, because I think Java is doing automatic string interning, which means for a string, anyway there is only one copy of it in the memory.

So let's see String s = new String("a new string");.

"a new string" is already a string which has been created in the memory.

When I do String s = new String("a new string");, then the s is also "a new string". So according to automatic string interning, s should be pointed to the same memory address of "a new string", right?

Then how can we say we create unnecessary objects?

like image 596
Jackson Tale Avatar asked May 19 '12 15:05

Jackson Tale


People also ask

What is string intern () When and why should it be used?

String Interning is a method of storing only one copy of each distinct String Value, which must be immutable. By applying String. intern() on a couple of strings will ensure that all strings having the same contents share the same memory.

Does new string create object in string pool?

Each time a string literal is created, the JVM checks the string literal pool first. If the string already exists in the string pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object initializes and is placed in the pool.

Why new keyword is not used in string?

String message = new String("Hai"); new String("Hai") is a new String object. In this case, even if the literal "Hai" was already in the string literal pool, a new object is created. This is not recommended because chances are that you might end with more than one String objects with the same value.


1 Answers


String a = "foo"; // this string will be interned
String b = "foo"; // interned to the same string as a
boolean c = a == b; //this will be true
String d = new String(a); // this creates a new non-interned String
boolean e = a == d; // this will be false
String f = "f";
String g = "oo";
String h = f + g; //this creates a new non-interned string
boolean i = h == a // this will be false
File fi = ...;
BufferedReader br = ...;
String j = br.readLine();
boolean k = a == j; // this will always be false. Data that you've read it is not automatically interned
like image 139
ControlAltDel Avatar answered Oct 07 '22 04:10

ControlAltDel