Strings in Java
Introduction
In Java, the String class is one of the most commonly used classes, representing sequences of characters. Strings are immutable objects, which means once a String object is created, it cannot be changed. This immutability feature provides several advantages such as simplicity, security, and efficiency.
Creating Strings
Strings in Java can be created using literals or the new
keyword.
Using String Literals
When you create a string literal, the JVM checks if the same value already exists in the string pool. If it does, it reuses the existing instance.
1
2
3
4
5
6
7
8
public class Main {
public static void main(String[] args) {
String str1 = "Hello, World!";
String str2 = "Hello, World!";
System.out.println(str1 == str2); // Output: true
}
}
Using the new Keyword
Using the new
keyword creates a new String object in the heap memory.
1
2
3
4
5
6
7
8
public class Main {
public static void main(String[] args) {
String str1 = new String("Hello, World!");
String str2 = new String("Hello, World!");
System.out.println(str1 == str2); // Output: false
}
}
In this example, str1 and str2 are different objects even though they contain the same sequence of characters.
String Immutability
The immutability of strings means that once a String object is created, it cannot be modified. Any modification operations on strings actually result in the creation of new String objects.
1
2
3
4
5
6
7
8
9
public class Main {
public static void main(String[] args) {
String original = "Hello";
String modified = original.concat(", World!");
System.out.println(original); // Output: Hello
System.out.println(modified); // Output: Hello, World!
}
}
In this example, the concat method creates a new String object and does not modify the original string.
Common String Methods
Length
The length method returns the number of characters in a string.
1
2
3
4
5
6
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
System.out.println("Length: " + str.length()); // Output: Length: 13
}
}
CharAt
The charAt method returns the character at a specified index.
1
2
3
4
5
6
public class Main {
public static void main(String[] args) {
String str = "Hello";
System.out.println("Character at index 1: " + str.charAt(1)); // Output: Character at index 1: e
}
}
Substring
The substring method extracts a substring from the string.
1
2
3
4
5
6
7
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
System.out.println(str.substring(7)); // Output: World!
System.out.println(str.substring(0, 5)); // Output: Hello
}
}
Equals
The equals method checks if two strings have the same value.
1
2
3
4
5
6
7
8
9
10
public class Main {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
System.out.println(str1.equals(str2)); // Output: true
System.out.println(str1.equals(str3)); // Output: true
}
}
CompareTo
The compareTo method compares two strings lexicographically.
1
2
3
4
5
6
7
8
public class Main {
public static void main(String[] args) {
String str1 = "apple";
String str2 = "banana";
System.out.println(str1.compareTo(str2)); // Output: negative value (because "apple" is less than "banana")
}
}
ToLowerCase and ToUpperCase
These methods convert the string to lower case or upper case.
1
2
3
4
5
6
7
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
System.out.println(str.toLowerCase()); // Output: hello, world!
System.out.println(str.toUpperCase()); // Output: HELLO, WORLD!
}
}
Replace
The replace method replaces all occurrences of a specified character or substring with another character or substring.
1
2
3
4
5
6
7
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
System.out.println(str.replace('o', '0')); // Output: Hell0, W0rld!
System.out.println(str.replace("World", "Java")); // Output: Hello, Java!
}
}
Trim
The trim method removes whitespace from both ends of a string.
1
2
3
4
5
6
public class Main {
public static void main(String[] args) {
String str = " Hello, World! ";
System.out.println(str.trim()); // Output: Hello, World!
}
}
StringBuilder and StringBuffer
For scenarios where you need to modify strings frequently, using StringBuilder or StringBuffer is more efficient than using the String class. These classes provide mutable sequences of characters.
StringBuilder Example
1
2
3
4
5
6
7
8
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
sb.append(", World!");
System.out.println(sb.toString()); // Output: Hello, World!
}
}
StringBuffer Example
StringBuffer is similar to StringBuilder but is thread-safe.
1
2
3
4
5
6
7
8
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.append(", World!");
System.out.println(sb.toString()); // Output: Hello, World!
}
}
Conclusion
The String class in Java is fundamental for handling text. Its immutability offers numerous benefits, including simplicity and security, but it can also lead to performance issues if not used correctly. For scenarios requiring frequent modifications, StringBuilder or StringBuffer should be used. Understanding the capabilities and limitations of the String class is essential for efficient and effective Java programming.