0 votes
in JAVA by
How many ways can we create the string object?

1 Answer

0 votes
by

1) String Literal

Java String literal is created by using double quotes. For Example:

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 the string doesn't exist in the pool, a new string instance is created and placed in the pool. String objects are stored in a special memory area known as the string constant pool For example:

String s1="Welcome";  

String s2="Welcome";//It doesn't create a new instance  

2) By new keyword

String s=new String("Welcome");//creates two objects and one reference variable  

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 constant string pool. The variable s will refer to the object in a heap (non-pool).

Related questions

0 votes
asked Apr 9, 2021 in JAVA by Robindeniel
+1 vote
asked Jan 24, 2020 in JAVA by rahuljain1
...