Java Strings

Java Strings


What is a Java String? In Java, a string is an object that represents a sequence of characters or char values. The java.lang.String class is used to create a Java string object.

There are two ways to create a String object:

  1. By string literal : Java String literal is created by using double quotes.
    For Example: String s=“Welcome”;  
  2. By new keyword : Java String is created by using a keyword “new”.
    For example: String s=new String(“Welcome”);  
    It creates two objects (in String pool and in heap) and one reference variable where the variable ‘s’ will refer to the object in the heap.

 

Now, let us understand the concept of Java String pool.

Java String Pool: Java String pool refers to collection of Strings which are stored in heap memory. In this, whenever a new object is created, String pool first checks whether the object is already present in the pool or not. If it is present, then same reference is returned to the variable else new object will be created in the String pool and the respective reference will be returned. Refer to the diagrammatic representation for better understanding: