Introduction
In this lab, you will learn how to determine if a number is even or odd in Java. We will explore the use of the modulo operator (%) to check for a remainder when a number is divided by 2, which is the fundamental principle for identifying even numbers.
You will implement a simple Java program to perform this check, test it with both positive and negative integer inputs, and consider how to handle non-integer inputs to make your solution more robust.
Use Modulo Operator for Even Check
In this step, we will learn how to determine if a number is even or odd in Java using the modulo operator. The modulo operator (%) gives you the remainder of a division. For example, 10 % 3 is 1 because 10 divided by 3 is 3 with a remainder of 1.
An even number is any integer that can be divided by 2 with no remainder. This means that if you divide an even number by 2, the remainder is always 0. We can use the modulo operator to check this condition.
Let's create a simple Java program to check if a number is even.
Open the
EvenCheck.javafile in the WebIDE editor. If the file doesn't exist, create it in the~/projectdirectory. You can do this by right-clicking in the File Explorer on the left, selecting "New File", and typingEvenCheck.java.Add the following code to the
EvenCheck.javafile:public class EvenCheck { public static void main(String[] args) { int number = 10; // We'll check if this number is even // Use the modulo operator to check for a remainder when divided by 2 if (number % 2 == 0) { System.out.println(number + " is an even number."); } else { System.out.println(number + " is an odd number."); } } }Let's look at the new parts:
int number = 10;: This declares an integer variable namednumberand assigns it the value 10. We can change this value to test different numbers.if (number % 2 == 0): This is anifstatement. It checks if the condition inside the parentheses is true. The conditionnumber % 2 == 0checks if the remainder ofnumberdivided by 2 is equal to 0.System.out.println(number + " is an even number.");: This line is executed if the condition in theifstatement is true (the number is even).else: This keyword introduces the block of code to be executed if the condition in theifstatement is false (the number is odd).System.out.println(number + " is an odd number.");: This line is executed if the number is odd.
Save the
EvenCheck.javafile (Ctrl+S or Cmd+S).Now, compile the program. Open the Terminal at the bottom of the WebIDE and make sure you are in the
~/projectdirectory. Then, run the following command:javac EvenCheck.javaIf there are no errors, a
EvenCheck.classfile will be created.Finally, run the compiled program:
java EvenCheckYou should see the output indicating whether the number 10 is even or odd.
10 is an even number.
Now, try changing the value of the number variable in the EvenCheck.java file to a different integer (e.g., 7, -5, 0) and repeat steps 3, 4, and 5 to see how the output changes.
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.javafile in the WebIDE editor.Modify the
mainmethod to test several different numbers. You can change the value of thenumbervariable multiple times, or you can add moreif-elseblocks to check different numbers sequentially. For simplicity, let's change the value ofnumberand 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 numberSave the file.
Compile the modified program in the Terminal:
javac EvenCheck.javaRun the program:
java EvenCheckYou 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 numberSave the file.
Compile the program:
javac EvenCheck.javaRun the program:
java EvenCheckYou 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 numberSave the file.
Compile the program:
javac EvenCheck.javaRun the program:
java EvenCheckYou 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 zeroSave the file.
Compile the program:
javac EvenCheck.javaRun the program:
java EvenCheckYou 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.
Handle Non-Integer Inputs
In the previous steps, we've successfully used the modulo operator to check if integer numbers are even or odd. However, what happens if the user tries to input something that is not an integer, like a decimal number or text? Our current program is designed to work with integers (int), and providing non-integer input will cause an error.
In this step, we will modify our program to take input from the user and handle cases where the input is not a valid integer. We will use the Scanner class, which we briefly saw in the "Your First Java Lab", to read user input.
Open the
EvenCheck.javafile in the WebIDE editor.Replace the entire content of the file with the following code:
import java.util.Scanner; import java.util.InputMismatchException; public class EvenCheck { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); try { int number = scanner.nextInt(); // Read integer input from the user // Use the modulo operator to check for a remainder when divided by 2 if (number % 2 == 0) { System.out.println(number + " is an even number."); } else { System.out.println(number + " is an odd number."); } } catch (InputMismatchException e) { System.out.println("Invalid input. Please enter an integer."); } finally { scanner.close(); // Close the scanner } } }Let's look at the changes:
import java.util.Scanner;: Imports theScannerclass to read input.import java.util.InputMismatchException;: Imports the exception class that is thrown when the input does not match the expected type.Scanner scanner = new Scanner(System.in);: Creates aScannerobject to read input from the console.System.out.print("Enter an integer: ");: Prompts the user to enter a number.try { ... } catch (InputMismatchException e) { ... }: This is atry-catchblock, which is used for error handling. The code inside thetryblock is executed. If anInputMismatchExceptionoccurs (meaning the input is not an integer), the code inside thecatchblock is executed.int number = scanner.nextInt();: This line attempts to read an integer from the user input. If the user enters something that cannot be interpreted as an integer, anInputMismatchExceptionis thrown.System.out.println("Invalid input. Please enter an integer.");: This message is printed if anInputMismatchExceptionis caught.finally { scanner.close(); }: The code inside thefinallyblock is always executed, regardless of whether an exception occurred or not. It's used here to close theScannerresource.
Save the file.
Compile the modified program in the Terminal:
javac EvenCheck.javaRun the program:
java EvenCheckWhen prompted, enter an integer (e.g.,
15) and press Enter. The program should correctly identify if it's even or odd.Enter an integer: 15 15 is an odd number.Run the program again:
java EvenCheckThis time, when prompted, enter a non-integer value (e.g.,
helloor3.14) and press Enter. The program should now handle the invalid input gracefully.Enter an integer: hello Invalid input. Please enter an integer.
By adding the try-catch block, our program is now more robust and can handle cases where the user provides input that is not in the expected format. This is an important aspect of writing user-friendly programs.
Summary
In this lab, we learned how to check if a number is even in Java using the modulo operator (%). We discovered that an even number has a remainder of 0 when divided by 2. We implemented a simple Java program using an if-else statement to perform this check and print whether a given integer is even or odd.
We further explored testing the even check with both positive and negative integer inputs to ensure the modulo operator behaves as expected for different signs. Finally, we considered how to handle non-integer inputs, understanding that the modulo operator is typically used with integer types and discussing potential approaches for validating input types or handling exceptions in a more robust application.



