Thursday, 5 September 2019

What is the difference between creating a Java String as new() and literal ?

Just have a look in below example :- 
String str = new String("abc");
String str = "abc";
Here we are creating object of a String in two ways. 
-> Using the new operator 
String str = new String("abc");
This will always create two object, One in the Heap Area and One in the String constant pool and the String object reference always points to heap area object.
-> Using String Literals
String str = "abc";
When compiler encounters String literal, it checks the String Constant Pool to see if the given string already exists.
To make java more memory efficient JVM provide a special area of memory i.e “ String constant pool”.
If it exists or you can say match is found then the reference to the new literal is directed to the existing String and no new String literal object is created.( The existing String simply has an additional reference )
So basically it search in String pool (a cache of String object in Perm gen space, which is now moved to heap space in recent Java release), Otherwise it will create a new string object and put in string pool for future re-use.
From Java 7 onwards, the Java String Pool is stored in the Heap space, which is garbage collected by the JVMThe advantage of this approach is the reduced risk of OutOfMemory error because unreferenced Strings will be removed from the pool, thereby releasing memory.
WHY STRING IS IMMUTABLE OR FINAL?? 
If more than one reference variable refer to the one or same String, and any bad programer by mistake or knowingly change the value of String then what will happen?? oopsss..
Thanks my string is final.. 
Or some one override the string class functionality, couldn't that cause problem in the pool??
Well that one of the best reason String marked as a Final. 
Still confused with String Literal pool??

No comments:

Post a Comment