Java is a versatile programming language with different applications. Major reason for this is the flexibility and ease it provides at granular level. this article will help you write Java Program To Reverse A Number. Following pointers will be covered in this article,
Java Program To Reverse A Number
Numbers can be reversed in Java using different methods, let us take a look at the first one,
Using A While Loop
The usage of while loop can be made to reverse a set of numbers. Here is the program,
public class Main { public static void main(String[] args){ int number=4321,reverse=0; while(number!=0){ int dig=number%10; reverse=reverse*10+dig; number/=10; } System.out.println("Reversed Number: " + reverse); } }
Output:
Reversed Number : 1234
Explanation:
- An integer number is declared in this example.
- The number is divided by 10, and the remainder is stored in a variable dig.
- Thus, the last digit of number, i.e. 1 is stored in the variable dig.
- The variable reverse is multiplied by 10 (this adds a new place in number), and dig is added to it. Here, 0*10+1=1.
- The number is then divided by 10, such that it contains the first three digits: 432.
- All the numbers are iterated in the same manner.
Let us continue with this ‘Java Program To Reverse A Number’ article,
Using A For Loop
Instead of a while loop, we make use of for loop in the following example:
public class Main { public static void main(String[] args) { int number = 764321, reverse = 0; for(;number != 0; number /= 10) { int dig = number % 10; reverse = reverse * 10 + dig; } System.out.println("Reversed Number: " + reverse); } }
It must be noted that, initialization expression is not used here.
Output:
This is the final bit of this article, let us see how recursion helps here,
Using Recursion
When a method calls itself continuously, then the process is known as recursion.
import java.util.Scanner; class Main { //Reverse Method public static void recurse(int number) { if(number < 10) { System.out.println(number); return; } else{ System.out.print(number % 10); //Method calling itself recurse(number/10); } } public static void main(String args[]) { int num=987654321; System.out.print("Reversed Number:"); recurse(num); System.out.println(); } }
Output:
Reversed Number : 123456789
These methods provide a holistic approach to reverse a number in the programming language of java.
Thus we have come to an end of this article on ‘Java Program To Reverse A Number’. If you wish to learn more, check out the Java Online Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.
Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.