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
- String Programs in Java with Output
- Java Program to Count Number of Duplicate Words in String
- Java Program to Count Number of Words in Given String
- Java Program to Count the Number of Occurrences of Substring in a String
- Java Program to Count the Occurrences of Each Character in String
- Java Program to Merge two String Arrays
- Java Program to Remove Duplicate Words from String
- Java Program to Reverse a String(5 ways)
- Java Program to Reverse Each Word of a String
- Java Program to Swap Two Strings
- How to Check if the String Contains only Digits
- How to Check if the String Contains only Letters
- How to Check If the String Contains Only Letters or Digits
- Java Program to Check if Input String is Palindrome
- Java Program to Find all Permutations of String
- How to Remove or Trim All White Spaces from a String in Java
- How to Remove Leading and Trailing White Space From a String in Java
- Java Program to Count Duplicate Characters in a String
- Remove Character from String in Java (Java 8)
- Java Program to Count Vowels and Consonants in a String (Java 8)
- 4 Ways to Find First Non-Repeated Character in String in Java
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