how many instances be created in String str1 =new String ("abc")?

java

Solution

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:

- Java String is Special

- what is String pool in java?

- Strings, Literally.

Problem

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?

Original source

Related problems