Full Stack Web Development Internship Program
- 29k Enrolled Learners
- Weekend/Weekday
- Live Class
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,
Numbers can be reversed in Java using different methods, let us take a look at the first one,
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,
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,
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.
Course Name | Date | Details |
---|---|---|
Java Course Online | Class Starts on 19th October,2024 19th October SAT&SUN (Weekend Batch) | View Details |
Java Course Online | Class Starts on 14th December,2024 14th December SAT&SUN (Weekend Batch) | View Details |
edureka.co