kml_ckr
kml_ckr

Reputation: 2251

java | operator is for what?

What is the output of this java code and why ?

 int a = 5 | 3 ;
 System.out.println(a);

Upvotes: 1

Views: 309

Answers (8)

Roman
Roman

Reputation: 66226

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

Upvotes: 3

Christian
Christian

Reputation: 4104

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

Upvotes: 5

Alexis Dufrenoy
Alexis Dufrenoy

Reputation: 11966

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.

Upvotes: 2

gdj
gdj

Reputation: 1295

it's bitwise or:

5 = 110
3 = 011
5 | 3 =
    111

Upvotes: 1

echo
echo

Reputation: 7875

That's the bitwise-or operator.

http://leepoint.net/notes-java/data/expressions/bitops.html

Upvotes: 0

helpermethod
helpermethod

Reputation: 62304

See Bitwise and Bit Shift Operators.

Upvotes: 0

Pete Kirkham
Pete Kirkham

Reputation: 49331

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.

Upvotes: 5

Andrey
Andrey

Reputation: 21295

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

Upvotes: 1

Related Questions