Check whether number is even or odd

Java

Java Problem Overview


How would I determine whether a given number is even or odd? I've been wanting to figure this out for a long time now and haven't gotten anywhere.

Java Solutions


Solution 1 - Java

You can use the modulus operator, but that can be slow. If it's an integer, you can do:

if ( (x & 1) == 0 ) { even... } else { odd... }

This is because the low bit will always be set on an odd number.

Solution 2 - Java

if ((x % 2) == 0) {
   // even
} else {
   // odd
}

Solution 3 - Java

If the remainder when you divide by 2 is 0, it's even. % is the operator to get a remainder.

Solution 4 - Java

The remainder operator, %, will give you the remainder after dividing by a number.

So n % 2 == 0 will be true if n is even and false if n is odd.

Solution 5 - Java

Every even number is divisible by two, regardless of if it's a decimal (but the decimal, if present, must also be even). So you can use the % (modulo) operator, which divides the number on the left by the number on the right and returns the remainder...

boolean isEven(double num) { return ((num % 2) == 0); }

Solution 6 - Java

I would recommend

> Java Puzzlers: Traps, Pitfalls, and Corner Cases Book by Joshua Bloch > and Neal Gafter

There is a briefly explanation how to check if number is odd. First try is something similar what @AseemYadav tried:

public static boolean isOdd(int i) {
     return i % 2 == 1;
}

but as was mentioned in book:

> when the remainder operation returns a nonzero result, it has the same > sign as its left operand

so generally when we have negative odd number then instead of 1 we'll get -1 as result of i%2. So we can use @Camilo solution or just do:

public static boolean isOdd(int i) {
     return i % 2 != 0;
}

but generally the fastest solution is using AND operator like @lucasmo write above:

public static boolean isOdd(int i) {
     return (i & 1) != 0;
}

@Edit It also worth to point Math.floorMod(int x, int y); which deals good with negative the dividend but also can return -1 if the divisor is negative

Solution 7 - Java

Least significant bit (rightmost) can be used to check if the number is even or odd. For all Odd numbers, rightmost bit is always 1 in binary representation.

public static boolean checkOdd(long number){
   return ((number & 0x1) == 1);
}

Solution 8 - Java

Works for positive or negative numbers

int start = -3;
int end = 6;

for (int val = start; val < end; val++)
{
    // Condition to Check Even, Not condition (!) will give Odd number
    if (val % 2 == 0) 
    {
        System.out.println("Even" + val);
    }
    else
    {
        System.out.println("Odd" + val);
    }
}

Solution 9 - Java

This following program can handle large numbers ( number of digits greater than 20 )

package com.isEven.java;
import java.util.Scanner;

public class isEvenValuate{

public static void main(String[] args) {			
		
		Scanner in = new Scanner(System.in);
		String digit = in.next();
		
		int y = Character.getNumericValue(digit.charAt(digit.length()-1));
		
		boolean isEven = (y&1)==0;
		
		if(isEven)
			System.out.println("Even");
		else
			System.out.println("Odd");

    }
}

Here is the output ::

  122873215981652362153862153872138721637272
  Even

Solution 10 - Java

If the modulus of the given number is equal to zero, the number is even else odd number. Below is the method that does that:

public void evenOrOddNumber(int number) {
  if (number % 2 == 0) {
    System.out.println("Number is Even");
   } else {
    System.out.println("Number is odd");
  }
 }

Solution 11 - Java

    /**
     * Check if a number is even or not using modulus operator.
     *
     * @param number the number to be checked.
     * @return {@code true} if the given number is even, otherwise {@code false}.
     */
    public static boolean isEven(int number) {
        return number % 2 == 0;
    }

    /**
     * Check if a number is even or not using & operator.
     *
     * @param number the number to be checked.
     * @return {@code true} if the given number is even, otherwise {@code false}.
     */
    public static boolean isEvenFaster(int number) {
        return (number & 1) == 0;
    }

source

Solution 12 - Java

Another easy way to do it without using if/else condition (works for both positive and negative numbers):

int n = 8;
List<String> messages = Arrays.asList("even", "odd");

System.out.println(messages.get(Math.abs(n%2)));

For an Odd no., the expression will return '1' as remainder, giving

> messages.get(1) = 'odd' and hence printing 'odd'

else, 'even' is printed when the expression comes up with result '0'

Solution 13 - Java

You can use the modulus operator, but that can be slow. A more efficient way would be to check the lowest bit because that determines whether a number is even or odd. The code would look something like this:

public static void main(String[] args) {        
    System.out.println("Enter a number to check if it is even or odd");        
    System.out.println("Your number is " + (((new Scanner(System.in).nextInt() & 1) == 0) ? "even" : "odd"));        
}

Solution 14 - Java

You can do like this:

boolean is_odd(int n) {
    return n % 2 == 1 || n % 2 == -1;
}

This is because Java has in its modulo operation the sign of the dividend, the left side: n. So for negatives and positives dividends, the modulo has the sign of them.

Of course, the bitwise operation is faster and optimized, simply document the line of code with two or three short words, which does it for readability.

Solution 15 - Java

package isevenodd;
import java.util.Scanner;
public class IsEvenOdd {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter number: ");
        int y = scan.nextInt();       
        boolean isEven = (y % 2 == 0) ? true : false;
        String x = (isEven) ? "even" : "odd";  
        System.out.println("Your number is " + x);
    }
}

Solution 16 - Java

Here is full example:-

import java.text.ParseException;

public class TestOddEvenExample {
	public static void main(String args[]) throws ParseException {

		int x = 24;
		oddEvenChecker(x);

		int xx = 3;
		oddEvenChecker(xx);
	}

	static void oddEvenChecker(int x) {
		if (x % 2 == 0)
			System.out.println("You entered an even number." + x);
		else
			System.out.println("You entered an odd number." + x);
	}
}

enter image description here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoshView Question on Stackoverflow
Solution 1 - JavalucasmoView Answer on Stackoverflow
Solution 2 - JavapoyView Answer on Stackoverflow
Solution 3 - JavaRyan StewartView Answer on Stackoverflow
Solution 4 - JavaPhilView Answer on Stackoverflow
Solution 5 - Javafireshadow52View Answer on Stackoverflow
Solution 6 - JavaMichu93View Answer on Stackoverflow
Solution 7 - Javauser10544847View Answer on Stackoverflow
Solution 8 - JavaKiran GView Answer on Stackoverflow
Solution 9 - JavaTitus Roby KView Answer on Stackoverflow
Solution 10 - Javacorneliouz BettView Answer on Stackoverflow
Solution 11 - JavaduyuanchaoView Answer on Stackoverflow
Solution 12 - JavaAseem YadavView Answer on Stackoverflow
Solution 13 - JavaSlap Chukandar SinghView Answer on Stackoverflow
Solution 14 - JavaCamiloView Answer on Stackoverflow
Solution 15 - JavaBobView Answer on Stackoverflow
Solution 16 - JavaVipul GulhaneView Answer on Stackoverflow