String in Java?

🧵 What is a String in Java?

In Java, a String is a sequence of characters treated as an object of the class java.lang.String.

✅ Strings are immutable, meaning once created, they cannot be changed.


✅ Creating Strings

🔹 Using string literal (recommended):

String s1 = "Hello";

🔸 Using new keyword (creates new object):

String s2 = new String("Hello");

🔁 "Hello" in literal form goes into the String pool.
new String() creates a new object in the heap, even if the value is the same.


🧠 Why Strings are Immutable?

  • Security (e.g., for URLs, file paths)
  • String pool optimization
  • Thread safety
  • Caching of hashCode()

🔧 Common String Methods

Method Description
length() Returns length of string
charAt(int index) Returns character at given index
substring(int start, int end) Returns part of the string
toLowerCase() / toUpperCase() Changes case
equals() Compares content
equalsIgnoreCase() Compares content, ignoring case
compareTo() Lexicographical comparison
contains(String s) Checks if string contains a substring
replace(a, b) Replaces all occurrences of a with b
trim() Removes leading/trailing spaces
split(String regex) Splits string into array

🧪 Example:

public class StringDemo {
    public static void main(String[] args) {
        String name = "Java Programming";

        System.out.println(name.length());         // 16
        System.out.println(name.charAt(5));         // P
        System.out.println(name.substring(5));      // Programming
        System.out.println(name.toUpperCase());     // JAVA PROGRAMMING
        System.out.println(name.contains("Java"));  // true
    }
}


⚠️ Comparing Strings:

❌ Don’t use == (compares reference)

String a = new String("Hello");
String b = new String("Hello");
System.out.println(a == b); // false

✅ Use equals() (compares value)

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

🧵 String Pool:

Java maintains a String constant pool to save memory.
When you create a string literal, it's stored in a pool and reused.


✅ Summary:

Feature Value
Class name String
Package java.lang
Mutable? ❌ Immutable
Stored in Heap + String pool
Common use cases Text handling, comparison, formatting

 

📦 String vs StringBuilder vs StringBuffer

 

📦 Quick Overview

Feature String StringBuilder StringBuffer
Mutability ❌ Immutable ✅ Mutable ✅ Mutable
Thread-safe ❌ No ❌ No ✅ Yes
Performance 🐢 Slow (creates new) ⚡ Fastest (no sync) ⚡ Fast (sync overhead)
Use Case Fixed text, safe Fast in single-thread Safe in multi-thread
Introduced in JDK 1.0 JDK 1.5 JDK 1.0

🧠 Detailed Differences

🔹 1. String – Immutable

  • Once created, its value cannot be changed
  • Any operation (like concat) creates a new object
  • Stored in the String Pool if created as a literal
String s = "Java";
s = s.concat(" World"); // New object created

🔸 2. StringBuilder – Mutable (Not Thread-Safe)

  • Designed for faster string manipulation in single-threaded contexts
  • No synchronization → better performance
StringBuilder sb = new StringBuilder("Java");
sb.append(" World");
System.out.println(sb); // Java World

🔸 3. StringBuffer – Mutable (Thread-Safe)

  • All methods are synchronized
  • Safe to use in multi-threaded environments
  • Slightly slower due to overhead
StringBuffer sbf = new StringBuffer("Java");
sbf.append(" World");
System.out.println(sbf); // Java World

📊 Comparison Table

Feature String StringBuilder StringBuffer
Immutable ✅ Yes ❌ No ❌ No
Thread-safe ❌ No ❌ No ✅ Yes
Performance (single) 🐢 Slow ⚡ Fastest ⚡ Fast (but slower)
Performance (multi) ❌ Not suitable ❌ Not safe ✅ Suitable
Use-case Constants, keys High-speed editing Multi-threaded safety

🧪 Real-life Use Cases

Scenario Recommended Class
Constant text or keys String
Fast editing in a loop (e.g., XML) StringBuilder
Safe logging in multi-thread app StringBuffer
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.