We’ll use the following approach in this example:
- Create an empty
StringBuffer
for processing. We have usedStringBuffer
because string manipulation will create string objects in memory. - Loop from end of the string to the beginning of the string. Purpose of the loop is to get each character from end of the string to the beginning of the string.
- Append each character to the StringBuffer.
- Convert StringBuffer to String object.
public class ReverseStringExample { public static void main(String[] args) { String str = "Hello World"; System.out.println("String before reverse: " + str); StringBuffer revStrBuffer = new StringBuffer(""); for(int i=str.length()-1;i>=0;--i){ revStrBuffer.append(str.charAt(i)); } String reverseString = revStrBuffer.toString(); System.out.println("reverse string: " + reverseString); } }
Output
String before reverse: Hello World
reverse string: dlroW olleH