Java program to reverse a string

In this post we will learn how to reverse a string in java.


Here is example of the problem  –

Example 1:

Input :  s = "abc"

Output : s = "cba"

Example 2:

Algorithm to Reverse a String:

  • Take or input a String.
  • store it in variable “s”.
  • Take a string rev and initialize with empty string.
  • start i loop start from i=length()-1 to i>=0.
  • get one by one character and store it in rev.
  • And last print rev.

Program for reverse a string:

import java.util.Scanner;
class Main{
public static void main(String[]args){
Scanner sc =new Scanner(;
System.out.println("Enter a string");
String s= sc.nextLine();
String rev="";
for(int i=s.length-1;i>=0;i--){
System.out.println("Reverse string is="+rev)

// Output:

Enter a String 
Reverse string is =cba
 More java string programs:

Java Program to Get Input from User

Java Program to check a String is Palindrome or not

Java program to Count the Total number of Characters in a String





Leave a Comment

%d bloggers like this: