Java Strings

Last Updated : 2 Oct 2026

In Java, string is basically an object that represents sequence of char values. An array of characters works as a string in Java. For example:

is same as:

What is String in Java?

Generally, a String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The String class belongs to the java.lang package that is used to create a string object. Note that Java Strings are immutable that means their values cannot be changed once created.

There are the following two ways to create String object:

  1. Using String Literal
  2. Using new Keyword

1) Using String Literal

Java String literal is created by writing the string enclosed in double quotes. For Example:

Whenever we create a string literal, the JVM first checks the "string constant pool". If the string already exists in the pool, a reference to the pooled instance is returned. If the string does not exist in the pool, a new string instance is created and placed in the pool. For example:


Java String

In the above example, only one object will be created. First, JVM check for the string “Welcome”, the string does not exist in the string constant pool. So, it creates a new object for the string. For the second string, JVM checks for the string exists or not, the string exists in the string constant pool. In this case, new object will not be created. Instead of creating new object, the string constant pool returns the reference to the same instance

Example

Compile and Run

Output:

Welcome Welcome

Note: String objects are stored in a special memory area known as the "string constant pool". It makes the memory more efficient.

2) Using new Keyword

In the above syntax:

  • "Welcome" is a string literal, so it is stored in the string pool (one object).
  • new String("Welcome") creates a new String object in the heap (second object).
  • s is the reference variable that points to the object in the heap.

In such case, JVM creates a new string object in normal (non-pool) heap memory, and the literal "Welcome" placed in the string constant pool. The variable s refers to the object in a heap (non-pool).

Example

Compile and Run

Output:

Welcome Welcome

Java String Class

In Java, String is a basic data type represented by the String class.

Characteristics of the String Class

  1. Immutability: Once instantiated, a String object cannot be modified. This immutable design is a deliberate choice to ensure thread safety, consistency, and efficiency, especially regarding the String pool mechanism.
  2. String Pool: Java maintains a pool of string literals to help save memory. When a new string literal is created, Java checks the Pool for a matching string. If found, the new variable references the pooled string. If not, the new string is added to the Pool.
  3. Implemented Interfaces: The java.lang.String class implements Serializable, Comparable, and CharSequence interfaces.
String in Java

Serializable: It allows string objects to be serialized into byte streams, facilitating their transmission or storage.

Comparable<String>: It enables lexical comparison between two strings, supporting natural ordering within collections.

CharSequence Interface: The CharSequence interface is used to represent the sequence of characters. The String, StringBuffer, and StringBuilder classes implement it. It means, we can create strings by using the following three classes.

CharSequence in Java

The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created. For mutable strings, Java provides StringBuffer and StringBuilder classes.

String

In Java, the String class encapsulates a series of characters. Once instantiated, a String object's content is fixed and cannot be modified, attributed to its immutable nature. This immutability ensures that String objects are safe for concurrent use across threads and are optimally performant in situations where the textual content remains constant. To enhance memory efficiency, Java employs a technique called string interning. The approach optimizes the storage and access of commonly utilized string literals.

Syntax:

Using the String Constructor

Example

public class Main {  
    public static void main(String[] args) {  
        // Creating a String  
        String greeting = "Hello";  
        // Concatenating strings  
        String sentence = greeting + ", World!";  
        // Using a method from the String class  
        int length = sentence.length();  
        System.out.println(sentence); // Output: Hello, World!  
        System.out.println("Length: " + length); // Output: Length: 13  
    }  
}  
Compile and Run

Output:

Hello, World!
Length: 13

StringBuffer

StringBuffer represents a mutable sequence of characters that ensures thread safety, making it suitable for scenarios involving multiple threads that modify a character sequence. It includes various string manipulation capabilities, including the ability to insert, delete, and append characters. This design avoids the necessity of generating new objects with each change, leading to enhanced efficiency in situations requiring regular adjustments to the string content.

