Java Program to Reverse a Number

In this Java program, you’ll learn how to Reverse a Number using Java programming language.  

How to reverse a number? 

Example 1: using for loop 

[Maxbutton id=”1″ url=”https://coderseditor.com/?id=824″ text=”RUN CODE SNIPPET” ]

class Main { 
  public static void main(String[] args) { 
    int num = 123456789, reversed = 0; 
    for(;num != 0; num /= 10) { 
      int digit = num % 10; 
      reversed = reversed * 10 + digit; 
    } 
    System.out.println("Reversed Number: " + reversed); 
  } 
}

OUTPUT 

Reversed Number: 987654321

Example 2: using while loop 

RUN CODE SNIPPET
class Main { 
  public static void main(String[] args) { 
    int num = 123456789, reversed = 0; 
    while(num != 0) { 
      int digit = num % 10; 
      reversed = reversed * 10 + digit; 
      num /= 10; 
    } 
    System.out.println("Reversed Number: " + reversed); 
  } 
}

OUTPUT 

Reversed Number: 987654321

Share:

Leave A Reply

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

You May Also Like

Java is a popular programming language that is used to develop a wide range of applications. If you are a...
  • Java
  • March 6, 2023
Java is a programming language and computing platform that is used to create various types of applications. It is used...
  • Java
  • March 6, 2023
In this post, you’ll learn how to download and install JUnit in Eclipse so that you can use in your...
  • Java
  • October 9, 2022