What are different ways to create String Object?

There are two ways to create a String object in Java

  1. By string literal
  2. By new keyword

1. Using String Literal

Java String literal is created by using double quotes.
For Example:
String s="javaguides";
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 a string doesn't exist in the pool, a new string instance is created and placed in the pool.
For example:
String s1="javaguides";
String s2="javaguides";
 //will not create new instance
To know more detail how the String Pool works on  Guide to Java String Constant Pool
Now the question is why java uses a concept of a string literal?
It's simple, to make Java more memory efficient (because no new objects are created if it exists already in string constant pool).

2. Using a new Keyword

Let's create a simple example to demonstrate by creating String objects using the new keyword.
public static void main(String[] args) {
    String str = new String("Java Guides");
     // create String object using new Keyword
    int length = str.length();
    System.out.println(" length of the string '" + str + "' is :: " + length);
}

Output:
 length of the string 'Java Guides' is:: 11 
From the above example, JVM will create a new string object in normal(non-pool) heap memory and the literal "Java Guides" will be placed in the string constant pool. The variable str will refer to the object in heap(non-pool).
To create a String initialized by an array of characters, Here is an example:
char chars[] = {
    'a',
    'b',
    'c'
}

;
String s = new String(chars);
Let's learn the String in depth by exploring all the String APIs with examples.

Comments