How to reverse a String through a Java Program?

This is a simple program that reads a String using the Scanner class and reverses it using a for loop.

We import the Scanner by writing

import java.util.Scanner
then create a Scanner
Scanner s=new Scanner(System.in);

finally we will start with a blank String. Run a loop the length of the String. Pick one character at a time and concatenate the reverse way.

for(int i=0;i<=string.length()-1;i++)
{

char ch=string.charAt(i);
reverse=ch + reverse;

}

 

 


package strings;

import java.util.Scanner;

public class ReverseString {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String string=s.nextLine();
String reverse="";
for(int i=0;i<=string.length()-1;i++)
{

char ch=string.charAt(i);
reverse=ch + reverse;

}
System.out.println(reverse);

}

}

&nbsp;

Output

Leave a Reply