-3

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?

  • 4
    `&` also works in Java: [JLS 15.22.1. Integer Bitwise Operators &, ^, and |](https://docs.oracle.com/javase/specs/jls/se17/html/jls-15.html#jls-15.22.1), but an `if` only *accepts* a boolean expression, not an `int` one - Note: for binary literals use `0b` like in `int x = 0b1011` - Note2: `%` is not bitwise AND but remainder – user16320675 Mar 11 '22 at 09:16
  • 3
    Tangentially, you know that `x`'s and `y`'s binary representations are not 1011 and 0110, respectively and that 0110 is actually an octal number, right? – Federico klez Culloca Mar 11 '22 at 09:17
  • 2
    Since java `if` needs a boolean, `if ((x & y) != 0) ...` – Shawn Mar 11 '22 at 09:27

1 Answers1

2

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");
}
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
  • Re “`0b` prefix, which is also true for C language”: The C standard does not define a binary notation. Some compilers provide it as an extension. – Eric Postpischil Mar 11 '22 at 12:26
  • Thanks @EricPostpischil, you seem to be right, this notation is available in [C++ 14](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3472.pdf) and [GCC 4.3](https://gcc.gnu.org/gcc-4.3/changes.html) as extension – Nowhere Man Mar 11 '22 at 12:38