Reverse a Number
Reverse the digits of a number using a loop.
BeginnerTopic: Module 3: Loop Programs
Java Reverse a Number Program
This program helps you to learn the fundamental structure and syntax of Java programming.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int rev = 0;
while (n != 0) {
int d = n % 10;
rev = rev * 10 + d;
n /= 10;
}
System.out.println("Reversed number = " + rev);
sc.close();
}
}Output
Enter a number: 1234 Reversed number = 4321
Understanding Reverse a Number
We repeatedly take the last digit and build a new reversed number.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.