2

Possible Duplicates:
logical operators in java
What's the difference between | and || in Java?

As the title says, I need to know the difference between & operator and && operator. Can anyone help me in simple words.

  1. How do they differ from each other?
  2. And which one to be used in a IF statement?
hubalazs
  • 448
  • 4
  • 13
Andro Selva
  • 53,910
  • 52
  • 193
  • 240

3 Answers3

6

There are in fact three "and" operators:

  • a && b, with a and b being boolean: evaluate a. If true, evaluate b. If true, result is true. Otherwise, result is false. (I.e. b is not evaluated if a is not true.)
  • a & b, with a and b being boolean: evaluate both, do logical and (i.e. true only if both are true).
  • a & b, where a and b are both integral types (int, long, short, char, byte): evaluate a and b, and do a bitwise AND.

The second one can be viewed as a special type of the third one, if one sees boolean as a one-bit integral type ;-)

As the top-level condition of an if-statement you can use the first two, but the first one is most likely useful. (I.e. there are not many cases where you really need the second and the first would do something wrong, but the other way around is more common. In most cases the first is simply a little bit faster.)

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
4

If the first result is FALSE, && doesn't evaluate the second result. & does.

user541686
  • 205,094
  • 128
  • 528
  • 886
  • 2
    is not *entirely* correct. There's another difference: The `&` operator is also the bit-wise AND operator, whereas && is not. – Bohemian Jun 09 '11 at 01:43
  • @Bohemian: One could say this is already in the question title. – Paŭlo Ebermann Jun 09 '11 at 01:49
  • @Bohemian: Click Edit on my answer, what you see might be interesting. :P (As to why I commented it out: Because part of it is wrong for Java, and part of it is a little redundant -- you can't use `&&` for integers anyway, so you can't really go wrong here.) – user541686 Jun 09 '11 at 02:03
4

&& only evaluates the second expression if the first operation is true. & evaluates both expressions (even if the first expression is false and there is no point in evaluating the second expression). Hence && is a tiny bit faster than & in logical operations. Hence && is also known as short-circuit and.

& can also be used as a bitwise operator in addition to a logical operator. So you can do a 'Bit And' of 2 numbers like for example

int result = 1 & 3; // will evaluate to 1

&& cannot be used as a bit-and operator.

For conditional IF operator, use &&. It is a tiny bit faster than just &.

Basanth Roy
  • 6,272
  • 5
  • 25
  • 25