Test with Positive and Negative Numbers
In the previous step, we successfully checked if a positive integer is even or odd. Now, let's explore how the modulo operator works with negative numbers and zero. The concept of even and odd applies to all integers, including negative ones and zero.
An integer is even if it is divisible by 2, meaning the remainder is 0. This definition holds true for negative numbers as well. For example, -4 is even because -4 divided by 2 is -2 with a remainder of 0. -3 is odd because -3 divided by 2 is -1 with a remainder of -1 (or 1, depending on the definition of modulo for negative numbers, but the key is it's not 0). Zero is also considered an even number because 0 divided by 2 is 0 with a remainder of 0.
Let's modify our EvenCheck.java
program to test with different positive and negative numbers, as well as zero.
-
Open the EvenCheck.java
file in the WebIDE editor.
-
Modify the main
method to test several different numbers. You can change the value of the number
variable multiple times, or you can add more if-else
blocks to check different numbers sequentially. For simplicity, let's change the value of number
and re-run the program for each test case.
First, let's test with a positive odd number. Change the line int number = 10;
to:
int number = 7; // Test with a positive odd number
-
Save the file.
-
Compile the modified program in the Terminal:
javac EvenCheck.java
-
Run the program:
java EvenCheck
You should see the output:
7 is an odd number.
-
Now, let's test with a negative even number. Change the line int number = 7;
to:
int number = -4; // Test with a negative even number
-
Save the file.
-
Compile the program:
javac EvenCheck.java
-
Run the program:
java EvenCheck
You should see the output:
-4 is an even number.
-
Next, test with a negative odd number. Change the line int number = -4;
to:
int number = -3; // Test with a negative odd number
-
Save the file.
-
Compile the program:
javac EvenCheck.java
-
Run the program:
java EvenCheck
You should see the output:
-3 is an odd number.
-
Finally, test with zero. Change the line int number = -3;
to:
int number = 0; // Test with zero
-
Save the file.
-
Compile the program:
javac EvenCheck.java
-
Run the program:
java EvenCheck
You should see the output:
0 is an even number.
As you can see, the modulo operator correctly identifies even and odd numbers for positive, negative, and zero values. The logic number % 2 == 0
is a reliable way to check for evenness for any integer.