Reverse number in Java using for loop

In this post we solve a slightly difficult problem, that is trying to reverse the digits of a number. See below on example of Reverse number in Java using for loop.

Reverse number in Java using for loop

This code will be a lot longer than other examples we have, but we have commented it so it is easy to follow. What we did is extract the digit from the right side and add it to the reverse number shifting left. See below example:
/**
 * An example program that Reverse number in Java using for loop.
 */
public class ExampleProgram {
    public static void main(String[] args) {
        int someNumber = 123;
        int reversedDigitNumber = 0;
        int n = someNumber;
        for (; n > 0;) {
            // extract last digit
            int digit = n % 10;
            // shift number and add digit to the right
            reversedDigitNumber = (reversedDigitNumber * 10) + digit;
            // remove the digit processed
            n = n / 10;
        }
        System.out.println("Original Number: " + someNumber);
        System.out.println("Reversed Digit Number: " + reversedDigitNumber);
    }
}

And reversing 123 in the above code will yield the below output.

Original Number: 123
Reversed Digit Number: 321