Thursday 8 December 2016

java - String Literal vs String Object




I read a lot about String Literal vs String Object. I read that String literal is stored in a String pool and String object will create an object in the heap. I'm quite confused in an instance variable of a class that is initialized using "".



class A {
private String aStr = "ASTRING";
}


Will aStr will be added to String pool or will it create an object in the heap?



Answer



Whenever new Keyword is used then object is created in heap.
Here new Keyword is not used so string object is created in string pool.
For example:



String s1= new String("string object");


In the above example two objects are being created one is string object in string pool since it is in double quotes another is s1 which is created in heap as new keyword is used.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...