BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java program to reverse a number using for, while and recursion

Last Updated: September 15, 2022 by Chaitanya Singh | Filed Under: Java Examples

In this tutorial, you will learn how to reverse a number in Java. For example if a given input number is 19 then the output of the program should be 91. There are several ways to reverse a number in Java. We will mainly discuss following three techniques to reverse a number.

Table of contents

  • Program 1: Reverse a number using while Loop
  • Program 2: Reverse a number using for Loop
  • Program 3: Reverse a number using recursion

 

Reverse number

Program 1: Reverse a number using while Loop

  • In this program, user is asked to enter a number.
  • This input number is read and stored in a variable num using Scanner class.
  • The program then uses the while loop to reverse this number.
  • Inside the while loop , the given number is divided by 10 using % (modulus) operator and then storing the remainder in the reversenum variable after multiplying the reversenum by 10. When we divide the number by 10, it returns the last digit as remainder. This remainder becomes the first digit of reversenum, we are repeating this step again and again until the given number become zero and all the digits are appended in the reversenum.
  • At the end of the loop the variable reversenum contains the reverse number and the program prints the value of this variable as output.
import java.util.Scanner;
class ReverseNumberWhile
{
   public static void main(String args[])
   {
      int num=0;
      int reversenum =0;
      System.out.println("Input your number and press enter: ");
      //This statement will capture the user input
      Scanner in = new Scanner(System.in);
      //Captured input would be stored in number num
      num = in.nextInt();
      //While Loop: Logic to find out the reverse number
      while( num != 0 )
      {
          reversenum = reversenum * 10;
          reversenum = reversenum + num%10;
          num = num/10;
      }

      System.out.println("Reverse of input number is: "+reversenum);
   }
}

Output:

Input your number and press enter: 
145689
Reverse of input number is: 986541

Program 2: Reverse a number using for Loop

The logic in this program is same as above program, here we are using for loop instead of while loop. As you can see, in this program we have not used the initialization and increment/decrement section of for loop because we have already initialized the variables outside the loop and we are decreasing the value of num inside for loop by diving it by 10.

import java.util.Scanner;
class ForLoopReverseDemo
{
   public static void main(String args[])
   {
      int num=0;
      int reversenum =0;
      System.out.println("Input your number and press enter: ");
      //This statement will capture the user input
      Scanner in = new Scanner(System.in);
      //Captured input would be stored in number num
      num = in.nextInt();
      /* for loop: No initialization part as num is already
       * initialized and no increment/decrement part as logic
       * num = num/10 already decrements the value of num
       */
      for( ;num != 0; )
      {
          reversenum = reversenum * 10;
          reversenum = reversenum + num%10;
          num = num/10;
      }

      System.out.println("Reverse of specified number is: "+reversenum);
   }
}

Output:

Input your number and press enter: 
56789111
Reverse of specified number is: 11198765

Program 3: Reverse a number using recursion

Here we are using recursion to reverse the number. A method is called recursive method, if it calls itself and this process is called recursion. We have defined a recursive method reverseMethod() and we are passing the input number to this method.

This method then divides the number by 10, displays the remainder and then calls itself by passing the quotient as parameter. This process goes on and on until the number is in single digit and then it displays the last digit (which is the first digit of the number) and ends the recursion.

Note: You do not get confused between quotient and remainder so let me explain a bit about them here, / operator return quotient and % operator returns remainder. For example: 21/5 would return 4 (quotient), while 21%5 would return 1(quotient).

import java.util.Scanner;
class RecursionReverseDemo
{
   //A method for reverse
   public static void reverseMethod(int number) {
       if (number < 10) {
	   System.out.println(number);
	   return;
       }
       else {
           System.out.print(number % 10);
           //Method is calling itself: recursion
           reverseMethod(number/10);
       }
   }
   public static void main(String args[])
   {
	int num=0;
	System.out.println("Input your number and press enter: ");
	Scanner in = new Scanner(System.in);
	num = in.nextInt();
	System.out.print("Reverse of the input number is:");
	reverseMethod(num);
	System.out.println();
   }
}

