Check Number Divisible by 3 or 5 in Java
beginner· Control Flow · Conditional Statements
Problem
A number qualifies here if it's a multiple of 3, a multiple of 5, or both — only one of the two conditions needs to hold.
Given a number, determine whether it is divisible by 3 or by 5.
Input
18
Output
18 is divisible by 3 or 5: true
Java Program
Java
public class DivisibleBy3Or5 {
public static void main(String[] args) {
int n = 18;
boolean isDivisible = (n % 3 == 0) || (n % 5 == 0);
System.out.println(n + " is divisible by 3 or 5: " + isDivisible);
}
}Output
18 is divisible by 3 or 5: true
Core Logic
Checking each divisibility condition with the modulo operator, and requiring only one to hold, confirms the number is a multiple of 3, 5, or both.
How It Works
- 1
n % 3 == 0checks divisibility by 3. - 2
n % 5 == 0checks divisibility by 5, combined with||. - 3Either condition being true is enough for the overall result to be true.
For
n = 18, 18 % 3 is 0, so the condition is already true regardless of what 18 % 5 evaluates to.💡
Key Point: Unlike a combined AND check, || only needs one side to match — a number divisible by 3 alone, 5 alone, or both, all satisfy this check.
Key Concepts
modulo operatorlogical OR