java | operator is for what?

后端 未结 8 1196
故里飘歌
故里飘歌 2021-01-25 11:14

What is the output of this java code and why ?

 int a = 5 | 3 ;
 System.out.println(a);
8条回答
  •  伪装坚强ぢ
    2021-01-25 11:45

    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);
    

提交回复
热议问题