Syntax:

StringBuffer sb = new StringBuffer(); 

Example

public class Main {
    public static void main(String[] args) {
        // Creating a StringBuffer with initial content
        StringBuffer sb = new StringBuffer("Programming");
// Appending more text
        sb.append(" in Java");
 // Inserting text at a specific position
        sb.insert(0, "Welcome to ");
// Replacing a part of the text
        sb.replace(11, 22, "Coding");
 // Reversing the entire content
        sb.reverse();
// Displaying the final result
        System.out.println(sb);
    }
}
Compile and Run

Output:

avaJ ni gnidoC ot emoclew

StringBuilder

StringBuilder shares similarities with StringBuffer by being a mutable character sequence. The crucial distinction lies in StringBuilder not being synchronized, rendering it not suitable for thread-safe operations. This absence of synchronization, though, contributes to StringBuilder offering superior performance in environments that are single-threaded or confined to a specific thread. As a result, StringBuilder becomes the favored option for manipulating strings in contexts where the safety of concurrent thread access is not an issue.

Syntax:

StringBuilder sb = new StringBuilder();

Example

public class Main {  
    public static void main(String[] args) {  
        // Creating a StringBuilder  
        StringBuilder sb = new StringBuilder("Hello");  
        // Appending to the StringBuilder  
        sb.append(", World!");  
        // Inserting into the StringBuilder  
        sb.insert(5, " Java");  
        // Deleting from the StringBuilder  
        sb.delete(5, 10);  
        System.out.println(sb); // Output: Hello, World!  
    }  
}  
Compile and Run

Output:

Hello, World!

Java String Immutability

In Java, strings are immutable. It means that its value cannot be changed once a String object is created. If any operation appears to modify a String, what happens is the creation of a new String object. The original string remains unchanged. Immutability characteristic of strings has several implications for performance, security, and functionality.

Example: String Immutability

Java

Compile and Run

Output:

Original string: Java
After modification, original string: Java
Modified string: Java Programming
After calling toUpperCase on original string: Java
Original string in uppercase: JAVA

Memory Allotment of String

In Java, memory allocation for strings is influenced by immutability and the string pool.

String Literal Storage

When a string is created using a literal, Java first checks the string pool.

  • If the string already exists in the pool, the new reference points to the existing object.
  • If it does not exist, a new string object is created in the pool, and the reference points to it.

The mechanism helps to save memory and improves the performance, especially when the same strings are used multiple times in a program.

Syntax

It has the following syntax:

new Keyword and String Pool

Strings created with the new operator do not use the Pool by default. They are stored in the heap memory outside the Pool, which means each new operation results in a new object, even if it contains the same string data.

Syntax:

It has the following syntax:

Interning

We can manually add a string to the Pool or ensure it uses the Pool by calling the intern() method on a string object. If the Pool already contains an equal string, the string from the Pool is returned. Otherwise, the string is added to the Pool.

Syntax:

It has the following syntax:

Example: Demonstrating Memory Allotment of String

Java

Compile and Run

Output:

str1 == str2: true
str3 == str4: false
str1 == str5: true
str1 == str6: true

Construct String from a Subset of the char Array

We can create a string from a part of a character array using a special String constructor. We need to provide three things: the char array, the starting index, and the number of characters to include.

Syntax:

The method accepts the following parameters:

  • value: The char
  • offset: The initial offset into the array.
  • count: The number of characters to use from the array.

Example: Constructing String from Subset of Char Array

The following example demonstrates creating (constructing) a string from the subset of a character array.

Java

Compile and Run

Output:

World

Let’s see another example of Java String which is created using char[] array.

Example: Creating String Using Char[] Array

The following example demonstrates creating (constructing) a string from a character array (char[] Array).

Java

Compile and Run

Output:

java
strings
example

The above program, converts a char array into a String object. And displays the String objects s1, s2, and s3 on console using the println() method.