Home > DeveloperSection > Interviews > How many ways we can create the string object?

Posted on    April-25-2015 12:20 AM

 Java Java  String 
 1 Answer(s)
  984  View(s)
Rate this:

Mayank Tripathi
Mayank Tripathi

Total Post:807

Posted on    April-25-2015 12:20 AM

There are two ways to create String object:
1)By string literal
String s="welcome"; 
Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and placed in the pool.

2)By new keyword
In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non pool).

String s=new String("Welcome")

Don't want to miss updates? Please click the below button!

Follow MindStick