Tuesday, December 13, 2011

what is the difference between && and & in java ?

Difference between && and &:
1. Single & can be used as both bitwise operator and logical operator. But && can be used as only logical operator.

2. When we use double && between two expressions, if first expression returns false, second expression will not be evaluated. When we use single & between two expressions, Both expressions will be evaluated even first expression is false.

Example:

Using Single &:
int i=6;
if(i<4 & i++<10)
{
//some code
}

here
first expression: i<4
second expression: i++<10
In the above example, first expression is false. Because i value is 6. But second expression is also evaluated so now i value is 7.

Using &&:


int i=6;
if(i<4 && i++<10)
{
//some code
}

here
first expression: i<4
second expression: i++<10
In the above example, first expression is false. Because i value is 6. But second expression will not be evaluated.