-2

In Java, the & operator evaluates both the operands and so does the || operator.

I do understand the difference between && (AND) and || (OR) operators. I want to gain some understanding on bitwise & operators and the logical || operator.

What is the difference between them? Which one to use when?

Nital
  • 5,784
  • 26
  • 103
  • 195
  • Do you mean `&` or `&&`? – Purag Sep 10 '15 at 03:30
  • 7
    And are you trying to tell us that you don't know the difference between Boolean AND and Boolean OR? – Hot Licks Sep 10 '15 at 03:30
  • A && B ---> Both A and B have to be True. A || B --> A or B needs to be True – hello_harry Sep 10 '15 at 03:31
  • @HotLicks Actually, unless the OP wrote it wrong, `&` is a bitwise operator, as pointed out in the possible duplicate given by @Purag. – tomasyany Sep 10 '15 at 03:37
  • 1
    @tomasyany - Correct. There were so many things wrong with Opie's question that it would take a small book to respond completely. – Hot Licks Sep 10 '15 at 03:45
  • The question is still unclear; you're asking about the differences between two *completely different* operators. (They're not even in the same category of operators). What differences are you curious about? – Purag Sep 10 '15 at 03:48
  • @Purag - I have never used bitwise operators and was wondering what are possible scenarios where they could be used. After reading some online material it looks like bitwise operators operate only on int and long datatypes. It helps to know how integers are represented in binary. – Nital Sep 10 '15 at 03:53
  • Yes; they are "bitwise" because they modify the bits that make up a number. They can be used on any data type, as long as that data type can be safely cast to an `int` or `long`. Many people prefer to use `long`s for bit operations, though. – Purag Sep 10 '15 at 03:54

1 Answers1

1

The difference is in something called "short circuiting".

The & and | operators always evaluate both sides of the operands.
The && and || operators "short circuits" the operation by not evaluating the right operands if it isn't necessary.

  • And what about the fact that `&` and `|` are bitwise operators, and `&&` and `||` are logical operators? – tomasyany Sep 10 '15 at 03:35
  • Ok. Maybe I need to be more specific. What I mean is when `&` and `|` is used as logical operators –  Sep 10 '15 at 03:36