top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Reverse A String in Java

Introduction

When working with strings in Java, it’s necessary to reverse their order. Java provides an in-built reverse function to make the task simple. So whether you’re a professional or a novice, read on to learn how to reverse a string in Java word by word and more. 

Overview

Reversing a string in Java is a general operation, and Java offers various methods for the task. The in-built reverse function in Java is one of the most direct ways to reverse a string. 

However, instead of relying on Java utilities, you can reverse a string in Java using your logic. Let’s explore how to reverse a string in Java.

How to reverse a string in Java?

By Using StringBuilder

String originalString = "Good Morning!";
StringBuilder reversedString = new StringBuilder(originalString).reverse();
String finalString = reversedString.toString();
System.out.println(finalString);

We need to follow the steps below to use the reverse function in Java:

1. Create a StringBuilder object and give its constructor the initial String as an argument.

2. Use the StringBuilder object's reverse() function to reverse the string's character order.

3. Use the toString() method to convert the inverted StringBuilder object back to a String before assigning it to a new variable.

4. Print the reversed String to the console using the System.out.println() method.

By Using While Loop or For Loop

String originalString = "Good Morning!";
StringBuilder reversedString = new StringBuilder();
int i = originalString.length() - 1;
while (i >= 0) {
    reversedString.append(originalString.charAt(i));
    i--;
}
System.out.println(reversedString.toString());

We need to follow the steps below to reverse a string in Java using a while loop

1. Create a StringBuilder object and pass the original String to its constructor.

2. Initialize an integer variable to the length of the String minus 1.

3. Begin a while loop that continues as long as the index is greater than or equal to zero.

4. In each repetition, add the character at the current index to the StringBuilder object using the append() method.

5. Decrease the index by one.

6. After the loop completes, turn the StringBuilder object into a String using the toString() method.

7. Print the reversed String to the console using System.out.println().

Reversing a string using a For Loop:

String originalString = "Good Morning!";
StringBuilder reversedString = new StringBuilder();
for (int i = originalString.length() - 1; i >= 0; i--) {
    reversedString.append(originalString.charAt(i));
}
System.out.println(reversedString.toString());

To reverse a string in Java using for loop, you can follow the steps below: 

1. Make a StringBuilder object.

2. Initialize an integer variable to the length of the String minus 1.

3. Start a for loop that beings from the last character in the String and ends at the first character.

4. Get the character at the current position in the for loop, and add it to the StringBuilder object using the append() method.

5. Change the StringBuilder object into a String using the toString() method after the for loop completes.

6. Print the reversed String to the console using System.out.println().

A while loop and a for loop can reverse a string in Java, producing the same result.

By Converting a String to Bytes

String originalString = "Good Morning!";
byte[] byteArray = originalString.getBytes();
byte[] reversedByteArray = new byte[byteArray.length];
for (int i = 0; i < byteArray.length; i++) {
    reversedByteArray[i] = byteArray[byteArray.length - 1 - i];
}
String reversedString = new String(reversedByteArray);
System.out.println(reversedString);

1. Make a String variable and initialize it with a string value.

2. Use the String class’ getBytes() method to convert the original string into a byte array.

3. Make a new byte array called reversedByteArray with the same length as the byteArray.

4. Use a for loop to repeat over the byteArray from right to left and copy each byte into the corresponding index in the reversedByteArray

5. Change the reversedByteArray back into a String using the String constructor that takes a byte array as an argument.

6. Print the reversedString to the console using the println() method.

By Using ArrayList Object

String originalString = "Good Morning!";
ArrayList<Character> charList = new ArrayList<>();
for (char c : originalString.toCharArray()) {
    charList.add(c);
}
Collections.reverse(charList);
StringBuilder reversedStringBuilder = new StringBuilder(charList.size());
for (Character c : charList) {
    reversedStringBuilder.append(c);
}
String reversedString = reversedStringBuilder.toString();
System.out.println(reversedString);

1. Create a String variable called originalString and set its value to the desired string.

2. Make an empty ArrayList object called charList to store the string characters.

3. Utilize a for loop to repeat over each character in the originalString and add it to the charList using the add() method of the ArrayList class.

4. Use the reverse() method of the Collections class to reverse the order of the elements in the charList.

