6.Q. How a String is stored in memory?

Category: JAVA STRING INTERVIEW QUESTIONS AND ANSWERS

String object of string class are stored in Heap memory, not in stack area. Let’s go deep into this topic. String object can be created in two ways i.e. 1. By using string literal 2. By using the ‘new’ keyword

String literal is created by using a double quote. While creating a string using string literal , the JVM checks the String in String Constant Pool. If the string doesnot exist then a new string instance is created and placed in the String constant pool. But if the same string is exist in the String Constant Pool , then it will not create a new String object , rather it will return the reference to the same instance . So Java compiler doesn’t allocate new memory for string literal if the same string is already present in the String Constant Pool, due to which creating string object using string literal is memory efficient. Earlier upto JDK 6 , String constant pool was located inside PermGen. But from JDK7 , String constant pool moved to Heap Area.

But if we create String object using a new keyword , then it creates a new reference of the object and store in Heap Area and Thus creating string object using new keyword is not memory efficient.

Leave a Reply

Your email address will not be published. Required fields are marked *