Example
Java
public class NumberReverser {
public static int reverseNumber(int number) {
int reversed = 0;
while (number != 0) {
int digit = number % 10; // Get the last digit
reversed = reversed * 10 + digit; // Append digit to reversed number
number /= 10; // Remove the last digit from number
}
return reversed;
}
public static void main(String[] args) {
int originalNumber = 1234;
int reversedNumber = reverseNumber(originalNumber);
System.out.println("Reversed Number: " + reversedNumber);
}
}

You can also try this code with Online Java Compiler
Run Code
Output
Reversed Number: 4321
This code utilizes basic arithmetic operations to separate and reassemble the number in reverse order. The loop continues until all digits have been processed and the original number becomes zero.
Methods to Reverse a Number in Java
There are several techniques in Java to reverse a number, each using different logic and Java features. Let's explore the most common methods: using a while loop, using recursion, and using the StringBuilder class.
Using While Loop
The while loop method is very direct and efficient for reversing a number. This method follows the step-by-step algorithm we discussed earlier. It continually extracts the last digit of the number and builds the reversed number until the original number is reduced to zero.
How it Works
-
Initialize the Reversed Number: Start with a variable reversed set to zero. This variable will store the final reversed number.
-
Loop Until No More Digits: Use a while loop that runs as long as the original number is not zero.
-
Extract & Append Digits: Inside the loop, extract the last digit of the number using the modulo operator (%). Add this digit to the reversed number, but first, shift the current digits of reversed to the left by multiplying by 10. This makes space for the new digit.
- Reduce the Number: After extracting the digit, divide the original number by 10 to drop the last digit, effectively shrinking the number.
Example
Java
public class ReverseNumberWithLoop {
public static int reverse(int number) {
int reversed = 0;
while (number != 0) {
int lastDigit = number % 10; // Extract the last digit
reversed = reversed * 10 + lastDigit; // Append it to the reversed number
number /= 10; // Drop the last digit from the number
}
return reversed;
}
public static void main(String[] args) {
int original = 4567;
int reversed = reverse(original);
System.out.println("Original: " + original + " - Reversed: " + reversed);
}
}

You can also try this code with Online Java Compiler
Run Code
Output
Original: 4567 - Reversed: 7654
This code successfully reverses the number by using basic arithmetic operations without any need for complex structures or external libraries. It's a clear and efficient way to see how numbers can be manipulated using loops in Java.
Using Recursion
Recursion is a programming technique where a method calls itself to solve a problem. In the context of reversing a number in Java, recursion allows us to simplify the process by breaking down the problem into smaller, more manageable tasks.
How It Works
-
Base Case: This is crucial in recursion to stop the recursive call. For reversing a number, the base case occurs when the number has no more digits left (i.e., the number is 0).
-
Recursive Call: In each recursive step, we split the number into two parts: the last digit and the rest of the number. We then call the method again with the rest of the number, building up the reversed number as we return from each recursive layer.
- Building the Reversed Number: As the recursive calls return, we assemble the reversed number by multiplying the current reversed number by 10 and adding the last digit of the current recursive call's number.
Example
Java
public class ReverseNumberRecursively {
public static int reverse(int number, int reversed) {
if (number == 0) {
return reversed; // Base case: If number is zero, return reversed
} else {
int lastDigit = number % 10; // Get the last digit
return reverse(number / 10, reversed * 10 + lastDigit); // Recursive call
}
}
public static void main(String[] args) {
int original = 2345;
int reversed = reverse(original, 0);
System.out.println("Original: " + original + " - Reversed: " + reversed);
}
}

You can also try this code with Online Java Compiler
Run Code
Output
Original: 2345 - Reversed: 5432
In this example, reverse is called recursively, decreasing the original number by removing the last digit (by dividing by 10) and building the reversed number by appending this last digit. The process repeats until the original number is reduced to 0, at which point the complete reversed number is returned.
Note -: Recursion provides a clean and logical way to reverse numbers, making it easier to understand how smaller parts of a problem are tackled one step at a time.
Using StringBuilder Class
The StringBuilder class in Java provides a simple and efficient way to manipulate strings. When it comes to reversing a number, we can use this class to handle the number as a string, reverse the string, and then convert it back to a number.
How it Works
-
Convert Number to String: Start by converting the integer number to a string. This allows us to use the string manipulation capabilities of the StringBuilder.
-
Reverse the String: Create a StringBuilder instance with the number string. Use the reverse() method of StringBuilder to reverse the string in place.
- Convert Back to Integer: Once the string is reversed, convert it back to an integer using Integer.parseInt().
Example
Java
public class ReverseNumberWithStringBuilder {
public static int reverse(int number) {
StringBuilder sb = new StringBuilder();
sb.append(number); // Append the number to StringBuilder
sb.reverse(); // Reverse the string
return Integer.parseInt(sb.toString()); // Convert the reversed string back to an integer
}
public static void main(String[] args) {
int original = 56789;
int reversed = reverse(original);
System.out.println("Original: " + original + " - Reversed: " + reversed);
}
}

You can also try this code with Online Java Compiler
Run Code
Output
Original: 56789 - Reversed: 98765
This method is particularly useful for those who prefer working with strings and want a method that is both readable and straightforward. The StringBuilder is efficient and makes the code easy to understand and maintain.
Frequently Asked Questions
Can all numbers be reversed using these methods?
Yes, all integers, including negative numbers, can be reversed using these methods. For negative numbers, handle the sign separately to maintain its negativity after reversal.
What happens when reversing a number leads to overflow?
If reversing a number results in a value beyond the range of int data type, it will cause an overflow, potentially leading to incorrect results. It's important to check the size of the number before reversing.
Is one method better than the others?
Each method has its merits depending on the situation. Using loops is straightforward and fast, recursion is elegant but could lead to stack overflow with very large numbers, and the StringBuilder method is very readable and easy to implement but less numerical.
Conclusion
In this article, we have talked about the various methods to reverse a number in Java, each offering a unique approach to solving the problem. We started our article with a simple algorithm using a while loop, then we moved on to a more advanced recursive method that elegantly breaks down the problem, and finally, we used the StringBuilder class for those preferring to work with string manipulations.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.