In this Java tutorial, you will learn how to reverse a string in different ways like iterating over the characters and arranging them in reverse order, or using StringBuilder.reverse() method, with examples.

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.

Examples

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

</>
Copy
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

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

</>
Copy
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

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

</>
Copy
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.