Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 482
XiaoYao Avatar asked Jul 29 '13 09:07

XiaoYao


People also ask

How many new instances of string are created?

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.

How many objects will be created in string temp A B C?

String Str = "a" +"b"+"c"; Only one object will be created in scp area.

How are the instances created in string class?

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.

What is the difference of new string (' ABC ') and ABC?

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.


1 Answers

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:

  1. Java String is Special
  2. what is String pool in java?
  3. Strings, Literally.
like image 171
AllTooSir Avatar answered Nov 04 '22 08:11

AllTooSir