×

Even Odd Program in Java

Even Odd Program in Java

The number that are completely divisible by 2 are even and the number that leaves remainder are odd numbers. For example, the numbers 2, 0, 4, 8, -2, -16 are even numbers and the numbers -1, 1, 3, 5, 7, 9, 11 are odd. In this section, we have created Java programs with different approaches to check the number is even or odd.

The Modulus Operator Approach

Filename: ForLoopExample.java

public class ForLoopExample
{             
// Method for finding whether the input number is the even or odd
static boolean isEven(int number)
{
               if(number % 2 == 0)
                               return true;
               return false;        
}
public static void main(String argvs[])
{
               // an array of numbers
               int arr[] = {23, 0, -111, 444, -66, -100, -101, -79, 122, 198, 3003};
               // Iterating over every element of the input array
               for(int i = 0; i < arr.length; i++)
               {
                               // Invoking isEven() method and displaying results accordingly
                              if(isEven(arr[i]))
                              {
                                              System.out.println(arr[i] + ", is an even number.");
                              }
                              else
                              {
                                              System.out.println(arr[i] + ", is an odd number.");
                              }
               }
}
}

Output:

23 is an odd number.
0 is an even number.
-111 is an odd number.
444 is an even number.
-66 is an even number.
-100 is an even number.
-101 is an odd number.
-79 is an odd number.
122 is an even number.
198 is an even number.
3003 is an odd number.

Explanation: We are iterating over every element of the input array and invoking the method isEven(). The method uses the modulus operator (%) that finds the remainder when we divide the number by 2. If we get the remainder 0 the given number is even, else the number is odd.

Iterative Approach

Filename: EvenOddExample1.java

public class EvenOddExample1
{             
public static void main(String argvs[])
{
               // Input array
               int arr[] = {23, 0, -111, 444, -66, -100, -101, -79, 122, 198, 3003};
               // Iteratiing over every element of the input array
               for(int i = 0; i < arr.length; i++)
               {
                               int temp = arr[i]; // creating a copy
                               if(temp >= 0) // For the non-negative numbers
                               {
                                              while(temp > 0)
                                              {
                                                             temp = temp - 2;
                                              }
                                              // Displaying results
                                              if(temp == 0)
                                                             System.out.println(arr[i] + ", the even number.");
                                              else
                                                             System.out.println(arr[i] + ", the odd number.");
                               }
                               else // For the negative numbers
                               {
                                              while(temp < 0)
                                              {
                                                             temp = temp + 2;
                                              }
                                              // Displaying results
                                              if(temp == 0)
                                                             System.out.println(arr[i] + ", is an even number.");
                                              else
                                                             System.out.println(arr[i] + ", is an odd number.");
                               }
               }
}
}

Output:

23 is an odd number.
0 is an even number.
-111 is an odd number.
444 is an even number.
-66 is an even number.
-100 is an even number.
-101 is an odd number.
-79 is an odd number.
122 is an even number.
198 is an even number.
3003 is an odd number.

Explanation: We know that 0 is a multiple of 2. Therefore, 0 is an even number. Also, the sum of two even numbers is always an even number and the sum of one odd, and one even number is an odd number (For example, 2 + 6 = 8, 7 + 2 = 9). These concepts serve as the basis for distinguishing between even and odd numbers. We try to reduce every element of the input array to 0 by incrementing or decrementing by 2. If we become successful, the number is an even number, otherwise an odd number.

Recursive Approach

Filename: EvenOddExample2.java

public class EvenOddExample2
{
// Method for handling non-negative numbers         
public static void recForNonNeg(int noCpy, int no)
{
               if(noCpy == 0)
               {
                               System.out.println(no + " is the even number."); 
                               return;
               }
               else if (noCpy < 0)
               {
                               System.out.println(no + " is the odd number.");   
                               return;
               }
               // Recursively reducing the number to 0.
               recForNonNeg(noCpy - 2, no);
}
// Method for handling negative numbers
public static void recForNeg(int noCpy, int no)
{
               if(noCpy == 0)
               {
                               System.out.println(no + " is an even number."); 
                               return;
               }
               else if (noCpy > 0)
               {
                               System.out.println(no + " is an odd number.");   
                               return;
               }
               // Recursively reducing the number to 0.
               recForNeg(noCpy + 2, no);
}
public static void main(String argvs[])
{
               // Input array
               int arr[] = {23, 0, -111, 444, -66, -100, -101, -79, 122, 198, 3003};
               // Iteratiing over every element of the input array
               for(int i = 0; i < arr.length; i++)
               {
                               if(arr[i] >= 0)
                               {
                                              // Invoking the method to handle the non-negative numbers
                                              recForNonNeg(arr[i], arr[i]);
                               }
                               else
                               {
                                              // Invoking the method to handle the negative numbers
                                              recForNeg(arr[i], arr[i]);
                               }
               }
}
}

