Java Program for freshers: To reverse a String

               String is a collection of characters. String operations includes concatenation, counting the number of characters, deletion of a character and so on. let us create a reversal of string program as follows.

Logic:

  • ·       Read the input from the user.
  • ·       Create an empty string.
  • ·       Using a for loop, repeat the process.
  • ·       Assign the ‘i’ value to string length-1. Until i>0 , split the character at location ‘i’.
  • ·       Add to the empty string.
  • ·       Finally, print the value.

Program implementation:

  • ·       Import the built in module java.util.Scanner.
  • ·       Create a public class with main() function.
  • ·       An object is created for Scanner.
  • ·       Get the input from the user.
  • ·       Using the above logic, implement the reverse string program.
  • ·       Print the reversed String.

Program:

import java.util.Scanner; //Include the built in package

public class RevStringEg {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter the string which is supposed to be reversed:");

        String inStr = scanner.nextLine();

        String revString = "";

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

            revString += inStr.charAt(i);

        }

         System.out.println("The input String is: " + inStr);

        System.out.println("The Reversed String is: " + revString);

    }

}

Output:

let us compile and execute the program as follows....

C:\raji\blog>javac RevStringEg.java

C:\raji\blog>java RevStringEg

Enter the string which is supposed to be reversed:

welcome to Java World

The input String is: welcome to Java World

The Reversed String is: dlroW avaJ ot emoclew

That’s all. The java program to implement the reversal of string is written. Keep coding!!!

No comments:

Post a Comment