1. Introduction

Reversing a number involves converting the number from its original form to a form where its digits are in reverse order. In this tutorial, we’ll be creating a Java program that takes a number as input and outputs its reverse.

2. Program Steps

1. Import the Scanner class from the java.util package for user input.

2. Define the main class named NumberReverser.

3. Inside the main class, define the main method.

4. Inside the main method, create an object of the Scanner class to take user input.

5. Prompt the user to enter the number they want to reverse.

6. Initialize a variable to store the reversed number and set its initial value to 0.

7. Use a while loop to reverse the digits of the number.

8. Print the reversed number.

3. Code Program

import java.util.Scanner; // 1. Importing Scanner class for user input

public class NumberReverser { // 2. Defining the main class

    public static void main(String[] args) { // 3. Defining the main method

        Scanner input = new Scanner(System.in); // 4. Creating Scanner object to take user input

        System.out.print("Enter the number to reverse: "); // 5. Prompting user to enter the number
        int number = input.nextInt(); // Storing the user input in variable number

        int reversedNumber = 0; // 6. Initializing the reversedNumber variable with 0

        // 7. Using a while loop to reverse the number
        while (number != 0) {
            int digit = number % 10; // Extracting the last digit
            reversedNumber = reversedNumber * 10 + digit; // Adding the extracted digit to the reversed number
            number /= 10; // Removing the last digit
        }

        System.out.println("Reversed Number: " + reversedNumber); // 8. Printing the reversed number

        input.close(); // Closing the Scanner object to avoid memory leak
    }
}

Output:

Enter the number to reverse: 12345
Reversed Number: 54321

4. Step By Step Explanation

– Step 1: The Scanner class from the java.util package is imported to take user input.

– Step 2: The main class named NumberReverser is defined.

– Step 3: The main method is defined inside the NumberReverser class. It’s the entry point of the program.

– Step 4: A Scanner object named "input" is created for taking user input.

– Step 5: The user is prompted to enter a number, and the value 12345 is stored in the variable number.

– Step 6: A variable named reversedNumber is initialized to 0 to store the reversed number.

– Step 7: A while loop is used to reverse the digits of the number 12345. Each digit is extracted, added to reversedNumber, and then removed from number.

– Step 8: The program prints out the reversed number, which is 54321.

– Lastly, the Scanner object is closed to avoid any potential memory leak.