- by Rutu Shah
In this tutorial you will learn to reverse the given string sentence using for loop and while loop in java programming.
For example
Input : My name is Rutu Shah
Output : Shah Rutu is name My.
Using while Loop.
Lets begin with reversing string first using while Loop.
/*
* Prepared by : Rutu Shah
* This program reverse the entire string using while loop
* */
import java.util.Scanner;
public class ReverseWords {
public static void main(String[] args) {
{
System.out.print("Please enter the String :");
Scanner scan = new Scanner(System.in);
String ipString = scan.nextLine();
char[] ch = ipString.toCharArray();
String result = "";
int i = ch.length - 1;
while (i >= 0) {
int k = i;
while (i >= 0 && ch[i] != ' ') {
i--;
}
int j = i + 1;
while (j <= k) {
result = result + ch[j];
j++;
}
result = result + " ";
i--;
}
System.out.println("Reversed String : " + result);
}
}
}
Output

Using For Loop
/*
* Prepared by : Rutu Shah
* This program reverse the entire string using for loop
* */
import java.util.Scanner;
public class ReverseStringUsingForLoop {
public static void main(String[] args) {
String input,stringReverse = "", stringReverse1 = "";
int size = 0, newIndex = 0;
//Program's logic
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter the String : ");
input = scanner.nextLine();
for (size = 0; size < input.length(); size++){
newIndex = input.indexOf(' ', size);
if (newIndex != -1){
stringReverse1 = input.substring(size, newIndex);
stringReverse1 = " " + stringReverse1;
size = newIndex;
}else {
stringReverse1 = input.substring(size);
size = size+ stringReverse1.length();
}
stringReverse = stringReverse1 + stringReverse;
}
System.out.println("Reversed String : " +stringReverse);
}
}
Output
