How to Reverse a String in Java

Avatar

By squashlabs, Last Updated: Nov. 3, 2023

How to Reverse a String in Java

To reverse a string in Java, you can use various approaches. Here are two possible solutions:

1. Using a StringBuilder

One straightforward way to reverse a string in Java is by using the StringBuilder class, which provides a reverse() method. Here's an example:

public String reverseString(String input) {
    StringBuilder sb = new StringBuilder(input);
    sb.reverse();
    return sb.toString();
}

In this example, we create a new StringBuilder object with the given input string. Then, we call the reverse() method, which modifies the string in-place, reversing its characters. Finally, we convert the reversed StringBuilder object back to a string using the toString() method and return it.

This approach has a time complexity of O(n), where n is the length of the input string.

Related Article: How To Set Xms And Xmx Parameters For Jvm

2. Using a char array

Another approach to reverse a string in Java is by converting the string to a char array and then swapping the characters from both ends of the array. Here's an example:

public String reverseString(String input) {
    char[] charArray = input.toCharArray();
    int left = 0;
    int right = charArray.length - 1;
    
    while (left < right) {
        char temp = charArray[left];
        charArray[left] = charArray[right];
        charArray[right] = temp;
        left++;
        right--;
    }
    
    return new String(charArray);
}

In this example, we first convert the input string to a char array using the toCharArray() method. Then, we initialize two pointers: left pointing to the first character of the array and right pointing to the last character. We swap the characters at left and right positions iteratively while incrementing left and decrementing right until they cross each other.

Once we finish swapping all the characters, we create a new string from the reversed char array using the String constructor and return it.

This approach also has a time complexity of O(n), where n is the length of the input string.

Alternate Approaches

Related Article: Can Two Java Threads Access the Same MySQL Session?

- Using recursion: You can also reverse a string recursively by recursively calling a method to reverse the substring excluding the first character and then appending the first character at the end. However, this approach may not be as efficient as the previous ones for large strings due to the additional overhead of recursive function calls.

- Using Collections.reverse(): If you are allowed to use the java.util.Collections class, you can convert the string to a List, reverse the list using the reverse() method, and then convert it back to a string.

It's important to note that strings in Java are immutable, meaning that you cannot modify them directly. Therefore, converting the string to a mutable data structure like StringBuilder or char[] is necessary to perform the reversal.

Overall, reversing a string in Java can be achieved using various approaches, and the choice depends on factors such as performance requirements, code readability, and personal preference.

Java Hashmap Tutorial

This article provides a comprehensive guide on efficiently using Java Hashmap. It covers various use cases, best practices, real-world examples, perf… read more

How to Implement Recursion in Java

Recursion is a fundamental concept in Java programming, and understanding the data structure that controls recursion is essential for every software … read more

How to Convert List to Array in Java

Java developers often need to convert a List into an Array in their code. This article provides a step-by-step guide on how to achieve this using two… read more

Merge Sort Algorithm in Java and Python

This article provides a practical guide on how to implement the Merge Sort Algorithm in both Java and Python programming languages. The article cover… read more

Storing Contact Information in Java Data Structures

Storing contact information in Java data structures provides an way to organize and manage data. This article covers different data structures in Jav… read more

How to Print an ArrayList in Java

Printing an ArrayList in Java can be done in multiple ways. One approach is to use a for-each loop, which allows you to iterate through the elements … read more

Java Classloader: How to Load Classes in Java

This article Learn how to load classes in Java using the Java Classloader. This article covers the introduction to class loaders, class loader hiera… read more

Java Composition Tutorial

This tutorial: Learn how to use composition in Java with an example. This tutorial covers the basics of composition, its advantages over inheritance,… read more

How to Resolve java.lang.ClassNotFoundException in Java

Java is a powerful programming language used by developers worldwide. However, encountering the java.lang.ClassNotFoundException error can be frustra… read more

How To Fix Java Certification Path Error

Ensure your web applications are secure with this article. Learn how to resolve the 'unable to find valid certification path to requested target' err… read more