4.Q.HOW TO CREATE A STRING IN JAVA?

Category: JAVA STRING INTERVIEW QUESTIONS AND ANSWERS

A String can be created in two ways in Java:

  1. Through String Literal : Using String literal, one can create a string which is memory efficient because no new object is created if that string is already existed in the string constant pool.

Example:

String str=”Giftisincredible”;

2. Using new Keyword : A String can also be created using new keyword. While a String is created using new keyword, it creates a new object in heap memory , even if the same string already exists in the String constant pool.

While creating a String object using new keyword, one object is created in the heap memory, the string literal is stored in the string pool if the string is not already present in the string pool and the reference variable of that string object points to the heap object, not the string constant pool .

Example:

String str=new String(“Giftisincredible”);

Leave a Reply

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