Skip to main content

Command Palette

Search for a command to run...

Strings in Java

Updated
•6 min read•View as Markdown
M
Product Engineer with 3.4 years of experience in Java, Spring Boot, React, Vue, SQL, AWS, and Warehouse Management Systems. Passionate about backend development and software engineering.

Introduction

A String in Java is one of the most commonly used data types. It represents a sequence of characters, such as words, sentences, or symbols. Strings are widely used to store and manipulate text data, including names, addresses, passwords, emails, messages, file paths, and much more.

In Java, the String class belongs to the java.lang package, which is automatically imported into every Java program. Unlike primitive data types (int, char, boolean, etc.), String is an object.

One of the unique characteristics of Java Strings is that they are immutable, meaning once a String object is created, its value cannot be changed.


Definition

A String is an object in Java that represents a sequence of Unicode characters enclosed within double quotation marks (").

Definition:

A String is an immutable object of the String class that stores a sequence of characters.


Why Do We Use Strings?

Strings are used whenever textual information needs to be stored or processed.

Examples include:

  • User names

  • Passwords

  • Email addresses

  • Phone numbers

  • File names

  • URLs

  • Messages

  • Product names

  • City names

Example:

String name = "John";
String city = "Chennai";
String email = "john@gmail.com";

Syntax

String name = "Java";

2. Using new Keyword

String language = new String("Java");

Both create String objects, but they are stored differently in memory.


Example Program

public class StringExample {

    public static void main(String[] args) {

        String language = "Java";

        System.out.println(language);

    }

}

Output

Java

Types of String Creation

There are mainly two ways to create Strings.


1. String Literal

String s1 = "Java";
String s2 = "Java";

Explanation

Java stores String literals inside the String Constant Pool (SCP).

Since "Java" already exists, both variables point to the same object.

s1  ----\
          ---> "Java"
s2  ----/

Advantages

  • Memory efficient

  • Faster comparison

  • Recommended approach


2. String Object (Using new)

String s1 = new String("Java");
String s2 = new String("Java");

Explanation

Each statement creates a new object in heap memory.

s1 ---> Object 1

s2 ---> Object 2

Although both contain the same value, they are different objects.


String Immutability

One of the most important interview concepts.

Example:

String s = "Java";

s = s.concat(" Programming");

System.out.println(s);

Output

Java Programming

What Happened?

The original String "Java" was not modified.

Instead, Java created a new String object.

Old Object

"Java"

↓

New Object

"Java Programming"

The old object becomes eligible for Garbage Collection if no longer referenced.


Why Strings are Immutable?

Java made Strings immutable because it improves:

  • Security

  • Thread Safety

  • Performance

  • String Pool Optimization

  • Hashcode Caching

This is one of the most frequently asked Java interview questions.


Common String Methods

length()

Returns the number of characters.

String s = "Java";

System.out.println(s.length());

Output

4

charAt()

Returns a character at a specific index.

String s = "Java";

System.out.println(s.charAt(2));

Output

v

toUpperCase()

String s = "java";

System.out.println(s.toUpperCase());

Output

JAVA

toLowerCase()

String s = "JAVA";

System.out.println(s.toLowerCase());

Output

java

equals()

Compares content.

String s1 = "Java";
String s2 = "Java";

System.out.println(s1.equals(s2));

Output

true

equalsIgnoreCase()

String s1 = "JAVA";
String s2 = "java";

System.out.println(s1.equalsIgnoreCase(s2));

Output

true

compareTo()

Lexicographically compares two strings.

String s1 = "Apple";
String s2 = "Banana";

System.out.println(s1.compareTo(s2));

Output

Negative Number

contains()

String s = "Java Programming";

System.out.println(s.contains("Java"));

Output

true

startsWith()

String s = "Java Programming";

System.out.println(s.startsWith("Java"));

Output

true

endsWith()

String s = "Java Programming";

System.out.println(s.endsWith("Programming"));

Output

true

substring()

String s = "JavaProgramming";

System.out.println(s.substring(4));

Output

Programming

replace()

String s = "Java";

System.out.println(s.replace("Java","Python"));

Output

Python

trim()

String s = " Java ";

System.out.println(s.trim());

Output

Java

split()

String s = "Java,Python,C++";

String[] arr = s.split(",");

for(String str : arr)
    System.out.println(str);

Output

Java
Python
C++

String Comparison

Using ==

Checks object reference.

String s1 = "Java";
String s2 = "Java";

System.out.println(s1 == s2);

Output

true

Using equals()

Checks actual content.

String s1 = new String("Java");
String s2 = new String("Java");

System.out.println(s1.equals(s2));

Output

true

StringBuilder

Used when frequent modifications are required.

StringBuilder sb = new StringBuilder("Java");

sb.append(" Programming");

System.out.println(sb);

Output

Java Programming

Advantages

  • Mutable

  • Faster than String for repeated modifications

  • Better performance


StringBuffer

Similar to StringBuilder but synchronized, making it thread-safe.

StringBuffer sb = new StringBuffer("Java");

sb.append(" Programming");

System.out.println(sb);

Output

Java Programming

String vs StringBuilder vs StringBuffer

Feature String StringBuilder StringBuffer
Mutable ❌ No ✅ Yes ✅ Yes
Thread Safe ❌ No ❌ No ✅ Yes
Performance Slow for modifications Fast Moderate
Memory More objects created Efficient Efficient

Best Practices

  • Prefer String literals over new String().

  • Use equals() for content comparison instead of ==.

  • Use StringBuilder for repeated string concatenation.

  • Avoid creating unnecessary String objects.

  • Remember that Strings are immutable.


Conclusion

Strings are one of the foundational concepts in Java and are used extensively in almost every application. Understanding how Strings are created, stored, compared, and manipulated is essential for writing efficient and reliable Java programs. Concepts such as the String Constant Pool, immutability, and the differences between String, StringBuilder, and StringBuffer are particularly important for coding interviews and real-world development. By mastering these concepts and using the appropriate class for each scenario, you can write cleaner, faster, and more maintainable Java code.