To check if a number is even in Java, you can use the modulo operator (%
) to find the remainder when the number is divided by 2. If the remainder is 0, the number is even.
Here is an example of how to check if a number is even in Java:
refer to:lautturi.compublic boolean isEven(int number) { return number % 2 == 0; } // Example usage int x = 10; if (isEven(x)) { System.out.println(x + " is an even number"); } else { System.out.println(x + " is an odd number"); }
In this example, the isEven()
method takes an integer as input and returns a boolean value indicating whether the number is even or not. The if
statement then uses the boolean value returned by the isEven()
method to determine which block of code to execute.
You can also use the ternary operator (? :
) to check if a number is even in a single line of code:
int x = 10; String result = (x % 2 == 0) ? "even" : "odd"; System.out.println(x + " is an " + result + " number");
In this example, the ternary operator first checks if the remainder of x
divided by 2 is 0. If it is, the expression evaluates to "even", otherwise it evaluates to "odd". The resulting value is then printed to the console.