Java Reverse String: Tutorial With Programming Examples

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 10, 2024

In this Tutorial, we will learn to Reverse a String in Java using the Reverse() Method of StringBuilder and StringBuffer Classes with the help of Examples:

Here we will discuss the reverse() String Java method and it’s usage along with sufficient programming examples, FAQs, and scenario-based questions that will give you an idea about the applicable areas of this method.

Upon going through this tutorial, you will be in a position to understand the reverse() String Java method better and can apply the method in various String handling programs on your own.

=> Visit Here To Learn Java From Scratch.

Java String - reverse method

Java Reverse String

Before we start, we should understand that the Java String class is immutable and it does not have the reverse() method. However, StringBuilder and StringBuffer classes have the inbuilt Java reverse() method.

As the name suggests, the reverse() method is used to reverse the order of occurrences of all the characters of a String.

Syntax:

StringBuffer reverse()

StringBuffer Reverse String

In this example, we have initialized a String variable and stored all the characters of that String into StringBuffer. Then, we have used the reverse() method to reverse the occurrence of the characters of the String.

public class Reverse {
	
	public static void main(String[] args) {
		
		// Initialized a String variable
		String str = "gnitseT erawtfoS";
		
		// Created a StringBuffer "sb" and stored all the characters of the String
		StringBuffer sb = new StringBuffer(str);
		
		// Reversed the occurrence of characters
		sb.reverse();
		
		// Printed the StringBuffer
		System.out.println(sb);

	}
}

Output:

StringBuffer Reverse String

StringBuilder Reverse String

In this example, we are trying to reverse the occurrence of the characters through StringBuilder Class. We are carrying out the reverse() method on the same input values that we used during the StringBuffer.

public class Reverse {
	
	public static void main(String[] args) {
		
		// Initialized a String variable
		String str = "gnitseT erawtfoS";
		
		// Created a StringBuilder "stbuilder" and stored all the characters of the String
		StringBuilder stbuilder = new StringBuilder(str);
		
		// Reversed the occurrence of characters
		stbuilder.reverse();
		
		// Printed the StringBuilder
		System.out.println(stbuilder);
		
	}
}

Output:

StringBuilder Reverse String

Scenarios

Scenario 1: Reverse a String without using StringBuilder or StringBuffer reverse() method.

Explanation: In this scenario, we will show you how to reverse the characters of a string without using the reverse() method.

We have taken an input String and then converted it into character Array. With the help of for loop, we have printed the characters in the reverse order.

public class Reverse {

	public static void main(String[] args) {

		// Initialized a String variable
		String str = "SAKET";

		/*
		 *  converted String into character Array
		 *  and printed all the elements in
		 *  reverse order using for loop
		 */
		
		char chars[] = str.toCharArray(); 
		
		for (int i = chars.length - 1; i >= 0; i--) {
			System.out.print(chars[i]);
		}
	}
}

Output:

Reverse the characters of the string - output

Scenario 2: Reverse all the characters using the Split() method.

Explanation: This is another way to reverse the occurrence of the characters of a String. In this scenario, we will use the Split() method to split each character of a String and using for loop, we will print each character in the reverse order of occurrence.

Here, we have taken the input through the console using the Scanner Class.

import java.util.Scanner;

public class Reverse {

	public static void main(String[] args) {

		String str;
		
		// Taking input through the console using Scanner Class
		Scanner in = new Scanner(System.in);
		System.out.println("Enter your String");
		str = in.nextLine();
		
		/*
		 * Splitted each character of the String and then
		 * printed the same in the reverse order using
		 * for loop
		 */
		String[] split = str.split("");
		for(int i=split.length-1; i>=0; i--)
		{
			System.out.print(split[i] + "");
		}
		
	}

}

Output:

Reverse all the characters using the Split() method

Scenario 3: Reverse all the characters by using Swapping.

Explanation: This is yet another way to reverse the characters of a String. Here, we have initialized ‘i’ and length =0.

Inside the for loop, we have parsed the characters from both the sides by keeping ‘i’ equal to zero, incrementing by 1 and length decrementing by 1 for every comparison between the initial index and the last index. We have continued this condition until ‘i’ becomes ‘equal to’ or ‘greater than’ the length.

Finally, with the help of the forEach loop, we have printed each character.

class Reverse {
	public static void main(String[] args) {

		// Initialized an input String
		String str = "PLEHGNITSETERAWTFOS SI SIHT";

		// Converted the String into character Array
		char[] arr = str.toCharArray();

		int i, length = 0;
		length = arr.length - 1;

		for (i = 0; i < length; i++, length--) {
			
			/*
			 * Swapped the values of i and length.
			 * This logic is applicable for Sorting any Array
			 * or Swapping the numbers as well.
			 */
			
			char temp = arr[i];
			arr[i] = arr[length];
			arr[length] = temp;
		}

		for (char chars : arr)
			System.out.print(chars);
		System.out.println();
	}
}

