Java ProgramsControl FlowFind Last Digit

Find Last Digit in Java

beginner·  Control Flow  ·  Loops

Problem

The last digit of any number is exactly the remainder left over when it's divided by 10.

Given a number, find its last digit.

Input
45678
Output
Last digit: 8

Java Program

Java
public class LastDigitFinder { public static void main(String[] args) { int n = 45678; int lastDigit = n % 10; // remainder after dividing by 10 System.out.println("Last digit: " + lastDigit); } }

Output

Last digit: 8

Core Logic

Dividing by 10 and keeping only the remainder isolates the last digit directly, since every digit before it contributes a multiple of 10 and vanishes under modulo.

How It Works
  1. 1n % 10 divides n by 10 and keeps only what's left over.
  2. 2Every digit except the last one contributes a multiple of 10, so it's discarded by the modulo operation.
  3. 3The result is stored in lastDigit and printed with a label.
For n = 45678, 45678 % 10 evaluates to 8, the last digit.
💡

Key Point: This works because any number can be written as 10 × (everything but the last digit) + last digit — the modulo strips away the first part entirely.

Key Concepts

modulo operatorint

Related Programs