Reverse a String in Java

There are many ways in which you can reverse a String in Java.

Reversing a string means, character at the ith position in original string will have a position of (string length -i)th position in the new reversed string.

In this tutorial, we will go through some example Java programs that demonstrate the procedure to reverse a string.

Example 1 – Reverse String using String.getBytes

In this example program, we shall get the bytes of given String using String.getBytes() function. Then using a for loop, read each character one by one and arrange them in reverse order.

ReverseString.java

/**
 * Java Example Program, to reverse a String in Java
 */

public class ReverseString {

	public static void main(String[] args) {
		String str = "www.tutorialkart.com";
		String reverseStr="";
		
		for(byte c:str.getBytes()){
			reverseStr=(char)c+reverseStr;
		}
		System.out.println("Original String is : "+str);
		System.out.println("Reversed String is : "+reverseStr);
	}
}

When the above program is run, output to the console window shall be as shown below.

Output

Original String is : www.tutorialkart.com
Reversed String is : moc.traklairotut.www

Example 2 – Reverse String using String.charAt()

In this example, we shall traverse through the string from first character to last character using for loop, incrementing index and String.charAt() function.

ReverseString.java

/**
 * Java Example Program, to reverse a String in Java
 */

public class ReverseString {

	public static void main(String[] args) {
		String str = "www.tutorialkart.com";
		String reverseStr="";
		
		for(int i=0;i<str.length();i++) {
			reverseStr = str.charAt(i) + reverseStr;
		}
		
		System.out.println("Original String is : "+str);
		System.out.println("Reversed String is : "+reverseStr);
	}
}

Run the above program and you should get the output printed to the console as shown below.

Output

Original String is : www.tutorialkart.com
Reversed String is : moc.traklairotut.www

Example 3 – Reverse String using StringBuilder

StringBuilder is a very useful class when you doing string operations like concatenation, reverse, etc., on large strings.

In this example, we shall create a StringBuilder with the given string and use its function StringBuilder.reverse() to reverse the original string.

ReverseString.java

/**
 * Java Example Program, to reverse a String in Java
 */

public class ReverseString {

	public static void main(String[] args) {
		String str = "www.tutorialkart.com";
		
		StringBuilder sb = new StringBuilder(str);
		sb.reverse();
		
		String reverseStr = sb.toString();
		
		System.out.println("Original String is : "+str);
		System.out.println("Reversed String is : "+reverseStr);
	}
}

Run the program.

Output

Original String is : www.tutorialkart.com
Reversed String is : moc.traklairotut.www

Conclusion

In this Java Tutorial, we have learnt how to reverse a given String in Java.