Output:

Reverse all the characters by using Swapping

Frequently Asked Questions

Q #1) Is there a reverse() String method in Java?

Answer: No. The String class does not have a reverse() method. However, you can reverse a String using multiple ways in the String class itself. Also, StringBuilder, StringBuffer, and Collections support the reverse() method.

Q #2) How can we convert a StringBuilder into String?

Answer: Given below is the program in which we have converted the elements stored in a StringBuilder into a String.

public class Reverse {
	public static void main(String args[]) {
		
		String strArr[] = { "This", "is", "an", "Example", "of", "String" };
		
		// Created a new StringBuilder
		StringBuilder sb = new StringBuilder();
		
		/*
		 * Appended all the elements of str (delimited by space) into StringBuilder
		 */
		sb.append(strArr[0]);
		sb.append(" " + strArr[1]);
		sb.append(" " + strArr[2]);
		sb.append(" " + strArr[3]);
		sb.append(" " + strArr[4]);
		sb.append(" " + strArr[5]);

		// Converted the StringBuilder into it's String Equivalent
		String str = sb.toString();

		
		System.out.println(str);
	}
}

Output:

convert a StringBuilder into String

Q #3) List out the difference between String, StringBuilder, and StringBuffer?

Answer: Given below is the difference between String, StringBuilder, and StringBuffer.

StringStringBufferStringBuilder
A String is an Immutable class.StringBuffer is a Mutable class which is synchronized (thread-safe).StringBuilder is also a Mutable class which is non-synchronized.
A String is less efficient than StringBuffer and StringBuilder because every time we perform String manipulation, it creates a new String and throws the old String for garbage collection.StringBuffer is less efficient.StringBuilder is more efficient than StringBuffer.
A String is slower than the StringBuffer when we concat multiple Strings as it creates a new instance every time.StringBuffer is slower than StringBuilder.StringBuilder is fast because it is non-synchronized.

Q #4) How do I convert a char to a String in Java?

Answer: We can convert a character to a String using an inbuilt method “toString()”.

Suggested reading => How to Convert Char to String in Java

Given below is the program where we have used the toString() method to convert a char to a String.

public class Reverse {
	public static void main(String args[]) {

		char chars = 'A';
		
		/*
		 *  With the help of toString() method, we have 
		 *  converted a Character into its String Equivalent
		 */

		String str = Character.toString(chars);
		System.out.println(str);
	}
}

Output:

convert a char to a String in Java

Q #5) Write a Java program to check whether the string is a palindrome or not (Using StringBuffer).

Answer: We can use any of the String reverse program (illustrated above) and then add a condition to check whether it is palindrome or not.

An example program is given below.

import java.util.Scanner;

public class Reverse {
	public static void main(String[] args) {
		
		// Initialized a String variable
		String str = "racecar";
		
		// Created a StringBuffer "sb" and stored all the characters of the String
		StringBuffer sb = new StringBuffer(str);
		
		// Reversed the occurrence of characters
		sb.reverse();
		
		/*
		 *  Stored the contents of StringBuffer into str2
		 *  by converting it using toString()
		 */
		
		String str2 = sb.toString();
		
		System.out.println("The Original String is: "+str);
		System.out.println("The reversed String is "+str2);
		
		if (str.equals(str2))
			System.out.println("The String is palindrome");
		else
			System.out.println("The String is not a palindrome");

	}
}

Output:

check whether the String is palindrome or not (Using StringBuffer)?

Q #6) How to reverse a String in Java word by word?

Answer: You can reverse a String in Java (word by word) by using the inbuilt Java String Split() method. All you need to do is to pass whitespace in the Split() method.

Check out the example program below.

import java.util.Scanner;

public class Reverse {

	public static void main(String[] args) {
		
		String str;
		
		/* Getting input from console using Scanner class
		 * 
		 */
		
		Scanner in = new Scanner(System.in);
		System.out.println("Enter your String");
		str = in.nextLine();
		
		/*
		 *  Used split() method to print in reverse order
		 *  delimited by whitespace 
		 */
		
		String[] split = str.split(" ");    
		
		for(int i=split.length-1; i>=0; i--)
		{
			System.out.print(split[i] + " ");
		}
		
	}

}

Output:

Reverse a String in Java word by word

Q #7) Is StringBuilder thread-safe? Why is StringBuilder faster than StringBuffer?

Answer: No, the StringBuilder is not thread-safe or synchronized. StringBuffer is thread-safe. Thus, the StringBuilder is considered as faster than the StringBuffer.

Conclusion

In this tutorial, we have learned about the Java String reverse() method and the various techniques through which you can reverse a String.

Moreover, we have covered sufficient FAQs and programming examples that will help you to understand the reverse() method.

=> Visit Here To See The Java Training Series For All.

Was this helpful?

Thanks for your feedback!

Leave a Comment