Introduction
In Java, a String is an object that represents a sequence of characters. Unlike primitive data types such as int, double, or char, a String belongs to the java.lang package and provides numerous built-in methods to manipulate text efficiently.
One of the unique features of Java Strings is that they are immutable, meaning once a String object is created, its value cannot be changed. This design improves security, thread safety, and performance.
What is a Java String?
A String is an object that stores a sequence of characters.
For example:
String name = "John";
Here, “John” is a String literal consisting of four characters.
Unlike arrays of characters, Java Strings provide many built-in methods for searching, comparing, replacing, trimming, splitting, and modifying text.
Why Are Strings Important?
Strings are used almost everywhere in Java applications.
Some common uses include:
- User names
- Passwords
- Email addresses
- File names
- URLs
- Product descriptions
- JSON and XML data
- Chat messages
- Database queries
Without Strings, text processing would be extremely difficult.
How to Create a String
There are two common ways to create a String.
1. Using String Literal (Recommended)
String language = "Java";
This is the most common and memory-efficient method.
2. Using the new Keyword
String language = new String("Java");
This creates a new String object in heap memory even if the same value already exists.
String Memory (String Pool)
Java optimizes memory by maintaining a special area called the String Pool.
Example:
String s1 = "Java";
String s2 = "Java";
Only one object is created because both variables reference the same String in the String Pool.
However,
String s3 = new String("Java");
creates a separate object in heap memory.
Diagram
String Pool
+---------+
| "Java" |
+---------+
↑ ↑
s1 s2
Heap
+---------+
| "Java" |
+---------+
↑
s3
The String Pool helps reduce memory usage by reusing identical String literals.
Why Are Strings Immutable?
In Java, Strings cannot be modified after creation.
Example:
String name = "Java";
name = "Python";
The original “Java” object remains unchanged. Instead, a new String object “Python” is created, and name now references the new object.
Benefits of Immutability
- Better security
- Thread safety
- Efficient memory usage
- String Pool optimization
- Reliable hash codes
String Example
public class Main {
public static void main(String[] args) {
String message = "Welcome to Java";
System.out.println(message);
}
}
Output
Accessing Characters
You can access individual characters using the charAt() method.
String language = "Java";
System.out.println(language.charAt(0));
System.out.println(language.charAt(2));
Output
v
Finding String Length
The length() method returns the number of characters.
String text = "Programming";
System.out.println(text.length());
Output
String Concatenation
Strings can be joined using the + operator.
String first = "Hello";
String second = "World";
String result = first + " " + second;
System.out.println(result);
Output
You can also use the concat() method.
String result = first.concat(second);
Converting Case
Uppercase
String text = "java";
System.out.println(text.toUpperCase());
Output
Lowercase
String text = "JAVA";
System.out.println(text.toLowerCase());
Output
Comparing Strings
There are multiple ways to compare Strings.
Using equals()
String s1 = "Java";
String s2 = "Java";
System.out.println(s1.equals(s2));
Output
Using equalsIgnoreCase()
String s1 = "JAVA";
String s2 = "java";
System.out.println(s1.equalsIgnoreCase(s2));
Output
Using compareTo()
String s1 = "Apple";
String s2 = "Banana";
System.out.println(s1.compareTo(s2));
A negative value means the first String comes before the second alphabetically.
Common String Methods
| Method | Description |
|---|---|
| length() | Returns String length |
| charAt() | Returns character at an index |
| substring() | Extracts part of a String |
| contains() | Checks whether text exists |
| equals() | Compares values |
| equalsIgnoreCase() | Ignores case during comparison |
| toUpperCase() | Converts to uppercase |
| toLowerCase() | Converts to lowercase |
| trim() | Removes leading and trailing spaces |
| replace() | Replaces characters or text |
| split() | Splits a String into an array |
| indexOf() | Finds the first occurrence of text |
| lastIndexOf() | Finds the last occurrence of text |
| startsWith() | Checks the prefix |
| endsWith() | Checks the suffix |
| Checks the suffixtd> | Checks whether the String is empty |
Example of Common Methods
public class Main {
public static void main(String[] args) {
String text = " Java Programming ";
System.out.println(text.trim());
System.out.println(text.length());
System.out.println(text.contains("Program"));
System.out.println(text.replace("Java", "Python"));
}
}
Output
18
true
Python Programming
Splitting a String
String colors = "Red,Green,Blue";
String[] list = colors.split(",");
for(String color : list)
{
System.out.println(color);
}
Output
Green
Blue
Searching Inside a String
String text = "Java Programming";
System.out.println(text.indexOf("Program"));
Output
String vs StringBuilder
| String | StringBuilder |
|---|---|
| Immutable | Mutable |
| Creates new object after modification | Modifies existing object |
| Slower for repeated changes) | Faster |
| Thread-safe due to immutability | Not synchronized |
| Suitable for fixed text | Suitable for dynamic text |
If you need to perform many concatenation or modification operations, use StringBuilder for better performance.
Real-Life Example
Suppose you are developing an online shopping application.
String customer = "Rahul";
String product = "Laptop";
System.out.println("Customer: " + customer);
System.out.println("Product: " + product);
Output
Product: Laptop
Strings are used to store customer names, product names, addresses, payment statuses, and order details.
Advantages of Java String
- Easy to use
- Immutable and secure
- Rich collection of built-in methods
- Supports Unicode characters
- Memory efficient through the String Pool
- Thread-safe
- Widely used in APIs and frameworks
Disadvantages of Java String
- Immutable nature may create additional objects during frequent modifications.
- Repeated concatenation can reduce performance.
- Consumes more memory if not used carefully.
For frequent modifications, StringBuilder or StringBuffer is usually a better choice.
Common Mistakes
1. Using == Instead of equals()
Incorrect:
String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1 == s2);
Output
Correct:
System.out.println(s1.equals(s2));
Output
== compares object references, whereas equals() compares the actual content.
2. Forgetting That Strings Are Immutable
Incorrect:
String text = "java";
text.toUpperCase();
System.out.println(text);
Output
Correct:
text = text.toUpperCase();
3. Ignoring Null Values
Calling methods on a null String causes a NullPointerException.
String name = null;
// name.length(); // Throws NullPointerException
Always validate or initialize Strings before using them.
Best Practices
- Use String literals whenever possible.
- Use equals() for content comparison.
- Prefer StringBuilder for repeated modifications.
- Avoid unnecessary object creation with new String().
- Trim user input before validation.
- Handle null values safely.
- Use meaningful variable names for better readability.
Conclusion
The Java String class is one of the most fundamental and widely used classes in Java programming. It provides a simple and efficient way to store, manipulate, compare, and process textual data. Features such as immutability, the String Pool, and a rich collection of built-in methods make Strings both secure and powerful.
Java String – Interview Questions
Q 1: What is String in Java?
Q 2: Are Java Strings mutable?
Q 3: Where are String objects stored?
Q 4: How can a String be created?
Q 5: Why are Strings immutable?
Java String – Objective Questions (MCQs)
Q1. In Java, a String is a:
Q2. Strings in Java are:
Q3. Which of the following is the correct way to create a String in Java?
Q4. Which operator is used to concatenate two strings in Java?