🧰 Java Basics to Intermediate
Estimated reading: 4 minutes 52 views

🔤 Java Strings – The Complete Guide with Examples & Explanations (2025)


🧲 Introduction – Why Java Strings Are Crucial

Strings in Java are everywhere — from reading input to printing output, handling URLs, parsing JSON, and building dynamic applications. Mastering String operations is essential for every Java developer.

By the end of this guide, you’ll learn:

🔹 What Java Strings are and how they work internally
🔹 How to create, compare, and manipulate strings
🔹 Important String methods with examples
🔹 Best practices for immutability and performance

Let’s unravel the power of strings in Java! 🎯


🔑 What is a String in Java?

In Java, a String is an object that represents a sequence of characters. It is defined in the java.lang package and is immutable, meaning once a string is created, it cannot be changed.

String greeting = "Hello, Java!";

Explanation:

  • "Hello, Java!" is a string literal.
  • Stored in the String pool for memory optimization.
  • greeting references the String object.

🏗️ How to Create Strings

1️⃣ Using String Literal

String name = "Java";

✅ Stored in the string pool — avoids duplication.

2️⃣ Using new Keyword

String name = new String("Java");

✅ Creates a new object in the heap even if it already exists in the pool.

⚠️ Prefer literals over new for memory efficiency.


⚙️ Common String Methods

MethodDescriptionExample
length()Returns length of the string"Java".length()4
charAt(index)Character at given index"Java".charAt(1)'a'
substring(begin, end)Extracts substring"Java".substring(1,3)"av"
contains(str)Checks if string contains substring"Java".contains("va")true
equals(str)Compares content"Java".equals("java")false
equalsIgnoreCase(str)Compares ignoring case"Java".equalsIgnoreCase("java")true
indexOf(char)Returns index of first occurrence"Java".indexOf('v')2
toLowerCase()Converts to lowercase"Java".toLowerCase()"java"
toUpperCase()Converts to uppercase"Java".toUpperCase()"JAVA"
trim()Removes whitespace from ends" Java ".trim()"Java"
replace(a, b)Replaces characters"Java".replace('a','o')"Jovo"

🧪 Java String Examples

🔁 Concatenation

String first = "Hello";
String second = "World";
String result = first + " " + second;
System.out.println(result); // Hello World

✅ Uses + operator to join strings.

📘 You can also use concat() method.


🆚 Comparing Strings

String a = "Java";
String b = "Java";
String c = new String("Java");

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

== checks reference; equals() checks value.

⚠️ Use equals() for content comparison.


🔄 Substring and Indexing

String text = "Programming";
System.out.println(text.substring(3, 6)); // "gra"
System.out.println(text.indexOf('g'));   // 3

✅ Great for string slicing or pattern matching.


🔧 StringBuilder for Efficiency

StringBuilder sb = new StringBuilder();
sb.append("Java").append(" ").append("Rocks!");
System.out.println(sb.toString()); // Java Rocks!

StringBuilder is mutable and faster for large string manipulations.

📘 Prefer it inside loops or dynamic concatenation.


📦 String Immutability in Java

Java strings are immutable by design:

String original = "Hello";
original.concat(" World");
System.out.println(original); // Hello

✅ A new object is created, but not stored unless assigned.

💡 Use StringBuilder or StringBuffer when mutability is needed.


📊 Memory Management – String Pool

Java maintains a String Constant Pool to reuse common string literals:

String x = "Test";
String y = "Test";
System.out.println(x == y); // true (same reference)

📘 Interning improves performance and saves memory.


🧹 Best Practices for Working with Strings

💡 Prefer String literals when possible.
💡 Avoid == for content comparison.
💡 Use StringBuilder for concatenation in loops.
💡 Always trim() inputs from user forms.
💡 Use .equalsIgnoreCase() for case-insensitive checks.


✅ Summary

  • Strings are a core part of Java and are immutable objects.
  • Java provides many built-in methods for manipulation.
  • Use equals() for comparison and StringBuilder for performance.
  • Understand how the string pool optimizes memory.

❓ FAQ – Java Strings

❓ Are Java Strings mutable or immutable?
Java Strings are immutable. Once created, their value cannot be changed.

❓ How is StringBuilder different from String?
StringBuilder is mutable and more efficient for repeated modifications, unlike String which creates new objects for each change.

❓ What is the use of the string pool in Java?
The String pool saves memory by storing only one copy of each literal string.

❓ How do I compare two strings in Java?
Use equals() for content comparison. Use == only when you need to compare object references.

❓ What’s the difference between substring(3) and substring(3, 6)?

  • substring(3) returns the string from index 3 to end.
  • substring(3, 6) returns from index 3 up to index 6 (excluding 6).

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Java Strings

Or Copy Link

CONTENTS
Scroll to Top