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";
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.
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.
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