Java Program to Reverse a Number

In this tutorial, we will learn how to write a Java program to reverse a number using a while loop and a for loop in Java.
We will read input from the console using Scanner class.

1. Java Program to Reverse a Number using a while loop in Java

package com.javaguides.java.tutorial;

import java.util.Scanner;

/**
 * Java Program to reverse a Number using a while loop in Java
 * 
 * @author https://www.sourcecodeexamples.net/
 *
 */
public class JavaProgram {
    public static void main(String[] args) {

        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println("Enter the number :");
            int num = scanner.nextInt();

            int reversed = 0;

            while (num != 0) {
                int digit = num % 10;
                reversed = reversed * 10 + digit;
                num /= 10;
            }

            System.out.println("Reversed Number: " + reversed);
        }
    }
}
Output:
Enter the number :
12345
Reversed Number: 54321

2. Java Program to Reverse a number using a for loop in Java

package com.javaguides.java.tutorial;

import java.util.Scanner;

/**
 * Java Program to reverse a Number using a for loop in Java
 * 
 * @author https://www.sourcecodeexamples.net/
 *
 */
public class JavaProgram {
    public static void main(String[] args) {

        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println("Enter the number :");
            int num = scanner.nextInt();

            int reversed = 0;

            for (; num != 0; num /= 10) {
                int digit = num % 10;
                reversed = reversed * 10 + digit;
            }

            System.out.println("Reversed Number: " + reversed);
        }
    }
}
Output:
Enter the number :
12345
Reversed Number: 54321

Related Java Programs


Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments