java | operator is for what?

后端 未结 8 1189
故里飘歌
故里飘歌 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:36

    Its' binary "or" operator in a bunch of other languages, I assume it's the same in java

    0 讨论(0)
  • 2021-01-25 11:36

    See Bitwise and Bit Shift Operators.

    0 讨论(0)
  • 2021-01-25 11:38

    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.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-01-25 11:45

    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.

    0 讨论(0)
  • 2021-01-25 11:49

    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
    
    0 讨论(0)
提交回复
热议问题