How to reverse string in java example

These are the most common questions asking now a day to Android, Java developers, and technical interviews. There are several different ways to Reverse a string.

Here is example for better understanding :

Original String : “Hello”

Revers String : “olleH”

Original String : “My name is rohit”

Revers String : “tihor si eman yM”

Take String form console

Method 1.  Using reverse for loop

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReverseStringJava {
	public static void main(String arg[]){
		BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Enter Text : ");
		String out = "";
		try {
			String enterStr=bufferedReader.readLine();
			for (int i = enterStr.length() ; i >0; i--) {
				out=out+enterStr.charAt(i-1);
			}
			
			System.out.println("Your Text : " + out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Method 2. Using StringBuilder

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReverseStringJava {
	public static void main(String arg[]){
		BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Enter Text : ");
		String out = "";
		try {
			String enterStr=bufferedReader.readLine();
			StringBuilder sb=new StringBuilder(enterStr);
			out=sb.reverse().toString();
			
			System.out.println("Your Text : " + out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Reverse the String is programming question to test problem solving skill. You can solve this question in any language.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.