This java tutorial focuses on how to check if an integer is odd or even in java. As we are already aware from our elementary mathematics that an even integer is a number which can evenly be divided into 2 while the odd integer are those numbers which always gives a remainder of 1. We will provide two solution; one is to use the modulo or remainder operator, the other is to solve it using mathematical expressions.
Integer Odd or Even in java : Using the remainder operator
This sample source code takes an integer input from the console and evaluate it if it’s an odd or even integer. Moreover we have provided mechanism to check if the input number is valid or not.
package com.javatutorialhq.tutorial; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; // source code to determine if an integer is odd or even in java public class OddEven { public static void main(String[] args) { System.out.print("Enter a number: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { int input = Integer.parseInt(br.readLine()); //check if even int mod = input%2; if(mod==0){ System.out.println(input + " is an even integer"); } else{ System.out.println(input + " is an odd integer"); } } catch (NumberFormatException e) { System.out.println("Unknown input"); } catch (IOException e) { e.printStackTrace(); } } }
Sample Output :
Enter a number: 12 12 is an even integer
If we enter an invalid character the following is a sample output
Enter a number: 2jhdj Unknown input
Integer Odd or Even in java : Using mathematical expression
This method as i call it is a long one. However this sample code enhances our skills on using the basic mathematical operator of java. Code is using the property of primitive type integer, use of if else, and then the operators % and *.
package com.javatutorialhq.tutorial; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class OddEvenManual { // source code to determine if an integer is odd or even in java using mathematical expressions public static void main(String[] args) { System.out.print("Enter an Integer: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { int input = Integer.parseInt(br.readLine()); int result = input/2; if(result*2 == input){ System.out.println("Input "+input+" is an even number"); } else{ System.out.println("Input "+input+" is an odd number"); } } catch (NumberFormatException | IOException e) { System.out.println("Invalid Input"); } } }
Sample Output :
Enter an Integer: 101 Input 101 is an odd number