-7

Possible Duplicate:
Difference in & and &&

if (true && true) {
    System.out.println("test if");
}

if (true & true) {
    System.out.println("test if");
}

both are give same output.why ?

Community
  • 1
  • 1
Hemant Patel
  • 11
  • 1
  • 1
  • 1

7 Answers7

6

&& short-circuits, wheras & doesn't. Example:

if (methodA() && methodB()) {
    ...
}

In that case, if methodA already returns false, methodB is not called. Formally, if you have an expression a && b, b is only evaluated if a evaluated to true.

Apart from the obvious performance benefit, this is particularly useful for null checks:

if (x != null && x.getSomeValue()) {
    ...
}

If you used a s single & here, x.getSomeValue() would be evaluated even if x were null, resulting in an exception.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
1

In the first case, you don't test the second part of the if : the && operator executes from left to right and stops at the first false value.

This may be useful in this case :

if (a!=null && a.doSomething()==23) {

because it prevents a nullPointerException.

When you test boolean conditions, always use &&.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

& is a bit operation

&& logically links two booleans

Kai
  • 38,985
  • 14
  • 88
  • 103
1

Please see: http://www.jguru.com/faq/view.jsp?EID=16530

It depends on the type of the arguments...

For integer arguments, the single ampersand ("&")is the "bit-wise AND" operator. The double ampersand ("&&") is not defined for anything but two boolean arguments.

For boolean arguments, the single ampersand constitutes the (unconditional) "logical AND" operator while the double ampersand ("&&") is the "conditional logical AND" operator. That is to say that the single ampersand always evaluates both arguments whereas the double ampersand will only evaluate the second argument if the first argument is true.

For all other argument types and combinations, a compile-time error should occur.

dbalakirev
  • 1,918
  • 3
  • 20
  • 31
0

In & statetment it will check both left side and right side statements.in && will check only one side of statement(if one side is true it will not check other side)

Ramindu Weeraman
  • 344
  • 2
  • 10
0

&& is the logical AND

so you want to make sure BOTH statements become true.

& is the bitwise AND operator

Have a look here:

http://www.javaforstudents.co.uk/TrueFalse

Stefan
  • 2,603
  • 2
  • 33
  • 62
0

&& is logical and. true && true is true and everything else is false. & is bitwise and. (10 & 8) = 8

Rahul Baradia
  • 11,802
  • 17
  • 73
  • 121