Java Program for Reverse String

Reverse String

In this post, we will see, How to write a program for reverse String in java. 

A java string is an object representing a sequence of characters.  

Let's create a string variable 

Input:- String str = "Java";

Output:- "avaj"

Code Using an Inbuilt method ( reverse() ) of  StringBuilder

import java.util.Scanner;


public class ReverseString {


public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter a string: ");

String str = sc.nextLine();


StringBuilder sb = new StringBuilder(str);


System.out.println("Reversed string: " + sb.reverse().toString());


}


}

Output:- 

Enter a string: java
Reversed string: avaj

Explanations-

  • Created the Object of Scanner class
  • Ask the user to Enter a String using Standard input stream
  • Created the object of StringBuilder class
  • Then used the reverse() method of StringBuilder class 

Another process of Code using for loop 

import java.util.Scanner;


public class ReverseString {


public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter a string: ");

String str = sc.nextLine();

char[] ch = str.toCharArray();

        String rev = "";

       for( int i = (ch.length-1); i >= 0; i-- ) {

       rev = rev + ch[i];

       }

       System.out.println("Reverese String : "+rev);

    }


}


Output:-

Enter a string: java
Reverse string: avaj

Explanations-
  • Created the Object of Scanner class
  • Ask the user to Enter a String using Standard input stream
  • Store the input string in str variable
  • Then Convert the string to char array 
  • the iterate the character from last to first 
  • Then store the char value in rev string variable
Hope this program is helpful, please put your valuable comment and share with your friends-------

Post a Comment

Previous Post Next Post