Program to display the input string from backward

Display the input string in reverse order

The program displays the input String in reverse order and for this action, you can use the substring method.

The syntax for the built_in method substring is:-

Syntax : 
public String substring(int begIndex, int endIndex)
Parameters : 
beginIndex :  the begin index, inclusive.
endIndex :  the end index, exclusive.
Return Value : 
The specified substring.

import java.util.Scanner; //Importing Scanner class to get input from the user

import java.lang.String; //Importing Scanner class from the package lang of java project

public class Backwards

{

    // instance variables

    private String x;

    public void reverse()

    {

        System.out.println(“Enter a String”); //Instruction to user

        x= new Scanner(System.in).nextLine();

      int a= x.length(); //counting number of digit in value of variable x and storing in variable a

        //declaring and initializing the variable

        int b=0; 

        int  c=1; 

        String s1=” “; //declaring and initializing the variable s1

        for(int i=1;i<=a;i++)

        {

            String s= x.substring(b,c); //Built_in method used to abstract fixed characters from the provided string

            s1=s+s1;

            b++;

            c++;

        }

        System.out.println(“The string in reverse is “);

        System.out.println(s1);

    }

    public static void main(String []args)

    {

        Backwards r= new Backwards();

        r.reverse();

    }

}

The output of the above program looks like this:-

Leave a comment