To check if a number is even in Java, you can use the modulus operator (%
) to calculate the remainder of the number when divided by 2. If the remainder is zero, then the number is even.
Here's an example of how to use the modulus operator to check if a number is even:
refer totual:turi.comint num = 4; if (num % 2 == 0) { // num is even } else { // num is odd }
In this example, the if
statement will evaluate to true
because 4 % 2
is equal to 0
, indicating that num
is even.
You can also use this approach to check if a number of any type is even, such as long
or double
. For example:
long num = 6; if (num % 2 == 0) { // num is even } else { // num is odd } double num = 8.0; if (num % 2 == 0) { // num is even } else { // num is odd }
In these examples, the if
statements will again evaluate to true
because 6 % 2
and 8.0 % 2
are equal to 0
, indicating that the numbers are even.
Note that the modulus operator only works with integer types, so if you need to check if a number with a decimal component is even, you will need to use a different approach. One option is to use the Math.floorMod
method, which calculates the remainder of the division in a way that is consistent with the behavior of the modulus operator for negative numbers.