Reverse String in Java

JavaJavaBeginner
Practice Now

Introduction

In Java, a String is a sequence of characters. In some cases, it may be necessary to reverse a String. This can be done using the reverse() method of the StringBuilder class or by creating a new string in reverse order. In this lab, we will go through the steps to reverse a string in Java.

Create a String

The first step is to create a String that we want to reverse. We will create a String variable and assign it a string value.

String str = "LabEx";

Use StringBuilder to Reverse the String

In this step, we will use the reverse() method of the StringBuilder class to reverse the string. We will create a new StringBuilder object and pass the original string as an argument. Then, we will call the reverse() method on the StringBuilder object. Finally, we will convert the StringBuilder object back to a String using the toString() method.

StringBuilder strBuilder = new StringBuilder(str);
strBuilder.reverse();
String reversedStr = strBuilder.toString();

We can print the reversed string using the following code.

System.out.println("Reversed String using StringBuilder: " + reversedStr);

Create a New String in Reverse Order

In this step, we will create a new string in reverse order. We will use a for loop to iterate through each character of the original string starting with the last character. We will append each character to a new String object.

String newStr = "";
for(int i = str.length() - 1; i >= 0; i--) {
   newStr = newStr + str.charAt(i);
}

We can print the reversed string using the following code.

System.out.println("Reversed String using new String: " + newStr);

Final Code

The final code to reverse the string using StringBuilder and new String is as follows.

public class ReverseString {
   public static void main(String[] args) {
      String str = "LabEx";

      // Reversing a String using StringBuilder
      StringBuilder strBuilder = new StringBuilder(str);
      strBuilder.reverse();
      String reversedStr = strBuilder.toString();
      System.out.println("Reversed String using StringBuilder: " + reversedStr);

      // Reversing a String using new String
      String newStr = "";
      for(int i = str.length() - 1; i >= 0; i--) {
         newStr = newStr + str.charAt(i);
      }
      System.out.println("Reversed String using new String: " + newStr);
   }
}

Summary

In this lab, we learned how to reverse a string in Java using StringBuilder and new String. We also went through the steps to create a new String in reverse order using a for loop. It is important to note that the StringBuilder method is more efficient for large strings and should be used when performance is a concern.

Other Java Tutorials you may like