In this program, we will learn to code the Java Program to Find Last Digit of a Number. Let’s understand How to Find Last Digit of a Number in Java Programming Language. In previous programs, we have also discussed and learned to code the Java Program to add digits of a number.
Last Digit of a Number
Suppose a number 12345 so the last digit of the number is 5. We have to write a program to print the last digit of the given Number in Java Programming Language.
Let’s get straight into the code of the Java Program to Find Last Digit of a Number.
Java Program to Find Last Digit of a Number
import java.util.*; import java.lang.*; import java.io.*; class Main { public static void main (String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the number: "); int num = sc.nextInt(); int lastDigit = num%10; System.out.println("The last Digit of the Number is "+lastDigit); } }
Output
Enter the number: 123345
The last Digit of the Number is 5
Output
Enter the number: 4567
The last Digit of the Number is 7
How Does This Program Work ?
Scanner sc = new Scanner(System.in); System.out.println("Enter the number: "); int num = sc.nextInt();
In this program, we take the number as input from the user using Scanner
class in Java and store it in variable num of int datatype.
int lastDigit = num%10;
Then, using the % operator we calculate the last digit of the number. “%” modulo operator is used to find the remainder of the result when we divide two numbers using the % operator. For example, when 12345 is divided by 10 then the quotient is 1234 and the remainder is 5 i.e. 12345 % 10 = 5.
System.out.println("The last Digit of the Number is "+lastDigit);
Then, we display the result using the System.out.println()
function.
This is the Java Program to Find Last Digit of a Number.
Conclusion
I hope after going through this post, you understand the Java Program to Find Last Digit of a Number. If you have any doubt regarding the topic, feel free to contact us in the comment section. We will be delighted to help you.
Also Read:
Write a program to accept a number through the user and check entered number last
digit is 4 or not.