How many ways can we create the string object?

Solution:

1) String Literal

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

  1. 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:

  1. String s1="Welcome";
  2. String s2="Welcome";//It doesn't create a new instance

2) By new keyword

  1. 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).

0 answers