Reverse a string in Java

There are many ways to Reverse a string in Java. We can reverse String using StringBuilder,StringBuffer, iteration etc. Let’s see the ways to reverse String in Java.

The StringBuilder class has built-in reverse() method. so first we pass string into string buffer and call to reverse method,now convert the value from toString() method to string because return type is string.

The StringBuffer class has built-in reverse() method. so first we pass string into string buffer and call to reverse method,now convert the value from toString() method to string because return type is string.

From iteration loop case first we convert String in character from toCharArray method and the pass this character into for loop at reverse order.then we store this character in a string builder from append method.

				
					public class StringReverse {
	public static void main(String[] args) {
		String str = "hello world";

		String s1 = new StringBuffer(str).reverse().toString();
		System.out.println("from StringBuffer reverse:- " + s1);

		String s2 = new StringBuilder(str).reverse().toString();
		System.out.println("from StringBuilder reverse:- " + s2);

		System.out.println("from iteration method reverse:- " + reverseTest(str));

	}

	public static String reverseTest(String str) {
		StringBuilder sb = new StringBuilder();
		char c[] = str.toCharArray();
		for (int i = c.length - 1; i >= 0; i--) {
			sb.append(c[i]);
		}
		return sb.toString();
	}
}
				
			

Output :-
from StringBuffer reverse:- dlrow olleh
from StringBuilder reverse:- dlrow olleh
from iteration method reverse:- dlrow olleh

Leave a Comment

Your email address will not be published. Required fields are marked *