String
is one of the most widely used classes in Java. It represents a sequence of characters and is immutable, meaning once created, it cannot be changed. This blog will cover everything about String
in Java, including all available methods with explanations and examples.
1. Understanding Strings in Java
In Java, String
is a class in the java.lang
package. It is immutable and stored in the String Pool for optimization.
Creating a String
String s1 = "Hello"; // Using String literal (Stored in String Pool)
String s2 = new String("Hello"); // Using new keyword (Stored in Heap)
2. String Methods in Java
A. Basic Methods
1. length()
Returns the number of characters in the string.
String s = "Hello";
System.out.println(s.length()); // Output: 5
2. charAt(int index)
Returns the character at the specified index.
System.out.println(s.charAt(1)); // Output: 'e'
3. isEmpty()
Checks if the string is empty.
String s = "";
System.out.println(s.isEmpty()); // Output: true
4. isBlank()
(Java 11)
Checks if a string is empty or contains only whitespace.
String s = " ";
System.out.println(s.isBlank()); // Output: true
B. String Comparison Methods
5. equals(Object obj)
Compares two strings for equality.
String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1.equals(s2)); // Output: true
6. equalsIgnoreCase(String anotherString)
Compares two strings, ignoring case.
System.out.println("hello".equalsIgnoreCase("HELLO")); // Output: true
7. compareTo(String anotherString)
Compares two strings lexicographically.
System.out.println("apple".compareTo("banana")); // Output: -1
8. compareToIgnoreCase(String anotherString)
Compares two strings lexicographically, ignoring case.
System.out.println("Apple".compareToIgnoreCase("apple")); // Output: 0
C. Substring & Searching Methods
9. contains(CharSequence seq)
Checks if the string contains a given sequence.
System.out.println("Hello World".contains("World")); // Output: true
10. startsWith(String prefix)
& endsWith(String suffix)
Checks if the string starts or ends with a given substring.
System.out.println("Java".startsWith("J")); // Output: true
System.out.println("Java".endsWith("a")); // Output: true
11. indexOf(String str)
& lastIndexOf(String str)
Finds the index of a substring.
System.out.println("Hello World".indexOf("o")); // Output: 4
System.out.println("Hello World".lastIndexOf("o")); // Output: 7
12. substring(int beginIndex, int endIndex)
Extracts a substring from the string.
String str = "Hello World";
System.out.println(str.substring(0, 5)); // Output: Hello
D. String Modification Methods
13. toUpperCase()
& toLowerCase()
Converts the string to upper or lower case.
System.out.println("java".toUpperCase()); // Output: JAVA
System.out.println("JAVA".toLowerCase()); // Output: java
14. trim()
Removes leading and trailing spaces.
String s = " Java ";
System.out.println(s.trim()); // Output: "Java"
15. replace(char oldChar, char newChar)
Replaces all occurrences of a character.
System.out.println("banana".replace('a', 'o')); // Output: bonono
16. replaceAll(String regex, String replacement)
Replaces occurrences of a substring using regex.
System.out.println("Hello123".replaceAll("\\d", "")); // Output: Hello
17. repeat(int count)
(Java 11)
Repeats the string.
System.out.println("Hi ".repeat(3)); // Output: Hi Hi Hi
E. Splitting and Joining Strings
18. split(String regex)
Splits the string into an array.
String[] words = "Java,Python,C++".split(",");
System.out.println(Arrays.toString(words)); // Output: [Java, Python, C++]
19. join(CharSequence delimiter, CharSequence... elements)
Joins multiple strings with a delimiter.
String result = String.join("-", "Java", "Python", "C++");
System.out.println(result); // Output: Java-Python-C++
F. Converting and Formatting
20. valueOf(any data type)
Converts different data types into a string.
System.out.println(String.valueOf(123)); // Output: "123"
21. format(String format, Object... args)
Formats the string.
String formatted = String.format("Name: %s, Age: %d", "Alice", 25);
System.out.println(formatted); // Output: Name: Alice, Age: 25
G. String Handling in Java 8+
22. lines()
(Java 11)
Splits a string into lines.
"Hello\nWorld".lines().forEach(System.out::println);
23. strip(), stripLeading(), stripTrailing()
(Java 11)
Removes whitespaces.
String s = " Java ";
System.out.println(s.strip()); // Output: "Java"
System.out.println(s.stripLeading()); // Output: "Java "
System.out.println(s.stripTrailing()); // Output: " Java"
3. Immutability of Strings
Strings in Java are immutable to:
- Improve performance using String Pooling.
- Ensure thread safety.
Example of Immutability
String s = "Java";
s.concat(" Programming");
System.out.println(s); // Output: Java (Not modified)
To modify, use StringBuilder
or StringBuffer
.
4. Performance Considerations
- StringBuffer (Thread-safe, mutable)
- StringBuilder (Faster, mutable)
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World
5. Conclusion
This guide covered all String
methods with examples. Understanding String
operations is crucial for writing efficient Java applications.
Would you like to explore StringBuilder vs. StringBuffer in more detail? Let me know in the comments!