How to Reverse a String in Java

In this article we learn the how to reverse a string in java with example. We can reverse a string in java by using StringBuilder, StringBuffer, iteration etc. Let’s see the all ways to reverse string in java.

How to Reverse a String in Java?

1. Reverse a String in Java By Using StringBuilder

First you have to know some interesting facts about String and StringBuilder classes:

  • String objects are immutable.
  • The String class in Java does not have a reverse() method, however, the StringBuilder class has a built-in reverse() method.
  • The StringBuilder class does not have a toCharArray() method, while the String class has a toCharArray() method.

Step 1: Create a new class (For Example: ReverseAStringInJava).

Step 2: Write main method inside the class.

Step 3: Write the string in main method (String s1 = “java”;)

Step 4: Create a object of StringBuilder class (StringBuilder sb = new StringBuilder(s1);)

Step 5: Use StringBuilder class reverse() method.

Step 6: Print the reverse string.

Reverse a String in Java By Using StringBuilder
Reverse a String in Java By Using StringBuilder

Output:

avaj

2. Reverse a String in Java By Using StringBuffer

Step 1: Create a new class (For Example: ReverseAStringInJava).

Step 2: Write main method inside the class.

Step 3: Write the string in main method (String s1 = “java”;)

Step 4: Create a object of StringBuffer class (StringBuffer sb = new StringBuffer(s1);)

Step 5: Use StringBuffer class reverse() method.

Step 6: Print the reverse string.

Reverse a String in Java By Using StringBuffer
Reverse a String in Java By Using StringBuffer

Output:

avaj

3. Reverse a String in Java By Reverse Iteration

Step 1: Create a new class (For Example: ReverseAStringInJava).

Step 2: Write main method inside the class.

Step 3: Write the string in main method (String s1 = “java”;)

Step 4: Take another string in method (String rev = “”;)

Step 5: Calculate the length of string s1 by using length method and store it in variable l.

Step 6: Use for loop to do reverse iteration.

Step 7: Use charAt method and store this into string rev.

Step 8: Print the string rev outside the for loop.

Reverse a String in Java By Reverse Iteration
Reverse a String in Java By Reverse Iteration

Output:

avaj

Other Popular Articles:

What is String in Java?

Java String Methods with Examples

Leave a Comment