Java program to reverse a string

Program to reverse the string

In this article we are going to make a java program to reverse the string reversing an string means lets take an example for better understading suppose we have a string called “prepinsta” so we have to find reverse of that string is “atsniperp” we can do this in two way by using reverse method of StringBuilder class and by using normal for loop with charAt() method.

Java program to reverse a string

Algorithm

  • Take a string input from the user
  • Store it in the variable called “s” in this case
  • After that we will append that string variable in the StringBuilder
  • After that reverse the StringBuilder object by using  the reverse function.

            OR

  • Take a string input from the user
  • Store it in the variable called “s” in this case
  • Take a String “rev” variable and initialize with empty string
  • Start i for loop start from i=s.length()-1 to i>=0
  • Get one by one character with the help of charAt() and store it in the “rev” variable 
  • At last print that “rev” variable

Code in Java(Method-1)

import java.util.Scanner;

public class ReverseString {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		System.out.print( "Enter string : ");
		String s = sc.next();
		StringBuilder sb = new StringBuilder();
                sb.append(s);
                System.out.println( "String is : "+sb);
                sb.reverse();
                System.out.println("Reversed string is : "+sb);   
       }

}
This code is contributed by Shubham Nigam (Prepinsta Placement Cell Student)

Code in Java(Method-2)

import java.util.Scanner;
public class ReverseString {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a string");
    String s = sc.next();
    String rev = "";

    for (int i = s.length()-1; i >=0; i--) {
      rev=rev+s.charAt(i);
    }
    System.out.println(rev);
  }
}
This code is contributed by Shubham Nigam (Prepinsta Placement Cell Student)

Output

Enter string : prepinsta
String is : prepinsta
Reversed string is : atsniperp