Home » Java » doesn't java follow implicit type conversion?-Exceptionshub

doesn't java follow implicit type conversion?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I was solving the following problem on Hacker rank. The program is supposed to print “Weird” onto the screen when N is odd. I checked the condition for N to be odd with the bitwise and(&) operator. But, I was getting this message from the compiler. I recently switched to java from c++. This operation works in C++. I wonder why it’s not supported by java.
enter image description here

public class Solution {
private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
    int N = scanner.nextInt();
    if(N&1){
        System.out.println("Weird");
    }
    else if(N>=2&&N<=5)
    {
       System.out.println("Not Weird"); 
    }
    else if(N>=6&&N<=20){
        System.out.println("Weird");
    }
    else{
        System.out.println("Not Weird");
    }

    scanner.close();
}

}

How to&Answers:

Java is not C, you can’t coerce an int to a boolean. This

if(N&1){

should be

if ((N & 1) == 1) {