Reverse a String in Java

Reverse a String in Java

Reversing a string is a common task in Java, and there are several ways to achieve it. Here’s a simple approach using different techniques to reverse a string effectively.

1. Using a StringBuilder

Java’s StringBuilder class provides a convenient reverse() method, which can be directly used to reverse the contents of a string.

String original = "Hello, World!";
String reversed = new StringBuilder(original).reverse().toString();
System.out.println(reversed);  // Output: !dlroW ,olleH

This method is simple and efficient. It makes use of the mutable StringBuilder class. This class is designed to handle such operations with ease.

2. Using a Character Array

Another approach involves converting the string into a character array. Next, reverse the array in place. Finally, convert it back to a string.

String original = "Hello, World!";
char[] chars = original.toCharArray();

for (int i = 0, j = chars.length - 1; i < j; i++, j--) {
    char temp = chars[i];
    chars[i] = chars[j];
    chars[j] = temp;
}

String reversed = new String(chars);
System.out.println(reversed);  // Output: !dlroW ,olleH

This method gives you control over the reversal process, allowing you to manipulate the characters directly.

3. Using a Loop

A more manual approach is to iterate through the string from the end to the beginning. Append each character to a new string.

String original = "Hello, World!";
String reversed = "";

for (int i = original.length() - 1; i >= 0; i--) {
    reversed += original.charAt(i);
}

System.out.println(reversed);  // Output: !dlroW ,olleH

This method is straightforward but less efficient than the previous ones, especially with larger strings, due to the repeated concatenation.

4. Using Java 8 Streams

For those who enjoy working with streams, you can also reverse a string by converting it to a stream of characters, reversing the order, and then collecting it back into a string.

String original = "Hello, World!";
String reversed = Arrays.stream(original.split(""))
                        .collect(Collectors.collectingAndThen(Collectors.toList(),
                                                              list -> {
                                                                  Collections.reverse(list);
                                                                  return list.stream();
                                                              }))
                        .collect(Collectors.joining());

System.out.println(reversed);  // Output: !dlroW ,olleH

This approach showcases the flexibility and power of Java streams, though it is more verbose than other methods.

Each of these methods provides a way to reverse a string, and you can choose the one that best fits your needs based on readability, performance, or coding style.


Discover more from Byte Code

Subscribe to get the latest posts sent to your email.

Leave a Reply

I’m A Java Enthusiast

Welcome to Byte-Code, your go-to corner of the internet for all things Java. Here, I invite you to join me on a journey through the world of programming, where we’ll explore the intricacies of Java, dive into coding challenges, and build solutions with a touch of creativity. Let’s code something amazing together!

Let’s connect