Java String reverse with and without reverse() Example

Java String reverse with and without reverse() Example


To reverse a string with less code in Java, there comes reverse() method in StringBuffer class. reverse() method cannot be used directly on string as reverse() is not defined in String class but defined in StringBuffer and StringBuilder. String should be converted to StringBuffer and then applied reverse() method.

1. Reversing using reverse() method.


string reverse
Output screenshot of string reverse Example

If string is required in coding after reversing, convert sb1 to string using either valueOf() method or toString() method as follows.

String str2 = sb1.toString();

2. Reversing without using string reverse method.


string reverse
Output screenshot of string reverse Example

Leave a Reply

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