Output:

23 is an odd number.
0 is an even number.
-111 is an odd number.
444 is an even number.
-66 is an even number.
-100 is an even number.
-101 is an odd number.
-79 is an odd number.
122 is an even number.
198 is an even number.
3003 is an odd number.

Explanation: The concept used in the recursive approach is similar to what we have in the iterative approach. The only difference is instead of using a loop to reduce the input numbers to 0; we are reducing the number using the recursion.

Bitwise AND operator Approach

Filename: EvenOddExample3.java

public class EvenOddExample3
{
public static void main(String argvs[])
{
               // Input array
               int arr[] = {23, 0, -111, 444, -66, -100, -101, -79, 122, 198, 3003};
               // Iterating over every element of the input array
               for(int i = 0; i < arr.length; i++)
               {
   // Checking the left most bit of every number and displaying results accordingly
                               if((arr[i] & 1) == 0)
                               {
                                              System.out.println(arr[i] + " is an even number.");
                               }
                               else
                               {
                                              System.out.println(arr[i] + " is an odd number.");
                               }
               }
}
}

Output:

23 is an odd number.
0 is an even number.
-111 is an odd number.
444 is an even number.
-66 is an even number.
-100 is an even number.
-101 is an odd number.
-79 is an odd number.
122 is an even number.
198 is an even number.
3003 is an odd number.

Explanation: Apart from getting completely divisible by 2, the even numbers have one more unique feature. To learn about it, observe the following table:

NumberEquivalent binary representation
10001
20010
30011
40100
50101
60110
70111
81000
91001
101010
111011
121100

Notice the rightmost bit of every number. We learn by the observation that for every odd number, the rightmost bit (or LSB) is 1, and for even numbers, it is 0. With the help of this concept, we are able to distinguish between an even and an odd number.

Comparison of the above-written Approaches

Usually, we should use the bitwise AND (&) or the modulus operator (%) approach to check the number is even or odd. Because these two approaches do not use the loop or recursion. However, during interview time, an interviewer may trick and can ask to write the logic to check the number is even or odd without using the modulus operator and loop. Therefore, we must know the iterative as well as the recursive approach, but, when given the liberty, the first and fourth approach should always take precedence over the second and third one.


Related Topics

Java Create File

A File is a hypothetical way, which has no genuine presence. It is very much like while "using" that File that the major real activity of putting away something in...

5 minutes read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Construct the Largest Number from the Given Array in Java

In this section, we will create a Java programme that will enable you to locate the greatest integer in an array. The programme will begin comparing the array's numbers with...

3 minutes read.

Automorphic Number Program in Java

We will learn about automorphic numbers through examples in this article, and we'll also make Java programmes that can determine whether a specific number was automorphic or not. What is an...

3 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Java URL Class with Example

Java URL Uniform Resource Locator To find any resource on the internet, you need to have an address of it. The URL and IP addresses are the pointers used for this purpose....

12 minutes read.

Lombok Java

What is Lombok java? A well-liked and widely-used Java framework that is used to reduce or eliminate boilerplate code is called Project Lombok. Both time and effort are saved. We may...

7 minutes read.

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

4 minutes read.

Java String contains() method

contains() method returns true only if it contains the given sequence of characters otherwise it returns false. syntax: public boolean contains(CharSequence sequence) parameters: sequence : It is the sequence to be searched. Returns: It returns true...

1 minute read.

Ad Hoc Problem on Arrays in Java

Ad hoc problems are issues that arise unexpectedly and require immediate attention. These problems can range from small and straightforward issues to more complex and time-consuming problems. Examples of ad...

3 minutes read.

Java Virtual Machine (JVM)

JVM is a virtual runtime environment to execute Java byte codes. The JVM doesn’t understand the keywords we used to write code. That is why it is converted into bytecode. It controls the...

3 minutes read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

Flag Pattern in Java

The flag pattern in Java can be printed, which will be covered in this part. Given how difficult they are to code, flag patterns are rarely asked by interviewers. We separate...

2 minutes read.

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

1 minute read.

Java Socket Programming

Java Socket Programming Socket programming is used for the communication between the applications, i.e., client and server running on different JRE may be connection-oriented or connectionless. The client program can be designed using the...

8 minutes read.

Int vs Integer in Java

In Java, numerical data can be stored using int or Integer. int and Integer both have different definitions but similar usage in Java. What is int in Java? int is a primitive...

4 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.