Master Core Java Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

Strings in Java

Learn how Java represents text using String, how strings are created and compared, and how to use common String methods efficiently.

What is a String?

A String represents a sequence of characters. In Java, String is a class provided by the java.lang package.

Strings are objects, even though Java provides special syntax for creating them using string literals.

Java
String name = "CIIT";

System.out.println(name);

Creating Strings

Strings are commonly created using string literals.

Java
String language = "Java";

String message = "Welcome CIIT world 🌍..!";

A String can also be explicitly created using the constructor, although literals are normally preferred.

Java
String text = new String("Java");

String Immutability

Strings in Java are immutable. Once a String object is created, its character contents cannot be changed.

Java
String text = "CIIT";

text = text + " Institute";

System.out.println(text);

The original String object is not modified. A new String object is created for the concatenated result, and the variable is updated to reference it.

String Pool

Java maintains a special pool for string literals. Identical literals can share the same pooled String object.

Java
String first = "CIIT";

String second = "Institute";

System.out.println(first == second);
Output
true

The == comparison here checks whether the two variables refer to the same object.

Comparing Strings with equals()

Use equals() when you want to compare String contents.

Java
String first = "CIIT";

String second = new String("Institute");

System.out.println(first.equals(second));
Output
true

Case-Insensitive Comparison

Java
String first = "ciit";

String second = "INSTITUTE";

System.out.println(
    first.equalsIgnoreCase(second)
);
Output
true

String length()

The length() method returns the number of UTF-16 code units in the String.

Java
String text = "CIIT";

System.out.println(text.length());
Output
4

charAt()

The charAt() method returns the character at a specified zero-based index.

Java
String text = "Java";

System.out.println(text.charAt(0));

System.out.println(text.charAt(2));
Output
J
v

substring()

The substring() method extracts part of a String. The ending index is exclusive.

Java
String text = "Programming";

System.out.println(
    text.substring(0, 4)
);

System.out.println(
    text.substring(4)
);
Output
Prog
ramming

contains()

Java
String text = "Java Programming";

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

System.out.println(
    text.contains("Python")
);
Output
true
false

startsWith() and endsWith()

Java
String file = "report.pdf";

System.out.println(
    file.startsWith("report")
);

System.out.println(
    file.endsWith(".pdf")
);
Output
true
true

indexOf() and lastIndexOf()

Java
String text = "Java Programming";

System.out.println(
    text.indexOf("a")
);

System.out.println(
    text.lastIndexOf("a")
);

replace()

Since Strings are immutable, replace() returns a new String instead of modifying the original.

Java
String text = "Java is easy";

String updated =
    text.replace("easy", "powerful");

System.out.println(updated);
Output
Java is powerful

toLowerCase() and toUpperCase()

Java
String text = "Java Programming";

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

System.out.println(
    text.toUpperCase()
);
Output
java programming
JAVA PROGRAMMING

trim() and strip()

trim() removes certain leading and trailing characters with code points at or below U+0020. Modern Java also provides strip(), which uses Unicode-aware whitespace rules.

Java
String text = "   Java   ";

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

System.out.println(
    text.strip()
);

String Concatenation

Strings can be combined using the + operator.

Java
String firstName = "Samadhan";

String lastName = "Patole";

String fullName =
    firstName + " " + lastName;

System.out.println(fullName);

concat()

Java
String first = "CIIT";

String second = " Institute";

String result = first.concat(second);

System.out.println(result);

split()

The split() method divides a String according to a regular expression.

Java
String languages =
    "Java,Python,CSharp";

String[] values =
    languages.split(",");

for (String value : values) {

    System.out.println(value);

}
Output
Java
Python
CSharp

String.join()

String.join() can combine multiple strings using a delimiter.

Java
String result = String.join(
    ", ",
    "Java",
    "Python",
    "CSharp"
);

System.out.println(result);
Output
Java, Python, CSharp

String Formatting

String.format() creates formatted text using placeholders.

Java
String name = "Amit";

int age = 25;

String result = String.format(
    "Name: %s, Age: %d",
    name,
    age
);

System.out.println(result);
Output
Name: Amit, Age: 25

Text Blocks

Modern Java supports text blocks for convenient representation of multiline text.

Java
String message = """
        Hello
        Welcome to Java
        Programming
        """;

StringBuilder

When text needs to be modified repeatedly, use StringBuilder instead of creating many temporary String objects.

Java
StringBuilder builder =
    new StringBuilder();

builder.append("Java");
builder.append(" ");
builder.append("Programming");

System.out.println(
    builder.toString()
);
Output
Java Programming

StringBuffer

StringBuffer is another mutable character sequence. Its methods are synchronized, making it different from StringBuilder.

Java
StringBuffer buffer =
    new StringBuffer("Java");

buffer.append(" Programming");

System.out.println(buffer);

String vs StringBuilder vs StringBuffer

Feature String StringBuilder StringBuffer
Mutable No Yes Yes
Typical Use Fixed text Repeated text modification Mutable text with synchronized methods
Synchronization Immutable No Yes
Performance Good for immutable values Usually preferred for local mutable building More overhead than StringBuilder

Checking Empty and Blank Strings

Java
String text = "";

System.out.println(text.isEmpty());

String value = "   ";

System.out.println(value.isBlank());
Output
true
true

isEmpty() checks whether the String has zero characters. isBlank() also considers strings containing only whitespace to be blank.

String and null

A String variable can contain null, meaning it does not currently reference a String object.

Java
String text = null;

if (text != null) {

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

}
Important: Calling an instance method such as length() on a null reference causes NullPointerException.

String and Unicode

Java Strings use UTF-16 internally. Characters outside the Basic Multilingual Plane may require a surrogate pair, so char is not always equivalent to one Unicode code point.

Java
String text = "Hello";

System.out.println(
    text.codePointAt(0)
);

Example: Username Validation

Java
String username = "  Sam2210  ";

username = username.strip();

if (!username.isBlank()
        && username.length() >= 5) {

    System.out.println(
        "Valid username"
    );

} else {

    System.out.println(
        "Invalid username"
    );

}

String Best Practices

  • Use equals() for content comparison.
  • Avoid using == when your intention is to compare String contents.
  • Remember that Strings are immutable.
  • Use StringBuilder for repeated local string modifications.
  • Handle possible null references safely.
  • Use strip() when Unicode-aware whitespace handling is desired.

Interview Questions

String immutability supports safe sharing, predictable behavior, and enables optimizations such as string pooling.

For object references, == compares references, while equals() is used to compare logical content when the class implements it appropriately.

String is immutable. StringBuilder is mutable and is generally useful when repeatedly constructing or modifying text within a single thread.

It is the JVM's mechanism for sharing String literals so identical literals can reuse the same String object.

isEmpty() checks for zero length, while isBlank() also considers a string containing only whitespace to be blank.
Summary

Java Strings are immutable objects used to represent text. Important concepts include string literals, the String pool, content comparison with equals(), common String methods, Unicode handling, and mutable alternatives such as StringBuilder and StringBuffer.