How To Reverse A Number In java?

Last updated on Jun 17,2021 8.8K Views

How To Reverse A Number In java?

edureka.co

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,

Let us get started then,

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:

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:

Reversed Number : 1234567

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.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 7th December,2024

7th December

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES