Firstly I learnt that &, |, ^ are the bitwise operators, and now somebody mentioned them as logical operators with &&, ||, I am completely confused – the same operator has two names? There are already logical operators &&, ||, then why use &, |, ^?
Firstly I learnt that & , | , ^ are the bitwise operators, and
Share
The Java operators
&,|and^are EITHER bitwise operators OR logical operators … depending on the types of the operands. If the operands are integers, the operators are bitwise. If they are booleans, then the operators are logical.And this is not just me saying this. The JLS describes these operators this way too; see JLS 15.22.
(This is just like
+meaning EITHER addition OR string concatenation … depending on the types of the operands. Or just like a “rose” meaning either a flower or a shower attachment. Or “cat” meaning either a furry animal or a UNIX command. Words mean different things in different contexts. And this is true for the symbols used in programming languages too.)In the case of the first two, it is because the operators have different semantics with regards to when / whether the operands get evaluated. The two different semantics are needed in different situations; e.g.
versus
The
^operator has no short-circuit equivalent because it simply doesn’t make sense to have one.