Output:

Input your number and press enter: 
5678901
Reverse of the input number is:1098765

Example: Reverse an already initialized number
In all the above programs, the number is entered by the user, however if do not want the user interaction part and want to reverse a hardcoded number then this is how you can do it. Here num is initialized with a number, you can just change the value to reverse a different number.

class ReverseNumberDemo
{
   public static void main(String args[])
   {
      int num=123456789;
      int reversenum =0;
      while( num != 0 )
      {
          reversenum = reversenum * 10;
          reversenum = reversenum + num%10;
          num = num/10;
      }

      System.out.println("Reverse of specified number is: "+reversenum);
   }
}

Output:

Reverse of specified number is: 987654321

Related Java Examples :

  • Java Program to reverse the Array
  • Sort an Array in Descending (Reverse) Order – Java
  • Java Program to Reverse a String using Recursion
  • Java Program to print number of elements in an array
❮ Java TutorialJava Programs ❯

Top Related Articles:

  1. Java Program to Calculate average using Array
  2. Java Program to Calculate Simple Interest
  3. Neon Number in Java with example
  4. Tech Number Program in Java
  5. java program to find factorial of a given number using recursion

Tags: Java Numbers

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Sanket says

    May 1, 2014 at 7:40 AM

    Reverse number i want explanation mean in layman term ….plz explain the concept of all logic that it happening in middle of program plz explain like u are not writing a program instead your are writing that all math sum in a paper ….

    Reply
  2. Gabriel says

    September 23, 2014 at 3:37 PM

    Hi what does it mean when ” int num=0 “? Does that mean all integers start from 0?

    Reply
    • Pankaj says

      June 12, 2015 at 8:40 AM

      by int num=0; it says that not garbage velue(a value which affects the outcome of a result) will be stored in the variable num

      Reply
    • Sooraj S says

      February 23, 2017 at 3:50 PM

      int num=0; means that the variable is initialized with the value zero(0).

      Reply
    • Amankumar says

      July 24, 2017 at 4:21 AM

      No…here num is a variable and it is assigned as value 0 which mean num has null value so that it can be used further

      Reply
  3. Kumar says

    July 6, 2015 at 1:46 PM

    In Reverse a number using recursion method:
    It is not suitable numbers. bez it is failed the test case at
    Input as :: 1200 or zero has last digit.

    Please correct me if i am wrong.
    Thanks
    Praveen

    Reply
  4. Ashwin says

    July 11, 2015 at 8:03 AM

    How do i use reverse of a number concept in this palindrome program.. Please help me use it…

    Reply
  5. Minal says

    August 12, 2015 at 5:01 AM

    @ Saket
    Possible explanation is:
    Let x=123, then ⌊log10x⌋=2. As ⌊x10−1⌋=⌊12.3⌋=12 and ⌊x10−2⌋=⌊1.23⌋=1, we have

    123×102−99(12×10+1×1)=123×100−99×121=12300−11979=321

    Reply
  6. hema says

    August 25, 2015 at 2:27 PM

    Hello
    can anyone tell me how to reverse a number which starts with zero..like 0213,0334

    Reply
  7. rufert says

    September 17, 2015 at 10:03 AM

    Can someone please help me how to print this in outpu
    987654321
    87654321
    7654321
    654321
    54321
    4321
    321
    21
    1

    Reply
    • Liza says

      March 17, 2016 at 6:50 AM

      public static void printNumbers(int numbers)
      {
      String strNum = Integer.toString(numbers);
      for (int i = 0; i < strNum.length(); i++)
      {
      System.out.println(strNum.substring(i));
      }
      }
      public static void main(String[] args)
      {

      printNumbers(987654321);
      }

      Reply
  8. kiran says

    January 13, 2016 at 11:20 AM

    if you want to reverse a number which starts with zero,you should use string data type, as input of 0212 in int data type will takes as 212.

    Reply
  9. P.Brooks says

    February 2, 2016 at 7:55 PM

    How do you add a max string length to the reverse number program? For example, the number must be positive and have a maximum of six digits.

    Reply
  10. Balaji Singh says

    April 1, 2016 at 5:30 PM

    Hi,

    I need an help from you .

    Question is below :

    Consider that you have two ArrayList first ArrayList takes only Strings , and second ArrayList takes only Integer.

    Now I want this two Array list to added to HashMap and iterate it also .

    So how would you do ?

    Reply
  11. Balaji Singh says

    April 1, 2016 at 5:31 PM

    And Thanks for all your Programs and concepts that you published.
    Your concepts are very much good , informative and quite easy to understand.

    Reply
  12. Avi says

    July 26, 2016 at 2:33 PM

    Really great website to start with! ^_^

    Reply
  13. Kathryn says

    September 3, 2016 at 12:36 AM

    Why is it that reversenum isn’t always zero? The way I’m reading, say we input 205. reversenum = 0 * 10
    Reversenum= 0 + 5 = 5
    num = 205/10 = 20

    So printing reversenum would just print 5? I don’t get that.

    Reply
  14. Issei says

    September 4, 2016 at 1:53 PM

    Hello
    i am having trouble understanding these lines of code.
    Could please explain how it works?
    {
    reversenum = reversenum * 10;
    reversenum = reversenum + num%10;
    num = num/10;
    }

    Reply
    • Sipra Mallick says

      November 11, 2016 at 12:02 PM

      Suppose u want to reverse a number 123.
      As we have initialized reversenum=0
      so,
      reversenum = 0 * 10;
      reversenum = 0 + 123%10; [123%10=3. so reversenum becomes 3]
      num = 123/10;[num stores the value as 12]

      In the next iteration,
      reversenum = 3* 10;
      reversenum = 30 + 12%10;[reversenum=30+2=32.]
      num = 12/10;[num stores the value 1]

      In the last iteration
      reversenum = 32 * 10;
      reversenum = 320 + 1%10;[reversenum=320+1=321]
      num = 1/10;

      Here the looping stops and the result is printed as 321.

      Reply
    • Wuu says

      November 27, 2016 at 1:01 AM

      executes a block of statements repeatedly until the condition(Boolean expression) returns false, so we choose a number like 325

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

      the step
      1. num =325 != 0
      2. reversenum = 0*10=0
      3. reversenum = 0+(325%10) = 0+5=5
      4. num = 325/10 = 32
      5. num =32 !=0
      6. reversenum = 5 *10 = 50
      7. reversenum = 50 + (32 % 10) = 50+2=52
      8. num=32/10 = 3
      9 num = 3 != 0
      10. reversenum = 52 *10 =520
      11. reversenum = 520 + (3 % 10) = 520+3 = 523
      12. num = 3/10 =0
      final num =0 return false, so we get the reverse number 523.

      Reply
      • md raza says

        January 13, 2017 at 8:24 AM

        Finally, Now i was able to understand the concept

        Reply
  15. Ken Santos says

    February 24, 2017 at 12:20 AM

    Can anyone write a program that will accept number and produces sequence number in alternate arrangement and reverse order.

    Enter number: 5
    Output
    5142332415

    Reply
  16. GUL says

    April 24, 2017 at 6:11 AM

    why did you multiply reversenum by 10

    Reply
  17. Sabir says

    May 6, 2017 at 1:58 AM

    hello Sir I am facing a problem with the logic.The output of 012 is not coming as 210 only 21! Why?

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Examples

  • Check Odd-even
  • Linear Search
  • Binary Search
  • Floyd's Triangle
  • Reverse number
  • Random Number
  • first n prime numbers
  • Disp prime Numbers
  • Check Prime number
  • Palindrome String
  • Find factorial
  • Sum of elements of Array
  • Area of rectangle
  • Area of Square
  • Area of Triangle
  • Circle

Tutorials

  • Java Tutorial
  • OOPs Concepts
  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap