String Reverse In Java Example

This section explains you how to reverse a string from its original value.

String Reverse In Java Example

This section explains you how to reverse a string from its original value.

String Reverse In Java Example

String Reverse In Java Example

In this tutorial we will read about reversing a String in Java. Here we will see how a String can be represented in its reverse value.

Reversing a String is an operation to represent an original String into its reverse order. In Java we can reverse a number using various ways. We can use the reverse() method of StringBuilder class (jdk 1.5 and later) and StringBuffer class (jdk earlier than 1.5). reverse() method changes the sequence of characters in reverse order. As well as, we can apply our own logic to display the String in reverse order.

Syntax of StringBuilder reverse() method.

public StringBuilder reverse()

Example

Here an example is being given which will demonstrate you about how to reverse a String using StringBuilder's reverse() method and by applying own logic. In this example we will create a Java class where we will define a String constant, and then we will reverse this String using StringBuilder's reverse() method. Then we will create a method using which we will reverse a String by applying own logic. In this method we will get the length of the string and then we will find the character array and then we will again append the String characters in its reverse order i.e. character at first index will be replaced with last index, second index character will be replaced with second last index and so on.

ReverseStringExample.java

public class ReverseStringExample {

	static String string = "RoseIndia";
	
	static StringBuilder sb = new StringBuilder(string);
	static String reverseString = sb.reverse().toString();
	
	public static void reverse(String str)
	{
		if(!(str == null || (str.equals(""))))
		{
			String newString = "";
			int len = str.length();
			for(int i = len-1; i >= 0; i--)
			{
				newString = newString+str.charAt(i);
			}
			System.out.println(str+" reversed to : "+newString);
		}
	}
	
	public static void main(String arr[])
	{
		System.out.println(string+" reversed to : "+reverseString);
		java.util.Scanner scan = new java.util.Scanner(System.in);
		System.out.print("Enter a String to reverse : ");
		String word = scan.next();
		ReverseStringExample.reverse(word);
	}
}

Output

When you will compile and execute the above example you will get the output as follows :

Download Source Code