What is the output of this java code and why ?
int a = 5 | 3 ;
System.out.println(a);
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);