Learn how to find sum of first and last digit of a number in Java using a simple while loop with example code and output.
Code Explanation (Step-by-Step)
- Initialize a number (56789).
- Copy the number into firstDigit int variable .
- Use a while loop to divide the number by 10 until only one digit remains.
- The remaining digit is the first digit.
- Use the modulus operator (% 10) to get the last digit.
- Add the first and last digits to store in sum variable.
- Now print the sum value.
public class SumFirstLastNumber {
public static void main(String[] args) {
int number = 56789;
int firstDigit = number;
while (firstDigit >= 10) {
firstDigit = firstDigit / 10;
}
System.out.println("First digit number: " + firstDigit);
int lastDigit = number % 10;
System.out.println("Last digit number: " + lastDigit);
int sum = firstDigit + lastDigit;
System.out.println("Sum of first and last digit of a number: " + sum);
}
}
Output :-
First digit number: 5
Last digit number: 9
Sum of first and last digit of a number: 14
Java 8 Program to Calculate First and Last Digit Sum
public class FirstLastDigitSum {
public static void main(String[] args) {
int number = -56789;
// Validate input
if (number < 0) {
System.out.println("Invalid input! Please enter a positive number.");
return;
}
String num = String.valueOf(number);
int firstDigit = Character.getNumericValue(num.charAt(0));
int lastDigit = Character.getNumericValue(num.charAt(num.length() - 1));
int sum = firstDigit + lastDigit;
System.out.println("First Digit: " + firstDigit);
System.out.println("Last Digit: " + lastDigit);
System.out.println("Sum of First and Last Digit: " + sum);
}
}
Output for Negative Number :
Invalid input! Please enter a positive number.
Output for Positive Number (56789) :
First Digit: 5
Last Digit: 9
Sum of First and Last Digit: 14
Here are some Java-related programs that will help you understand Java concepts better: