Symbols for logic in Java

Absolutely simple Java question which is difficult for me to find on Google. Which means the following:

(7 & 8) == 0? 

This is equivalent to writing:

 7 == 0 || 8 == 0? 

I wrote a short article that tests this, and it seems to be so. I just wanted to make sure nothing was missing.

+7
source share
5 answers

Nope. & bitwise and . It sets the bit if the corresponding bits are set on both inputs. Since in binary format 7 is 111 and 8 is 1000 , they have no bits, so the result is 0 .

Actually there is no strict syntax for the thing you are proposing, not one line. There are several workarounds: checking membership in Set or BitSet , using the switch - but nothing more efficient and short as soon as 7 == 0 || 8 == 0 7 == 0 || 8 == 0 .

+17
source

& bitwise AND. Given two bits for inputs, the following gives a bit output bitwise AND:

 0 & 0 = 0 0 & 1 = 0 1 & 0 = 0 1 & 1 = 1 

In this case

 7 in binary is 00000111 8 in binary is 00001000 -------- 00000000, which is 0 in decimal. 

Say you had 26 instead of 8.

  7 in binary is 00000111 26 in binary is 00011010 -------- 00000010, which is 2 in decimal. 

Bitwise operations are used to extract and process fields packed into numbers.

For example, suppose you had 3 fields packed into a single number, two of 4 bits (0..15), one and 3 bits (0..7).

 // n = aaaabbbbccc // Unpack the fields: a = (n >> 7) & 0xF; b = (n >> 3) & 0xF; c = (n >> 0) & 0x7; // Pack the fields: n = (a << 7) | (b << 3) | (c << 0); 
+10
source

& is the bitwise AND operator. This means that you are AND AND bits representing 8 and 7:

7 β†’ 0111

8 β†’ 1000

This obviously leads to 0.

This wikipedia article explains your example well and explains other bitwise operators.

+4
source

This is a bit comparison, working fine, because you are comparing with 7 and 8, it is not guaranteed in other cases. If both bits in integers match, you will get results as "1" and not "0".

+3
source

& is a small comparison, as already mentioned, but can also serve as the β€œand” short circuit. For example:

 if((x == 3) && (y = 3/0)){ 

will cause an error all the time. Nevertheless,

 if((x == 3) & (y = 3/0)){ 

gives an error only if x is equal to 3. If x is not equal to 3, java will not evaluate the rest of the expressions, because False and everyone will be False.

+3
source

All Articles