14

I feel stupid asking such a simple question, but is there an easy way to determine whether an Integer is even or odd?

Snailer
  • 3,671
  • 3
  • 33
  • 45

6 Answers6

40
if ((n % 2) == 0) {
    // number is even
}

else {
    // number is odd
}
Richard Fearn
  • 24,169
  • 6
  • 56
  • 55
23

It's not android specific, but a standard function would be:

boolean isOdd( int val ) { return (val & 0x01) != 0; }

Many compilers convert modulo (%) operations to their bitwise counterpart automatically, but this method is also compatible with older compilers.

Abandoned Cart
  • 3,966
  • 1
  • 31
  • 36
billjamesdev
  • 14,354
  • 6
  • 50
  • 74
11

You can use modular division (technically in Java it acts as a strict remainder operator; the link has more discussion):

if ( ( n % 2 ) == 0 ) {
    //Is even
} else {
    //Is odd
}
Community
  • 1
  • 1
eldarerathis
  • 34,279
  • 10
  • 88
  • 93
4

If you do a bitwise-and with 1, you can detect whether the least significant bit is 1. If it is, the number is odd, otherwise even.

In C-ish languages, bool odd = mynum & 1;

This is faster (performance-wise) than mod, if that's a concern.

mtrw
  • 32,117
  • 7
  • 59
  • 70
1

When somehow % as an operator doesn't exist, you can use the AND operator:

oddness = (n & 1) ? 'odd' : 'even'
littlegreen
  • 7,102
  • 9
  • 44
  • 49
1

Similar to others, but here's how I did it.

boolean isEven = i %2 ==0;
seekingStillness
  • 4,343
  • 4
  • 30
  • 62