Java Tutorial 0/145 lessons ~6 min read Lesson 16

    Strings

    java strings immutable string pool constant pool equals StringBuilder StringBuffer concat substring split trim interview

    Course progress0%
    Focus
    23 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    In the previous lessons, you learned about variables, arrays, methods, and Object-Oriented Programming. One of the most frequently used data types in Java applications is the String.

    Whether you're building a Spring Boot REST API, an e-commerce application, a banking system, or an Android app, you'll constantly work with strings to handle:

    • User names
    • Passwords
    • Email addresses
    • Product names
    • URLs
    • JSON/XML data
    • Log messages
    • SQL queries

    Although a String looks like a primitive data type, it is actually an object of the String class.

    Java Strings are immutable, meaning once a String object is created, its value cannot be changed.

    Understanding how Strings work internally is one of the most commonly tested topics in Java interviews.

    In this lesson, you'll learn:

    • What is a String?
    • String Creation
    • String Pool
    • String Immutability
    • String Methods
    • Comparing Strings
    • String Concatenation
    • Escape Characters
    • StringBuilder vs StringBuffer
    • String Performance
    • Real-world Examples
    • Best Practices
    • Common Mistakes
    • Hands-on Exercises
    • Professional Interview Questions

    What is a String?

    A String is a sequence of Unicode characters.

    Example:

    java
    String name = "Jagannath";

    Unlike primitive data types, a String is an object.

    Internally:

    java
    String name = new String("Jagannath");

    The first syntax is preferred because it uses the String Pool efficiently.

    Why Strings are Important

    Almost every Java application processes text.

    Examples:

    • Customer Name
    • Email Address
    • Password
    • Product Description
    • Search Keywords
    • File Names
    • JSON Responses
    • XML Documents

    Without Strings, modern applications would not be possible.

    Creating Strings

    Using String Literal

    java
    String city = "Hyderabad";

    Stored inside the String Constant Pool.

    Using new Keyword

    java
    String city = new String("Hyderabad");

    Creates a new object in heap memory regardless of whether the same value already exists.

    String Constant Pool

    The JVM maintains a special memory area called the String Constant Pool (SCP).

    Example:

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

    Memory:

    String Pool
    +--------+
    | Java |
    +--------+
    s1 ─┐
    ├──► "Java"
    s2 ─┘

    Only one object is created.

    Now:

    java
    String s3 = new String("Java");

    Memory:

    Heap
    s3 ─► New Object
    String Pool
    "Java"

    A new heap object is created in addition to the pooled literal.

    String Immutability

    Strings cannot be modified after creation.

    Example:

    java
    String language = "Java";
    language.concat(" Programming");
    System.out.println(language);

    Output:

    Java

    The original object remains unchanged because concat() returns a new String.

    Correct:

    java
    language = language.concat(" Programming");

    Output:

    Java Programming

    Why are Strings Immutable?

    Immutability provides:

    • Thread Safety
    • Security
    • Better Performance through String Pool
    • Reliable Hash Codes
    • Safe Class Loading

    Examples:

    • URLs
    • File Paths
    • Database Connections
    • Usernames
    • Class Names

    If Strings were mutable, many security vulnerabilities could occur.

    Comparing Strings

    Using ==

    java
    String s1 = "Java";
    String s2 = "Java";
    System.out.println(s1 == s2);

    Output:

    true

    Because both references point to the same pooled object.

    Using equals()

    java
    String a = new String("Java");
    String b = new String("Java");
    System.out.println(a.equals(b));

    Output:

    true

    equals() compares content, not object references.

    Why == Can Be Misleading

    java
    String a = new String("Java");
    String b = new String("Java");
    System.out.println(a == b);

    Output:

    false

    Because == compares memory references.

    Rule:

    • == → Reference Comparison
    • equals() → Content Comparison

    Common String Methods

    length()

    java
    String text = "Java";
    System.out.println(text.length());

    Output:

    4

    charAt()

    java
    String text = "Java";
    System.out.println(text.charAt(2));

    Output:

    v

    substring()

    java
    String text = "Programming";
    System.out.println(text.substring(3,7));

    Output:

    gram

    toUpperCase()

    java
    System.out.println("java".toUpperCase());

    Output:

    JAVA

    toLowerCase()

    java
    System.out.println("JAVA".toLowerCase());

    Output:

    java

    contains()

    java
    String email = "user@gmail.com";
    System.out.println(email.contains("@"));

    Output:

    true

    startsWith()

    java
    String url = "https://example.com";
    System.out.println(url.startsWith("https"));

    Output:

    true

    endsWith()

    java
    String file = "report.pdf";
    System.out.println(file.endsWith(".pdf"));

    Output:

    true

    replace()

    java
    String sentence = "Java is fun";
    System.out.println(sentence.replace("fun","powerful"));

    Output:

    Java is powerful

    split()

    java
    String csv = "Apple,Banana,Orange";
    String[] fruits = csv.split(",");

    Output:

    Apple
    Banana
    Orange

    trim()

    java
    String name = " Java ";
    System.out.println(name.trim());

    Output:

    Java

    Escape Characters

    EscapeMeaning
    \nNew Line
    \tTab
    \"Double Quote
    \\Backslash

    Example:

    java
    System.out.println("Java\nProgramming");

    Output:

    Java
    Programming

    String Concatenation

    Using +

    java
    String first = "Hello";
    String second = "Java";
    System.out.println(first + " " + second);

    Output:

    Hello Java

    StringBuilder

    For multiple string modifications, use StringBuilder.

    java
    StringBuilder sb = new StringBuilder("Java");
    sb.append(" Programming");
    System.out.println(sb);

    Output:

    Java Programming

    StringBuilder is mutable and faster than repeated String concatenation.

    StringBuffer

    java
    StringBuffer sb = new StringBuffer("Java");
    sb.append(" Programming");

    Difference:

    StringBuilderStringBuffer
    FasterSlower
    Not Thread-SafeThread-Safe
    Preferred in Single ThreadPreferred in Multi Thread

    String vs StringBuilder vs StringBuffer

    FeatureStringStringBuilderStringBuffer
    MutableNoYesYes
    Thread-SafeYes (Immutable)NoYes
    PerformanceSlower for repeated modificationsFastestSlightly slower

    Real-World Example: Email Validation

    java
    String email = "user@gmail.com";
    if(email.contains("@") && email.endsWith(".com")){
    System.out.println("Valid Email");
    }

    Real-World Example: Full Name

    java
    String firstName = "Jagannath";
    String lastName = "Mishra";
    String fullName = firstName + " " + lastName;
    System.out.println(fullName);

    Best Practices

    Use String Literals When Possible

    Prefer:

    java
    String language = "Java";

    Instead of:

    java
    String language = new String("Java");

    Use equals() for Comparison

    Never compare String contents using ==.

    Use StringBuilder for Repeated Modifications

    Avoid:

    java
    text = text + value;

    Inside loops.

    Check for Null Before Calling Methods

    java
    if(name != null){
    System.out.println(name.length());
    }

    Avoid Hardcoded Strings

    Store reusable constants in static final variables.

    Common Mistakes

    Using == Instead of equals()

    This compares references instead of content.

    Forgetting String Immutability

    Methods like concat(), replace(), and trim() return a new String.

    Excessive String Concatenation in Loops

    Use StringBuilder for better performance.

    Ignoring Case Sensitivity

    Use equalsIgnoreCase() when appropriate.

    Not Handling Null Values

    Calling methods on a null String results in a NullPointerException.

    Hands-on Exercise

    Create a Java program that:

    1. Creates Strings using literals and the new keyword.
    2. Demonstrates the String Constant Pool.
    3. Compares Strings using == and equals().
    4. Uses at least ten commonly used String methods.
    5. Reads a full name and prints initials.
    6. Validates an email address.
    7. Reverses a String using StringBuilder.
    8. Counts the number of words in a sentence.

    Summary

    Strings are among the most widely used objects in Java. Their immutability provides security, thread safety, and efficient memory usage through the String Constant Pool. Understanding String creation, comparison, common methods, and performance considerations is essential for writing robust Java applications.

    Key Takeaways

    • A String is an immutable object.
    • Prefer String literals to take advantage of the String Constant Pool.
    • Use equals() for content comparison.
    • == compares object references.
    • Common methods include length(), substring(), contains(), replace(), and split().
    • StringBuilder is ideal for repeated modifications.
    • StringBuffer provides thread-safe mutable strings.
    • String immutability improves security and performance.

    Professional Interview Questions

    1Why are Strings immutable in Java?

    Professional Answer

    Strings are immutable to ensure security, thread safety, efficient memory sharing through the String Constant Pool, and consistent hash codes. Immutability also prevents accidental modifications to critical values such as file paths, URLs, database connection strings, and class names.

    Follow-up Questions

    • How does immutability improve security?
    • Which other Java classes are immutable?

    Interview Tip: Mention both String Pool optimization and thread safety to demonstrate a deeper understanding.

    2What is the difference between == and equals() for Strings?

    Professional Answer

    The == operator compares object references to determine whether two references point to the same object in memory. The equals() method compares the actual sequence of characters stored in the strings. In most business applications, equals() should be used for String comparison.

    Follow-up Questions

    • When can == return true for two Strings?
    • What does equalsIgnoreCase() do?

    Interview Tip: Remember: == → Memory Reference, equals() → Content Comparison.

    3What is the difference between String, StringBuilder, and StringBuffer?

    Professional Answer

    String is immutable, making it safe and suitable for constant values. StringBuilder is mutable and offers better performance for repeated modifications in single-threaded applications. StringBuffer is also mutable but synchronizes its methods, making it thread-safe at the cost of some performance.

    Follow-up Questions

    • Why is StringBuilder faster than StringBuffer?
    • When would you choose StringBuffer?

    Interview Tip: String → Fixed text, StringBuilder → High-performance string manipulation, StringBuffer → Multi-threaded environments requiring thread safety.

    Ready to mark this lesson complete?Track your journey across the entire course.