Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many object creates with new operator? [duplicate]

Tags:

java

Possible Duplicate:
Java Strings: “String s = new String(”silly“);”

If i write

String s= new String("how many object b created by this method ");

how many reference objects and objects will be created in comparison to doing it this way:

Sting s1="Is this method is good as compare to upper"; 
like image 972
Aditya Avatar asked Dec 16 '22 12:12

Aditya


2 Answers

Using String s= new String("how many object b created by this method "); creates a new object 's' of String class, and you are passing the string "how many object b created by this method" to its constructor.

In String s1="Is this method is good as compare to upper"; 's1' is a string literal. On string literals:

Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption.

source

The above concept is related to string interning; all literal strings and string-valued constant expressions are interned in Java [source]. So basically, using String s1="Is this method is good as compare to upper"; will create a new object only if "Is this method is good as compare to upper" is not already in the pool.

like image 158
Dhruv Gairola Avatar answered Dec 19 '22 01:12

Dhruv Gairola


Using String s1="some string" doesn't create new String object. There is existing String object for every String literal already.

String literals with same values are represented with single String object, so if you use String s1="some string"; String s2="some string"; both s1, s2 refer to same "some string" object.

new String("...") creates one new String object, which uses same data as String object for value "..." passed to constructor.

like image 35
Peter Štibraný Avatar answered Dec 19 '22 03:12

Peter Štibraný