🚀 Essential String Methods in Java 🚀
Strings are one of the most commonly used data types in Java. But do you know how to manipulate them effectively? Let's explore some powerful String methods with simple examples!
This method returns the number of characters in a string, including spaces and special characters.
Example: Count the number of characters, including spaces.
String str = "Java";
System.out.println(str.length()); // Output: 4
This method returns the character at the given index (starting from 0).
String str = "Java";
System.out.println(str.charAt(1)); // Output: 'a'
The substring(int start, int end) method extracts a part of the string from the start index up to the end index.
Example: Extracts characters from index 7 to 10.
String str = "Hello, Java!";
System.out.println(str.substring(7, 11)); // Output: "Java"
If you only provide the starting index, the substring will continue to the end of the string.
Example: Extracts from index 4 to the end of the string.
String str = "Programming";
System.out.println(str.substring(4)); // Output: "ramming"
These methods are useful when performing case-insensitive comparisons or formatting output.
String str = "Java";
System.out.println(str.toUpperCase()); // Output: "JAVA"
System.out.println(str.toLowerCase()); // Output: "java"
String str = " Java ";
System.out.println(str.trim()); // Output: "Java"
Recommended by LinkedIn
This method checks if a string contains another sequence of characters. Used frequently in search functionality.
Example: Checks if "Java" is present in the string.
String str = "Java is awesome!";
System.out.println(str.contains("Java")); // Output: true
The replace() method replaces occurrences of a substring with another substring.
Example: Replace all occurrences of "fun" with "awesome".
String str = "Java is fun";
System.out.println(str.replace("fun", "awesome")); // Output: "Java is awesome"
The split() method splits a string into an array of substrings based on a given delimiter. Useful when processing CSV files or user input.
Example: Splits the string into an array based on ','.
String str = "Java,Python,C++";
String[] languages = str.split(",");
System.out.println(Arrays.toString(languages)); // Output: ["Java", "Python", "C++"]
The equals() method compares two strings exactly, including case, while equalsIgnoreCase() ignores case differences. Useful when user input might have different letter cases.
String s1 = "Java";
String s2 = "java";
System.out.println(s1.equals(s2)); // Output: false
System.out.println(s1.equalsIgnoreCase(s2)); // Output: true
💡 Key Takeaways
✅ Java Strings are immutable, so every method creates a new object.
✅ Use substring(), replace(), and split() to manipulate strings effectively.
✅ Always use .equals() instead of == to compare values.
✅ Methods like trim(), toUpperCase(), and contains() help in text processing.