zaro

How to check if a number is divisible by 3 and 5 in Java?

Published in Java Programming 2 mins read

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:

  1. isDivisibleBy3And5(int num) Method: This method takes an integer num as input.
  2. Modulo Operator (%): The modulo operator (%) returns the remainder of a division. num % 3 calculates the remainder when num is divided by 3. num % 5 calculates the remainder when num is divided by 5.
  3. Condition Check: (num % 3 == 0) && (num % 5 == 0) checks if both remainders are equal to 0.
    • num % 3 == 0 evaluates to true if num is divisible by 3.
    • num % 5 == 0 evaluates to true if num is divisible by 5.
    • The && (AND) operator ensures that both conditions must be true for the entire expression to be true.
  4. Return Value: The method returns true if the number is divisible by both 3 and 5; otherwise, it returns false.

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 in 0, indicating that -15 is divisible by 3.