Develofer Develofer - 9 months ago 69
Java Question

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 be added to String pool or will it create an object in the heap?

Answer Source

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.