The String class in Java is one of the most commonly used classes in the Java Standard Library. It’s part of the java.lang package, and it represents sequences of characters. Here’s an overview of its key features, properties, and common methods:
Key Features of the String Class:
- Immutable:
- Strings in Java are immutable, meaning once a String object is created, its content cannot be changed. Any operation that appears to modify a string actually creates a new String object.
- Example:
String s1 = “Hello”;
s1.concat(” World”); // This does not modify s1
System.out.println(s1); // Outputs: Hello
- Interning:
- Java uses a string pool to store string literals. If two string literals have the same content, they will point to the same memory location in the pool. This optimizes memory usage.
- Example:
String s1 = “Java”;
String s2 = “Java”;
System.out.println(s1 == s2); // true, because both point to the same object in the pool
- Implements CharSequence:
- String implements the CharSequence interface, which provides methods like length(), charAt(int index), subSequence(int start, int end), etc.
Commonly Used Constructors:
- Default Constructor:
- Example: String s = new String();
- String from char[]:
- Example: String s = new String(charArray);
- String from byte[]:
- Example: String s = new String(byteArray);
Popular Methods in the String Class:
- Basic Operations:
- length(): Returns the length of the string.
String s = “Hello”;
System.out.println(s.length()); // Outputs: 5
- charAt(int index): Retrieves the character at a specific index.
System.out.println(s.charAt(1)); // Outputs: e
- substring(int beginIndex, int endIndex): Extracts a portion of the string.
System.out.println(s.substring(1, 4)); // Outputs: ell
- Comparison:
- equals(Object obj): Compares the content of two strings.
- compareTo(String anotherString): Lexicographically compares two strings.
- equalsIgnoreCase(String anotherString): Compares strings ignoring case differences.
- Searching:
- indexOf(String str): Finds the first occurrence of a substring.
- lastIndexOf(String str): Finds the last occurrence of a substring.
- Manipulation:
- toUpperCase(), toLowerCase(): Converts the string to upper or lower case.
- trim(): Removes leading and trailing spaces.
- replace(char oldChar, char newChar): Replaces all occurrences of a character.
- Splitting and Joining:
- split(String regex): Splits the string based on a regex.
- join(CharSequence delimiter, CharSequence… elements): Joins multiple strings.
Performance Considerations:
- Using String vs StringBuilder or StringBuffer:
- Since String is immutable, concatenating strings using the + operator repeatedly can create many temporary objects, which affects performance.
- Use StringBuilder (non-thread-safe) or StringBuffer (thread-safe) for efficient string manipulation.
- String Pool:
- Strings created using literals are stored in the pool. Strings created using the new keyword are stored in heap memory and are not automatically interned.
String s1 = “Java”; // Interned
String s2 = new String(“Java”); // Not interned
System.out.println(s1 == s2); // false
Example Program:
public class StringExample {
public static void main(String[] args) {
String s1 = “Java”;
String s2 = “Programming”;
// Concatenation
String s3 = s1 + ” ” + s2;
System.out.println(s3); // Output: Java Programming
// Length and character access
System.out.println(“Length: ” + s3.length()); // Output: 16
System.out.println(“Character at index 5: ” + s3.charAt(5)); // Output: P
// Substring and replace
String s4 = s3.substring(5, 16);
System.out.println(“Substring: ” + s4); // Output: Programming
System.out.println(“Replace: ” + s3.replace(“Java”, “Kotlin”)); // Output: Kotlin Programming
// String comparison
String s5 = “java”;
System.out.println(s1.equalsIgnoreCase(s5)); // true
}
}