5. Create a StringBuilder object called reversedStringBuilder with an initial capacity equal to the size of the charList.

6. Create a for-each loop to repeat over every character in the charList and add it to the reversedStringBuilder utilizing the append() function of the StringBuilder class.

7. Convert the reversedStringBuilder object to a String using the StringBuilder class's toString() method, then assign it to a new String variable called reversedString.

8. Print the reversedString to the console using the println() method.

By Using StringBuffer

String originalString = "Good Morning!";
StringBuffer reversedStringBuffer = new StringBuffer(originalString);
reversedStringBuffer.reverse();
String reversedString = reversedStringBuffer.toString();
System.out.println(reversedString);

1. Make a String variable and assign a string value to it.

2. Make a StringBuffer object by passing the originalString to its constructor.

3. Call the reverse() method on the StringBuffer object. This method will reverse the contents of the StringBuffer object.

4. Use the toString() method to convert the reversedStringBuffer to a String.

5. Print the reversed String to the console using the println() method.

Using Stack

import java.util.Stack;
public class ReverseStringUsingStack {
    public static void main(String[] args) {
        String originalString = "Good Morning!";
        Stack<Character> stack = new Stack<>();
        for (char c : originalString.toCharArray()) {
            stack.push(c);
        }
        StringBuilder reversedStringBuilder = new StringBuilder();
        while (!stack.empty()) {
            reversedStringBuilder.append(stack.pop());
        }
        String reversedString = reversedStringBuilder.toString();
        System.out.println(reversedString);
    }
}

1. Create a Stack object called stack.

2. Make a String variable called originalString and set its value to the string you want to reverse.

3. Use a for-each loop to repeat over each character in the originalString string.

4. Push each character onto the stack within the loop using the push() method.

5. Create a StringBuilder object called reversedStringBuilder.

6. Make a while loop that runs as long as the stack is not empty.

7. Use the pop() method within the loop to retrieve the topmost element off the stack and add it to the reversedStringBuilder.

8. After the loop completes, convert the reversedStringBuilderb to a String using the toString() method.

9. Compile the reversed string to the console using the System.out.println() method.

Using Character Array

public class ReverseStringUsingCharArray {
    public static void main(String[] args) {
        String originalString = "Good Morning!";
        char[] originalArray = originalString.toCharArray();
        int left = 0;
        int right = originalArray.length - 1;
        while (left < right) {
            char temp = originalArray[left];
            originalArray[left] = originalArray[right];
            originalArray[right] = temp;
            left++;
            right--;
        }
        String reversedString = new String(originalArray);
        System.out.println(reversedString);
    }
}

1. Create a String variable called originalString with a desired value.

2. Convert the originalString to a char array using the toCharArray() method.

3. Initialize left and right integer variables to 0 and the length of the char array minus 1, respectively.

4. Enter a while loop while left is less than right.

5. Inside the while loop, swap the characters at originalArray[left] and originalArray[right].

6. Increment left and decrement right.

7. Convert the char array back to a String using the String constructor that takes a char array as a parameter.

8. Print the reversedString to the console using the println() method.

Using Recursion

public class ReverseStringUsingRecursion {
    public static void main(String[] args) {
        String originalString = "Good Morning!";
        String reversedString = reverse(originalString);
        System.out.println(reversedString);
    }
    public static String reverse(String str) {
        if (str.length() == 0) {
            return "";
        }
        return str.charAt(str.length() - 1) + reverse(str.substring(0, str.length() - 1));
    }
}

1. Create a String variable called originalString and assign it "Good Morning!".

2. Call the reverse() method and pass the originalString as an argument.

3. Check if the input string is 0 inside the reverse() method.

4. If the length is not 0, use recursion to reverse the string subset and add the last character.

5. Return the reversed string to the calling method.

Using Substring() Method

public class ReverseStringUsingSubstring {
    public static void main(String[] args) {
        String originalString = "Good Morning!";
        String reversedString = "";
        for (int i = originalString.length() - 1; i >= 0; i--) {
            reversedString += originalString.substring(i, i + 1);
        }
        System.out.println(reversedString);
    }
}

1. Create a String variable named originalString and assign it the value "Good Morning!".

