In java programming, it is easy to find whether the number is odd or even using a single function. The logic behind the function is to identify whether the input number is divisible by two without any remainder. If so, that integer is considered to be an even number.

Odd or Even Checker using Java

In this article, we take the number from the user through the Scanner class which is provided by the java.util package. First, we’ll create a new class “EvenOddChecker” and insert the main method to it. The code is written inside the main method to avoid complexity in creating new methods.

public class EvenOddChecker {
      public static void main(String args[]) {
	   int number;
	   System.out.print("Enter an integer: ");

	   //get input number from the user
	   Scanner input = new Scanner(System.in);

	   //convert the number from string format to integer
	   number = input.nextInt();
	     
	   //check whether the number is even or not
	   if (number % 2 == 0) {
	         System.out.println("The number "+ number + " is EVEN");
	   }
	   else {
	         System.out.println("The number "+ number + " is ODD");
	   }
	      
         //close scanner input
	   input.close();
	}
}

From the Scanner class, we take the input from the user, and it is important to remember that the Scanner class always takes the input as a string. So to do any calculations, it needs to convert it to integer format. For that, nextInt() function is used. After the conversion, the value is assigned to the number variable and used it inside the condition to check whether the number is divisible by two without any remainder.

If the number is divisible by two without any remainder, it will execute the code inside the 1st condition, and otherwise, it performs the else block. An important point to notice is that; we need to close the scanner object that we created to avoid resource leak after the function execution.

What is Resource Leak?

It is a scenario where resources are not released after the utilization. This action will lead to poor performance of the application. As garbage collection in java manages only memory related resources, it is important to close these system resources manually.

Program Output

Odd number

Enter An Integer: 245
The number 245 is ODD

Even Number

Enter An Integer: 20
The number 20 is EVEN

Related Articles

Last modified: March 15, 2019

Comments

Write a Reply or Comment

Your email address will not be published.