DEV Community

Cover image for Java String Manipulation: Common Methods You Should Know
Saurabh Kurve
Saurabh Kurve

Posted on

Java String Manipulation: Common Methods You Should Know

String manipulation is one of the most fundamental operations in Java programming. Whether you're processing user inputs, formatting output, or implementing algorithms, working with strings effectively is a critical skill. Java provides a rich set of methods for manipulating strings, making it easier to perform a wide range of tasks. In this blog, weโ€™ll explore some of the most common string manipulation methods every Java developer should know.


1. Creating Strings

Strings in Java can be created in two ways:

  • Using String literals:
  String str = "Hello, World!";
Enter fullscreen mode Exit fullscreen mode
  • Using the new keyword:
  String str = new String("Hello, World!");
Enter fullscreen mode Exit fullscreen mode

While both methods achieve the same result, using string literals is generally preferred due to the string pool optimization in Java.


2. Checking String Length

To find the length of a string, use the length() method:

String str = "Java Programming";
System.out.println("Length: " + str.length());
Enter fullscreen mode Exit fullscreen mode

Output:

Length: 16


3. Concatenation

You can combine strings using:

  • The + operator:
  String firstName = "John";
  String lastName = "Doe";
  String fullName = firstName + " " + lastName;
  System.out.println(fullName);
Enter fullscreen mode Exit fullscreen mode
  • The concat() method:
  String fullName = firstName.concat(" ").concat(lastName);
Enter fullscreen mode Exit fullscreen mode

4. Comparing Strings

Java offers several ways to compare strings:

  • equals() Method: Compares two strings for equality, considering case sensitivity.
  String str1 = "Java";
  String str2 = "Java";
  System.out.println(str1.equals(str2)); // true
Enter fullscreen mode Exit fullscreen mode
  • equalsIgnoreCase() Method: Ignores case sensitivity.
  System.out.println(str1.equalsIgnoreCase("java")); // true
Enter fullscreen mode Exit fullscreen mode
  • compareTo() Method: Compares strings lexicographically.
  System.out.println(str1.compareTo("Jawa")); // Negative value
Enter fullscreen mode Exit fullscreen mode

5. Extracting Substrings

The substring() method is used to extract a portion of a string:

String str = "Welcome to Java";
System.out.println(str.substring(11));       // "Java"
System.out.println(str.substring(0, 7));    // "Welcome"
Enter fullscreen mode Exit fullscreen mode

6. Searching in Strings

  • indexOf() Method: Finds the first occurrence of a character or substring.
  String str = "Programming in Java";
  System.out.println(str.indexOf('a')); // 12
  System.out.println(str.indexOf("Java")); // 16
Enter fullscreen mode Exit fullscreen mode
  • lastIndexOf() Method: Finds the last occurrence.
  System.out.println(str.lastIndexOf('a')); // 21
Enter fullscreen mode Exit fullscreen mode

7. Replacing Characters or Substrings

Use the replace() method to replace characters or substrings:

String str = "Java is fun";
System.out.println(str.replace("fun", "powerful")); // "Java is powerful"
Enter fullscreen mode Exit fullscreen mode

For advanced replacements, replaceAll() supports regular expressions:

String str = "123-456-7890";
System.out.println(str.replaceAll("\\d", "*")); // "***-***-****"
Enter fullscreen mode Exit fullscreen mode

8. Splitting Strings

The split() method divides a string into an array based on a delimiter:

String str = "apple,orange,banana";
String[] fruits = str.split(",");
for (String fruit : fruits) {
    System.out.println(fruit);
}
Enter fullscreen mode Exit fullscreen mode

Output:

apple
orange
banana
Enter fullscreen mode Exit fullscreen mode

9. Changing Case

  • toUpperCase() Method: Converts all characters to uppercase.
  String str = "hello";
  System.out.println(str.toUpperCase()); // "HELLO"
Enter fullscreen mode Exit fullscreen mode
  • toLowerCase() Method: Converts all characters to lowercase.
  System.out.println(str.toLowerCase()); // "hello"
Enter fullscreen mode Exit fullscreen mode

10. Trimming Whitespace

Use trim() to remove leading and trailing spaces:

String str = "  Java Programming  ";
System.out.println(str.trim()); // "Java Programming"
Enter fullscreen mode Exit fullscreen mode

11. Checking String Emptiness

Java provides two methods to check if a string is empty or blank:

  • isEmpty() Method: Returns true if the string has no characters.
  String str = "";
  System.out.println(str.isEmpty()); // true
Enter fullscreen mode Exit fullscreen mode
  • isBlank() Method (Java 11+): Returns true if the string is empty or contains only whitespace.
  String str = "   ";
  System.out.println(str.isBlank()); // true
Enter fullscreen mode Exit fullscreen mode

12. String Formatting

The String.format() method allows you to create formatted strings:

String name = "Alice";
int age = 25;
String message = String.format("My name is %s and I am %d years old.", name, age);
System.out.println(message);
Enter fullscreen mode Exit fullscreen mode

Output:

My name is Alice and I am 25 years old.


13. Joining Strings

From Java 8 onward, the String.join() method simplifies joining strings with a delimiter:

String result = String.join(", ", "Java", "Python", "C++");
System.out.println(result); // "Java, Python, C++"
Enter fullscreen mode Exit fullscreen mode

Mastering these common string manipulation methods in Java can significantly improve your coding efficiency and clarity. Strings are integral to most Java applications, and knowing how to manipulate them effectively will make your code more robust and maintainable. Experiment with these methods in your projects to fully harness their power!

Got any favorite string methods we missed? Let us know in the comments below!

Top comments (0)