'Java equivalent of & (single ampersand) in if statement, like in C?

So after learning both C and Java, Java doesn't have the capability of Bitwise-Anding in an if-statement between two values.

int x = 1011;
int y = 0110;
//      0010
if (x % y) {
  printf("EXAMPLE")
}

I know I'm missing something. I think it's because I don't really know understand what's occurring inside the if condition, and what'll make it true or false. Is there a Java equivalent to doing this?



Solution 1:[1]

First, both numbers x and y are NOT binaries:

  • int x = 1011; // decimal 1011
  • int y = 0110; // octal, equivalent of 8 + 64 = 72

The binary values have to use 0b prefix:

int x = 0b1011; // decimal 11
int y = 0b0110; // decimal  6

Second, (x % y) is NOT bitwise ending, it's a remainder of division of x by y. Bitwise AND is &. This is true for both C and Java.

Third, if the result of bitwise AND should be true, just compare its result to be non-equal to zero, to make the code equivalent of C.

So, the resulting code should look like:

int x = 0b1011; // decimal 11
int y = 0b0110; // decimal  6

if ((x & y) != 0) {
  System.out.println("EXAMPLE");
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1