2. Create an empty String variable named reversedString.

3. Use a for loop to iterate over the characters of the originalString variable in reverse order:

  • Initialize the loop variable i to the index of the last character of originalString.

  • Set the loop condition to i >= 0, meaning the loop will continue until it reaches the first character of originalString.

  • Decrement i by 1 in each iteration.

  • Use the substring() method to extract the character at the current index i from originalString and append it to the reversedString variable.

4. Print the reversedString variable to the console using the println() method.

Using the Character Array and swap() Method

public class ReverseStringUsingCharArray {
    public static void main(String[] args) {
        String originalString = "Good Morning!";
        char[] charArray = originalString.toCharArray();
        int left = 0;
        int right = charArray.length - 1;
        while (left < right) {
            swap(charArray, left, right);
            left++;
            right--;
        }
        String reversedString = new String(charArray);
        System.out.println(reversedString);
    }
    public static void swap(char[] charArray, int i, int j) {
        char temp = charArray[i];
        charArray[i] = charArray[j];
        charArray[j] = temp;
    }
}

1. Create and initialize a String variable with a value.

2. Convert the string to a char array using toCharArray().

3. Initialize leftIndex to 0 and rightIndex to length of the char array minus 1.

4. While leftIndex is less than rightIndex, swap characters at charArray[leftIndex] and charArray[rightIndex].

1. Increase leftIndex and decrease rightIndex.

2. Convert the char array back to a String using the String constructor.

3. Print the reversed String to the console.

Using the Java Collections Framework reverse() Method

import java.util.*;
public class ReverseStringUsingCollections {
    public static void main(String[] args) {
        String originalString = "Good Morning!";
        List<Character> charList = new ArrayList<Character>();
        for (char c : originalString.toCharArray()) {
            charList.add(c);
        }
        Collections.reverse(charList);
        String reversedString = "";
        for (char c : charList) {
            reversedString += c;
        }
        System.out.println(reversedString);
    }
}

1. Create a String variable called originalString and set it to a desired value.

2. Create an ArrayList of characters called charList.

3. Iterate over the characters of the originalString using a for-each loop and add each character to the charList.

4. Use the reverse() method from the Collections class to reverse the order of the elements in the charList.

5. Create an empty String variable called reversedString.

6. Iterate over the reversed charList using a for-each loop and add each character to the reversedString.

7. Print the reversedString to the console.

Following are some interesting facts about String and StringBuilder classes

Converting String into Bytes: getBytes() method is used to convert the input string into bytes[]

The getBytes() method under the String class turns a String into a byte array. It can be helpful in many operations. 

However, the encoding process used during conversion should be carefully chosen as it can impact the resulting byte array.

Using built-in reverse() method of the StringBuilder class

StringBuilder includes a reverse() method that alters the object in place and reverses the character order. 

This is perhaps more efficient than generating a new object. reverse() can quickly reverse a string for display or processing.

Converting String to character array: The user input the string to be reversed.

The String class offers a method called toCharArray(), which can convert a String to a char array.

It can be helpful when altering individual characters in the String, such as reversing the order of the characters.

We can follow these steps to reverse a string in Java using Scanner to get user input:

1. Create a Scanner object to read user input.

2. Get the user to enter a String and store the input in a String variable.

3. Change the String to a char array using the toCharArray() method.

4. Reuse the method as before to reverse the character order.

5. Change the reversed char array back to a String using the String constructor that takes a char array as an argument.

6. Print the reversed String to the console.

Conclusion

Java provides many methods for reversing strings, including turning the string to a character array, using the StringBuilder class, or converting the string to a byte array. 

Each method has advantages and can be used based on the demands of the current task. Java code can be written more effectively and efficiently by understanding these several programming problem-solving approaches.

FAQs

1. What is the simplest way in Java to reverse a string?

The in-built reverse function is the simplest way to reverse a string in Java. 

2. How can a for loop in Java reverse a string?

You can first turn a string into a character array in Java, iterate over the array in reverse order, and then add each character to a fresh string.

3. How can a for loop in Java reverse a string?

You can first turn a string into a character array in Java, iterate over the array in reverse order, and then add each character to a fresh string.

Leave a Reply

Your email address will not be published. Required fields are marked *