3

The code is to check whether a number is even or odd using the last bit is 1 or 0. if last bit is 1 it will go in if and print odd

import java.util.Scanner;

public class Even_or_odd {
    public void Check_even_or_odd(int a) {
        if(a&1)//error:Type mismatch: cannot convert from int to boolean
            System.out.println("odd");
        else
            System.out.println("even");
   }
   public static void main(String[] args) {
        System.out.println("enter a number to check even or odd");
        Scanner scan=new Scanner(System.in);
        int a=scan.nextInt();
        scan.close();
        Even_or_odd e=new Even_or_odd();
        e.Check_even_or_odd(a);
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Eran can you elloborate? – Rushabh Oswal Dec 31 '16 at 13:39
  • after adding a&1==1 . I got the error Multiple markers at this line - Comparing identical expressions - The operator & is undefined for the argument type(s) int, boolean – Rushabh Oswal Dec 31 '16 at 13:42
  • Basically, Java doesn't treat numbers as booleans, unlike c and some other languages which do. 0 or any number at all, is neither true nor false. You are doing binary & operation on two integers which ultimately result in an integer. Not boolean. – Rohit Dodle Dec 31 '16 at 13:42
  • Change it to (a&1)==1. Must just be some confusion with precedences. – Rohit Dodle Dec 31 '16 at 13:43

2 Answers2

5

Your code tests a for being odd/even by masking its binary representation with 1, which has all bits set to zero except least significant one, which is set to 1.

Odd numbers will produce 1 when masked with 1; even numbers will produce zero. However, you cannot write if (1) or if (0), because there is no implicit conversion from int to boolean in Java. You need to write

if ((a&1) != 0)

to fix this problem.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

Instead of binary operations, which is what I guess you are trying to do, check the input value using modulo:

if (a % 2 == 0) {
  System.out.println("even");
} else {
  System.out.println("odd");
}

In the condition block of the if statement you have to have a boolean value or an expression that evaluates to a boolean. a&1 evaluates to an integer.

Also see Check whether number is even or odd

Community
  • 1
  • 1
hotzst
  • 7,238
  • 9
  • 41
  • 64
  • I know the program using % opertaor,but i just want to highlight the same program using bitwise operator in java as it was bombarding errors. – Rushabh Oswal Dec 31 '16 at 14:04