In java, to swap first and last digit of number we can use loop concepts such as for loop and while loop. If the input number is 2345 then after swapping the first and last digit in that number, resulting output will be 5342.
In this article we will learn an example, detailed logic and program explanation for better understanding.
Required Knowledge
- Java programming basics
- Java Operators
- Loop concepts
Problem Statement
We need to write a java program to swap first and last digit of a number. The program should take a integer number as input and should swap the first and last digit without affecting the mid values of the number.
Let’s see an example,
Example
For an integer input value 4567, Output should be 7564.
Explanation:
Input Integer number: 4567
Take last digit from the number = 7
Take first digit from the number = 4
Hence, for the input number 4567, after swapping first and last digit it become 7564.
Logic to Swap first and last digit
There are multiple logics to swap first and last digit in a given number in the java programming language.
Logic 1: Using loops
- Take an input number. Calculate lastDigit using number%10 storing the last digit. Using number<10, check if the entered number has less than two digits.
- If it is a single digit, it says enter at least two digits and exits the program using return.
- A copy of the original number is stored in the variable num for later use.
- It uses a loop (typically a while or for loop) to count the digits in the original number (count), excluding the first digit, and simultaneously removes the last digit until number>0.
- After the loop completes, the variable number now holds the first digit of the original number. This is stored in the variable firstDigit.
- The midNum is calculated as num%power to isolate the middle digits correctly.
- Finally, reconstruct the number with swapped first and last digits using the expression lastDigit*(int)Math.pow(10, count)+midNum*10+firstDigit, it will print the swapped result.
Logic 2: Without using conditional statements or looping statements
- Take an input number. First checks if the entered number has less than two digits using (number<10). If it is a single digit, it says enter at least two digits and exits the program using return.
- Power is calculated as
- Calculate lastDigit using number%10 storing the last digit, and firstDigit is calculated as (int)(number/Math.pow(10, power)), extracting the first digit of the number.
- A variable a is computed as (int)(firstDigit/Math.pow(10, power)), creating a number where all digits except the last one are zeros.
- A variable b is derived using number%a which effectively removes the first digit from the number. And number is updated to b/10 , removing the last digit from b.
- Finally, reconstruct the number with swapped first and last digits using the expression lastDigit*(int)Math.pow(10, power)+b*10+firstDigit, it will print the swapped result.
Java program to swap first and last digit
Program 1: Using while loop
In the below program we are using while loop to swap first and last digit in a given number in Java.
import java.util.Scanner;
public class SwapFirstandLastDigit {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a number");
int number = s.nextInt();
int num = number;
int count = 0;
int lastDigit = number % 10;
if(number < 10) {
System.out.println("Enter a number with at least two digits.");
return; // Exit the program gracefully
}
while (number > 10) {
count++;
number = number / 10; // removes last digit until number greater than 10
}
int firstDigit = number;
num =num/10;// removes last digit
int power =(int) Math.pow(10, count-1); // to get middle values, we will do count-1 from the updated num
int midNum = num%power;
int x = lastDigit*(int)Math.pow(10, count)+midNum*10+firstDigit;
System.out.println("After swapping first and last digit: ");
System.out.println(x);
s.close();
}
}
Output:
Enter a number
87623
After swapping first and last digit:
37628
Java program explanation to swap first and last digit
- The program takes an integer input from the user using Scanner.
- Checks if the input number has at least two digits; if not, it asks the user to enter a valid number and terminates.
- Computes the last digit of the input number using modulus operation (
number % 10
). - Counts the number of digits in the input number by repeatedly dividing it by 10 until it’s greater than 10.
- Retrieves the first digit of the original number once the loop terminates.
- Removes the last digit from the original number (
num = num / 10
) to prepare for middle digits extraction. - Calculates a power of 10 (
Math.pow(10, count-1)
) to isolate the middle digits. - Extracts the middle digits from the modified number (
num % power
). - Constructs a new number by swapping the first and last digits and printing the result and close scanner class.
Program 2: Using for loop
In the below program we are using for loop to swap first and last digit in a given number in Java.
import java.util.Scanner;
public class SwapFirstandLastDigit {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a number");
int number = s.nextInt();
int num1 = number;
int count = 0;
int lastDigit = number % 10;
int num = number;
if(num < 10) {
System.out.println("Enter a number with at least two digits.");
return; // Exit the program gracefully
}
for (;num > 10;) {
count++;
num = num / 10; // removes last digit until number greater than 0
}
int firstDigit = num;
num1 =num1/10;// removes last digit
int power =(int) Math.pow(10, count-1); // to get middle values, we will do count-1 from the updated num
int midNum = num1%power;
int x = lastDigit*(int)Math.pow(10, count)+midNum*10+firstDigit;
System.out.println("After swapping first and last digit: ");
System.out.println(x);
s.close();
}
}
Output:
Enter a number
345678
After swapping first and last digit:
845673
Java program explanation to swap first and last digit
- The program reads an integer input from the user.
- Checks if the input has at least two digits; if not, asks the user to enter a valid number.
- Counts the number of digits in the input using a loop.
- Extracts the first and last digits of the input number.
- Swaps the first and last digits to form a new number.
- Prints the new number after swapping.
- Closes the Scanner object to release resources.
Program 3: Without Using looping statements
In the below program we are not using any looping statements to swap first and last digit in a given number in Java.
import java.util.Scanner;
public class SwapFirstandLastDigit {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a number");
int number = s.nextInt();
if (number < 10) {
System.out.println("Please enter a number with at least two digits.");
return;
}
int power = (int) (Math.log10(number));
int lastDigit = number % 10; // last digit will be stored here
int firstDigit = (int) (number / Math.pow(10, power)); // 1
int a = (int) (firstDigit * Math.pow(10, power)); // ex: 1, if user enters 4 digits num :1000
int b = number % a; // removes first digit
number = b / 10; // removes last digit
number = (lastDigit * (int) (Math.pow(10, power))) + number * 10 + firstDigit;
System.out.println(number);
s.close();
}
}
Output:
Enter a number
123456
623451
Java program explanation to swap first and last digit
- The program takes an integer input from the user.
- Checks if the input has at least two digits; if not, asks for valid input and exits.
- Determines the number of digits (
power
) using logarithmic calculation. - Extracts the last digit of the input.
- Calculates the first digit of the input.
- Adjusts the input number by removing the last digit and managing the digits for swapping.
- Constructs the swapped number using the adjusted digits.
- Outputs the swapped number.
- Closes the
Scanner
object to release resources.
Conclusion
In this article, we have learnt writing a Java program to swap the first and last digit in a number. We understood the logic and seen the program using while loop and foop and also without using any loops in Java. Hope this article helped you in understanding of the programs.
You can also check our another awesome tutorials
- Java Program to check Perfect number
- Check if a triangle is equilateral, isosceles or scalene in Java
- Java program to print all the odd numbers in a range
- Program to print sum of even numbers in a range in Java
Happy Java Programming!