Odd or Even Example in Java
Introduction
Odd Or Even is a classic Java console program that demonstrates the concept with complete source code and sample output. Calculation programs apply formulas to solve geometry, statistics and numeric problems.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
A formal definition of an even number is that it is an integer of the form n = 2k, where k is an integer;[3] it can then be shown that an odd number is an integer of the form n = 2k + 1.
Odd Or Even Example Program
import java.util.Scanner;
class OddOrEven{
public static void main(String args[]){
int num;
System.out.println("Enter a number: ");
Scanner in = new Scanner(System.in);
num = in.nextInt();
if ( num % 2 == 0 ){
System.out.println("The number you entered is an even number");
}
else{
System.out.println("The number you entered is an odd number");
}
}
}Sample Output
Enter a number:
56
The number you entered is an even numberWhen to use
Use these formulas in homework tools, engineering calculators or anywhere repeated numeric computation is needed.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
import java.util.Scanner;imports a class used later in the program. -
A
println/printcall writes text to the console — part of the sample output below. -
A
Scannerreads typed input from the keyboard (System.in). -
num = in.nextInt();updates a variable used in the calculation or output. -
The
ifstatement runs the nested code only when the condition is true. -
A
println/printcall writes text to the console — part of the sample output below. -
A
println/printcall writes text to the console — part of the sample output below.