1
votes

String is Immutable (Fact)

Lets say I have two objects of string given below:

String str1 = new String("dave");
String str2 = new String("dave");

While compiling, Interning of string objects happens. And according to Wikipedia, It says "string interning is a method of storing only one copy of each distinct string value, which must be immutable. All compile-time constant strings in Java are automatically interned using this method."

If that's a case, then what would happen to my two references str1 and str2 ? To which object they will point out once compiled ?

I hope its valid question, otherwise correct me, I'm confused little bit.

1
str1 and str2 are not compile time constants, since they are both instantiated with new - khelwood
@khelwood, So you mean both references would skip Interning while compilation. And nothing will happen to the two similar objects. They will exist individually with their respective references. Is it so ? - LearnJava
The two string literals "dave" may be interned, but the objects held by str1 and str2 are different objects each created by new at runtime. They do indeed exist individually. - khelwood
In other words str1 != str2 && str2 != "dave", && str2 != "dave" - Kevin Anderson
Doesn't System.out.println(str1 == str2); answer your question? new String("dave") is NOT the same as "dave". - Bernhard Barker

1 Answers

0
votes

Below both str1 and str2 are created on heap, because you are creating them at run time. Even both objects are created at different references.

String str1 = new String("dave");
String str2 = new String("dave");

Even str1 == str2 will return false. Their values are same but they are two different objects on heap.


However if you create the object at compile time, as example

String str1="dave";
String str2="dave";

then str1 == str2 will return true, because both these objects are part of same reference created at compile time in string pool.

When we use double quotes to create a String, it first looks for String with same value in the String pool, if found it just returns the reference else it creates a new String in the pool and then returns the reference.