0

Possible Duplicate:
& vs && and | vs ||
What are the cases in which it is better to use unconditional AND (& instead of &&)

While checking for the simple AND condition, i can use '&' and '&&'. It works fine with '&' and as well as '&&'. Is there any difference between those two.

sample code:

if(sample!=null & sample.size())
if(sample!=null && sample.size()
Community
  • 1
  • 1
Jagadeesh
  • 2,730
  • 6
  • 30
  • 45

6 Answers6

2

The first version (&) always evaluates both arguments. The second version (&&) evaluates the second argument only if the first argument has been evaluated to TRUE.

Same applies to the OR operator: there is | and ||. The (||) evaluates the second argument only if the first argument has been evaluated to FALSE.

Ilya Shinkarenko
  • 2,134
  • 18
  • 35
1

first expression check both sides, second expression checks 2nd side only if 1st is true.

dantuch
  • 9,123
  • 6
  • 45
  • 68
1

It evaluates both the left hand side and the right with just a singular &, even if the last hand side is false.

See my question below for the finer details...

When should I not use the Java Shortcut Operator &

Community
  • 1
  • 1
David
  • 19,577
  • 28
  • 108
  • 128
1
'&' for bit wise 'AND'
'&&' is for Logical 'AND'
Siva Arunachalam
  • 7,582
  • 15
  • 79
  • 132
1
if(sample!=null & sample.size())

Here if first condition is not satisfied then also it will check next condition.

if(sample!=null && sample.size())

Here if first condition is not satisfied then also it will not check next condition.

dantuch
  • 9,123
  • 6
  • 45
  • 68
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
1

The && is a short-circuit operator meaning that if sample is null in your example, it will stop and not evaluate the second condition.

On the other side, the & is not short-circuit and will evaluate sample.size() even if sample is null. Of course in this case it will throw NullPointerException, but in the short-circuit case it won't.

Dan D.
  • 32,246
  • 5
  • 63
  • 79