Skip to content
Related Articles

Related Articles

Strings in Java

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 22 Oct, 2022
Improve Article
Save Article

In the given example only one object will be created. Firstly JVM will not find any string object with the value “Welcome” in the string constant pool, so it will create a new object. After that it will find the string with the value “Welcome” in the pool, it will not create a new object but will return the reference to the same instance.

Note: String objects are stored in a special memory area known as string constant pool.

Why Java uses the concept of string literal?

To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool). 

Using new keyword

  • String s = new String(“Welcome”);
  • In such a 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 the heap (non-pool).

Syntax:  

<String_Type> <string_variable> = "<sequence_of_string>"; 

Example:  

String str = "Geeks";

Example:

Java




public class StringExample {
    public static void main(String args[])
    {
        String s1 = new String("example");
        // creating java string by new keyword
        // this statement create two object i.e
        // first object is created in heap
        // memory area and second object is
        // create in String constant pool.
 
        System.out.println(s1);
    }
}


Output

example

Memory allotment of String

Whenever a String Object is created as a literal, the object will be created in the String constant pool. This allows JVM to optimize the initialization of String literal.

Example: 

String str = "Geeks";

The string can also be declared using a new operator i.e. dynamically allocated. In case of String are dynamically allocated they are assigned a new memory location in the heap. This string will not be added to String constant pool.

Example: 

String str = new String("Geeks");

If you want to store this string in the constant pool then you will need to “intern” it.

Example:

String internedString = str.intern(); 
// this will add the string to string constant pool.

It is preferred to use String literals as it allows JVM to optimize memory allocation.

An example that shows how to declare a String 

Java




// Java code to illustrate String
import java.io.*;
import java.lang.*;
 
class Test {
    public static void main(String[] args)
    {
        // Declare String without using new operator
        String s = "GeeksforGeeks";
 
        // Prints the String.
        System.out.println("String s = " + s);
 
        // Declare String using new operator
        String s1 = new String("GeeksforGeeks");
 
        // Prints the String.
        System.out.println("String s1 = " + s1);
    }
}


Output

String s = GeeksforGeeks
String s1 = GeeksforGeeks

Interfaces and Classes in Strings in Java

CharBuffer: This class implements the CharSequence interface. This class is used to allow character buffers to be used in place of CharSequences. An example of such usage is the regular-expression package java.util.regex.

String: It is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created.

Ways of Creating a String

There are two ways to create a string in Java: 

  • String Literal
  • Using new Keyword

String literal

String s = “GeeksforGeeks”;

Using new keyword

String s = new String (“GeeksforGeeks”);

StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences.

Syntax:

StringBuffer s = new StringBuffer("GeeksforGeeks");

StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternative to String Class, as it creates a mutable sequence of characters.

Syntax:

StringBuilder str = new StringBuilder();
str.append("GFG");

StringTokenizer class in Java is used to break a string into tokens. 

Example:

string tokenizer

A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed. A token is returned by taking a substring of the string that was used to create the StringTokenizer object.

StringJoiner is a class in java.util package which is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. Though this can also be with the help of StringBuilder class to append delimiter after each string, StringJoiner provides an easy way to do that without much code to write.

Syntax:

public StringJoiner(CharSequence delimiter)

Above we saw we can create a string by  String Literal. 

For ex- // String s=”Welcome”; 

Here the JVM checks the String Constant Pool. If the string does not exist, then a new string instance is created and placed in a pool. If the string exists, then it will not create a new object. Rather, it will return the reference to the same instance. The cache that stores these string instances is known as the String Constant pool or String Pool. In earlier versions of Java up to JDK 6 String pool was located inside PermGen(Permanent Generation) space. But in JDK 7 it is moved to the main heap area. 

Why did the String pool move from PermGen to the normal heap area? 

PermGen space is limited, the default size is just 64 MB. it was a problem with creating and storing too many string objects in PermGen space. That’s why the String pool was moved to a larger heap area. To make Java more memory efficient, the concept of string literal is used. By the use of the ‘new’ keyword, The JVM will create a new string object in the normal heap area even if the same string object is present in the string pool. 

For example:

String a=new String(“Bhubaneswar”)

Let us have a look at the concept with a java program and visualize the actual JVM memory structure: 

Program:

Java




class StringStorage {
    public static void main(String args[])
    {
        String s1 = "TAT";
        String s2 = "TAT";
        String s3 = new String("TAT");
        String s4 = new String("TAT");
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
        System.out.println(s4);
    }
}


Output

TAT
TAT
TAT
TAT
JVM Memory Area

 

Note: All objects in Java are stored in a heap. The reference variable is to the object stored in the stack area or they can be contained in other objects which puts them in the heap area also.

Example 1: 

Java




//Construct String from subset of char array
 
class GFG{
 
public static void main(String args[]){
byte ascii[]={71,70,71};
   
  String s1= new String(ascii);
  System.out.println(s1);
   
   String s2= new String(ascii,1,2);
  System.out.println(s2);
}
}


Output

GFG
FG

Example 2:

Java




// Construct one string from another
 
class GFG{
public static void main(String args[])
{
   
  char c[]={'G','f','g'};
   
  String s1=new String (c);
  String s2=new String (s1);
   
  System.out.println(s1);
  System.out.println(s2);
 
 
}
}


Output

Gfg
Gfg

Immutable String in Java

  • In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
  • Once a string object is created its data or state can’t be changed but a new string object is created.

Java




// Java Program to demonstrate Immutable String in Java
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        String s = "Sachin";
       
        // concat() method appends
        // the string at the end
        s.concat(" Tendulkar");
       
        // This will print Sachin
        // because strings are
        // immutable objects
        System.out.println(s);
    }
}


Output

Sachin

Here Sachin is not changed but a new object is created with “Sachin Tendulkar”. That is why a string is known as immutable.

As you can see in the given figure that two objects are created but s reference variable still refers to “Sachin” and not to “Sachin Tendulkar”.

But if we explicitly assign it to the reference variable, it will refer to the “Sachin Tendulkar” object.           

For Example:

Java




// Java Program to demonstrate Explicitly assigned strings
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        String s = "Sachin";
        s = s.concat(" Tendulkar");
        System.out.println(s);
    }
}


Output

Sachin Tendulkar

Why string objects are immutable in java?

Because java uses the concept of string literal. Suppose there are 5 reference variables, all referes to one object “sachin”. If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!