You can check if a number is divisible by 3 and 5 in Java using the modulo operator (%
). If the remainder of dividing the number by 3 and the remainder of dividing the number by 5 are both 0, then the number is divisible by both 3 and 5.
Here's a Java code snippet demonstrating this:
public class DivisibilityCheck {
public static void main(String[] args) {
int number = 15; // Example number to check
if (isDivisibleBy3And5(number)) {
System.out.println(number + " is divisible by both 3 and 5.");
} else {
System.out.println(number + " is not divisible by both 3 and 5.");
}
int anotherNumber = 10;
if (isDivisibleBy3And5(anotherNumber)) {
System.out.println(anotherNumber + " is divisible by both 3 and 5.");
} else {
System.out.println(anotherNumber + " is not divisible by both 3 and 5.");
}
}
public static boolean isDivisibleBy3And5(int num) {
return (num % 3 == 0) && (num % 5 == 0);
}
}
Explanation:
isDivisibleBy3And5(int num)
Method: This method takes an integernum
as input.- Modulo Operator (
%
): The modulo operator (%
) returns the remainder of a division.num % 3
calculates the remainder whennum
is divided by 3.num % 5
calculates the remainder whennum
is divided by 5. - Condition Check:
(num % 3 == 0) && (num % 5 == 0)
checks if both remainders are equal to 0.num % 3 == 0
evaluates totrue
ifnum
is divisible by 3.num % 5 == 0
evaluates totrue
ifnum
is divisible by 5.- The
&&
(AND) operator ensures that both conditions must betrue
for the entire expression to betrue
.
- Return Value: The method returns
true
if the number is divisible by both 3 and 5; otherwise, it returnsfalse
.
Important Considerations:
- Data Types: This code works with integers. If you need to check divisibility for other number types (e.g.,
float
,double
), you should cast them to integers first, or handle potential precision issues that may arise with floating-point numbers. - Negative Numbers: The modulo operator works with negative numbers as well. For example,
-15 % 3
will result in0
, indicating that -15 is divisible by 3.