Reverse a Number in Java

In this section, we will reverse a number using three ways .

  • Using while loop
  • Using for loop
  • Using recursion

Example – Program to Reverse a number using while loop

public class ReverseNumber {
  public static void main(String[] args) {
    int reversNum = 0;    
    int num = 5678;
    
    while (num != 0) {
      int remaining = num % 10;
      reversNum = reversNum * 10 + remaining;
      num = num / 10;
    }
    System.out.println("Reverse of the number is: " + reversNum);
  }
}

Output

Reverse of the number is: 8765

Example – Reverse a number using for loop

public class ReverseNumber {
  public static void main(String[] args) {
    int reversNum = 0;
    int num = 5678;

    for (; num != 0; num /= 10) { // ; is used for no initialization expression

      int remaining = num % 10;
      reversNum = reversNum * 10 + remaining;
      
    }

    System.out.println("Reverse of the number is: " + reversNum);
  }
}

Output

Reverse of the number is: 8765

Example – Reverse a number using recursion

public class ReverseNumber{
  public static void reverseNumber(int number) {
    if (number < 10) {
      System.out.println(number);
      return;
    } else {
      System.out.print(number % 10);
      reverseNumber(number / 10);
    }
  }

  public static void main(String args[]) {
    int num=56781;
    System.out.print("Reverse of the number is : ");

    reverseNumber(num);
  }
}

Output

Reverse of the number is : 18765