Check whether number is even or odd
To check whether a number is even or odd in Java, you can use the modulus operator (%) to determine the remainder of the number when it is divided by 2.
If the remainder is 0, the number is even; otherwise, it is odd.
Here's an example of how you can use the modulus operator to check whether a number is even or odd:
public class Main {
public static void main(String[] args) {
int number = 5;
if (number % 2 == 0) {
System.out.println(number + " is even");
} else {
System.out.println(number + " is odd");
}
}
}
This code defines an int
variable number
and checks whether it is even or odd using the modulus operator. If the remainder of number
divided by 2 is 0, the code prints "5 is even" to the console; otherwise, it prints "5 is odd".
I hope this helps! Let me know if you have any questions.