There is an interview question:
How many instances will be created in this statement:
String str1 = new String ("abc")
And the answer is 2: str1
and "abc"
.
Is that correct?
new String() only creates one object. new String("literal") does create one or two objects. (It depends on whether the string object for "literal" has already been created.) The purpose of intern() is to deal with strings that are created in other ways; e.g. from a char array or byte array or by a String method.
String Str = "a" +"b"+"c"; Only one object will be created in scp area.
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool.
In other words doing String s = new String("ABC") creates a new instance of String , while String s = "ABC" reuse, if available, an instance of the String Constant Pool.
Only one instance will be created at run time . When the class is loaded the literal "abc"
will be interned in the String pool , though technically speaking JVM creates an instance of "abc"
and keeps it in the String pool . The expression new String("abc")
creates an instance of the String
.
JLS 3.10.5:
A string literal is a reference to an instance of class String (§4.3.1, §4.3.3).
Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.
Also , read JLS 15.28
Compile-time constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern.
Suggested Reading:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With