What is the output of this java code and why ?
int a = 5 | 3 ;
System.out.println(a);
Its' binary "or" operator in a bunch of other languages, I assume it's the same in java
See Bitwise and Bit Shift Operators.
The | operator is a bit by bit OR function.
5 in binary is written 101, and 3 is written 11. So 3|5 will give you 111, which is 7.
It's called "bitwise OR".
5 | 3 in bits is equal to
0101
or
0011
----
0111
Before enums appered in java 5, it was a common pattern to make some constants equals to powers of 2 and use bitwise OR to express both properties. For example, let's assume that font can be BOLD, ITALIC and UNDERLINED. Then if you have constants:
public class FontStyle {
final int BOLD = 1;
final int ITALIC = 2;
final int UNDERLINED = 4;
private int fontStyle;
public void setFontStyle(int style) {
this.fontStyle = fontStyle;
}
public boolean hasStyle(int style) {
return fontStyle & style == style;
}
}
Then, if you want to create style BOLD and UNDERLINED - just do this:
FontStyle boldAndUnderlined = new FontStyle();
boldAndUnderlined.setFOntStyle(FontStyle.BOLD | FontStyle.UNDERLINED);
This is a bitwise operator, part of the nuts and bolts Java tutorial
The output is the result of 'or'ing the bits in the binary representation of the numbers.
This is a bitwise or.
I did not test it. But it must be 7.
101 -> 5
011 -> 3
----
111 -> 7
1|1 = 1
1|0 = 1
0|1 = 1
0|0 = 0