C

Core Java tutorial for beginners

Clean • Professional

Core Java Strings – Methods and Immutable Nature Explained

4 minute

Strings in Java & String Methods with Immutable Nature

Strings are one of the most commonly used data types in Java. They allow you to store and manipulate sequences of characters, such as names, messages, or any text data. Understanding strings and their methods is crucial for writing efficient Java programs.

Strings are one of the most commonly used data types in Java. They allow you to store and manipulate sequences of characters, such as names, messages, or any text data.


What is a String in Java?

  • A String in Java is an object that represents a sequence of characters.
  • Strings are immutable, meaning once created, their value cannot be changed.
  • Strings belong to the java.lang package, so you don’t need to import anything to use them.

Example:

String name = "John";
System.out.println("Name: " + name);

Output:

Name: John

String Declaration and Initialization

There are two main ways to create strings:

learn code with durgesh images

  1. Using String Literal
String message = "Hello Java";
  1. Using new Keyword
String message = new String("Hello Java");

Note : String literals are stored in the String Pool to save memory. Using new creates a new object in the heap every time.


String Characteristics

FeatureDescription
ImmutableStrings cannot be modified after creation
IndexedCharacters in a string are indexed from 0
ObjectStrings are objects, not primitive data types
MethodsStrings have many built-in methods for manipulation

Common String Methods

MethodDescriptionExample
length()Returns the number of characters"Java".length() → 4
charAt(int index)Returns character at specified index"Java".charAt(2) → 'v'
concat(String s)Concatenates another string"Java".concat(" Programming") → "Java Programming"
toUpperCase()Converts to uppercase"java".toUpperCase() → "JAVA"
toLowerCase()Converts to lowercase"JAVA".toLowerCase() → "java"
equals(String s)Compares two strings"Java".equals("java") → false
equalsIgnoreCase(String s)Compares ignoring case"Java".equalsIgnoreCase("java") → true
substring(int start, int end)Extracts substring"Java".substring(1,3) → "av"
trim()Removes leading and trailing spaces" Java ".trim() → "Java"
replace(char old, char new)Replaces character"Java".replace('a','o') → "Jovo"

Immutable Nature of Strings

  • Immutable: Once a string is created, it cannot be modified.
  • Any operation on a string returns a new string object.

Example:

String str = "Java";
String newStr = str.concat(" Programming");

System.out.println(str);    // Java
System.out.println(newStr); // Java Programming

Why Strings Are Immutable

  1. Security: Strings are used in sensitive operations (e.g., passwords, file paths).
  2. Thread-Safety: Immutable objects can be shared safely in multithreaded environments.
  3. Memory Efficiency: String Pool reuses immutable objects.
  4. Performance: Cached hashcode improves performance in collections like HashMap.

String Pool in Java

  • The String Pool is a special memory area for storing string literals.
  • Strings created using literals go into the pool.
  • Strings created with new do not go into the pool (stored in heap).

Example:

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

System.out.println(s1 == s2); // true, same object in pool
System.out.println(s1 == s3); // false, different objects

Practical Example

public class StringExample {
    public static void main(String[] args) {
        String firstName = "John";
        String lastName = "Doe";

        // Concatenation
        String fullName = firstName + " " + lastName;
        System.out.println("Full Name: " + fullName);

        // Length
        System.out.println("Length: " + fullName.length());

        // Substring
        System.out.println("First Name: " + fullName.substring(0, 4));

        // Uppercase
        System.out.println("Uppercase: " + fullName.toUpperCase());
    }
}

Output:

Full Name: John Doe
Length: 8
First Name: John
Uppercase: JOHN DOE

🏆 Top 5 Java Interview Questions - Java Strings & Methods

1. What is the difference between String, StringBuilder, and StringBuffer?

Answer:

FeatureStringStringBuilderStringBuffer
MutabilityImmutableMutableMutable
Thread SafetyNot thread-safe (immutable by default)Not synchronized, not thread-safeSynchronized, thread-safe
PerformanceSlower for concatenationFaster for concatenationSlightly slower than StringBuilder
UsageStore fixed stringsEfficient string modifications in a single threadEfficient string modifications in multi-threaded environment

Example:

String str = "Hello";          // immutable
StringBuilder sb = new StringBuilder("Hello"); // mutable
StringBuffer sbf = new StringBuffer("Hello");  // thread-safe

2. Why are strings immutable in Java?

Answer:

  • To improve security (e.g., for class loading, network connections).
  • To enable string sharing via the String Pool, saving memory.
  • To make thread-safe operations without explicit synchronization.
  • To allow hashCode caching for faster operations in collections like HashMap.

3. What is the String Pool?

Answer:

  • A special memory region in Heap where String literals are stored.
  • Strings in the pool are shared; duplicate literals point to the same object.
  • Helps reduce memory usage and improves performance.

Example:

String s1 = "Java";
String s2 = "Java";
System.out.println(s1 == s2); // true (same object in String Pool)

String s3 = new String("Java");
System.out.println(s1 == s3); // false (new object in Heap)

4. Difference between == and equals() for strings?

Answer:

  • == → Compares reference (memory address).
  • equals() → Compares content/value of the string.

Example:

String a = "Hello";
String b = new String("Hello");

System.out.println(a == b);      // false
System.out.println(a.equals(b)); // true

5. How do you concatenate strings in Java efficiently?

Answer:

  • For few concatenations, + operator is fine.
  • For multiple concatenations in loops, use StringBuilder or StringBuffer to avoid creating multiple immutable objects.

Example:

StringBuilder sb = new StringBuilder();
for(int i = 0; i < 5; i++) {
    sb.append(i).append(" ");
}
System.out.println(sb.toString()); // 0 1 2 3 4

 

Article 0 of 0