String in Java

  • Post author:
  • Post category:Java
  • Post comments:0 Comments

🧠 Java String – Complete Notes

📘 Basics

In Java, String is a class in the java.lang package.

Immutable – Once created, it cannot be changed.

Internally uses:

char[] before Java 9

byte[] from Java 9 onwards

Stored in the String Constant Pool (SCP) when created with literals.

Created with new String() → stored in heap memory.

Java String
Java String

💡 Why Immutability is Important

1. Security: Used in passwords, network connections, etc.

2. Caching: String literals can be reused from the SCP.

3. Thread Safety: Immutable objects are inherently thread-safe.

4. Hashing: Strings are often used as keys in maps.

Immutability ensures consistent hash values.

⚖️ Comparison

Feature String StringBuffer StringBuilder

Mutability Immutable Mutable Mutable
Thread Safety Thread-safe Thread-safe Not Thread-safe
Performance Slower Faster Fastest

🧩 Code Example

String s = "Nimai";
s.concat("Pradhan");
System.out.println(s); // Nimai(unchanged)

StringBuilder sb = new StringBuilder("Nimai");
sb.append("Pradhan");
System.out.println(sb); // NimaiPradhan

🔍 String Constant Pool Example

String a = "Nimai";
String b = "Nimai";
System.out.println(a == b); // true (same SCP reference)

String c = new String("Nimai");
System.out.println(a == c); // false (different object in heap)

 

🧠 How to Force Heap String into SCP

Use the intern() method:

String c = new String("Nimai");
String d = c.intern();
System.out.println(a == d); // true (now points to SCP reference)

 

⚙️ How hashCode() and equals() Work in String

hashCode() in String is overridden to ensure that two strings with same characters return the same hash value.

This is important for performance in hash-based collections.

Example:

String a = "abc";
String b = "abc";
System.out.println(a.hashCode() == b.hashCode()); // true

 

❗ What If hashCode() Wasn’t Overridden?

Different objects with the same content could end up in different buckets,
leading to inefficient hashing.

String Having some methods which is frequently used-

length(),charAt(),substring(),indexof(),equals(),equalsIgnoreCase(),
toUpperCase(),toLowerCase(),trim(),replace(),split()

Why String is final-

String class declared as final so that no can extend or change it ,so that we can achieve immutable feature.it also ensure it security, performance and consistency.

String.join() and String joiner java8 features

StringJoiner cp=new StringJoiner(",");
cp.add("Nima").add("Pradhan").add("Charan");
System.out.print(cp);// Nima, Pradhan, Charan

String results =String.join("-", "A" ,"Nima" ,"Pradhan");
System.out.print(results ); A-Nima-Pradhan

 

Leave a Reply