[java] Difference between & and && in Java?

Possible Duplicates:
What's the difference between | and || in Java?
Difference in & and &&

I was just wondering what the difference between & and && is?
A few days I wrote a condition for an if statement the looked something like:

if(x < 50 && x > 0)

However, I changed the && to just & and it showed no errors. What's the difference?


Example: I compiled this simple program:

package anddifferences;

public class Main {

    public static void main(String[] args) {
        int x = 25;
        if(x < 50 && x > 0) {
            System.out.println("OK");
        }

        if(x < 50 & x > 0) {
            System.out.println("Yup");
        }
    }
}

It printed "OK" and "Yup". So does it matter which one I use if they both work?

This question is related to java operators

The answer is


& is bitwise. && is logical.

& evaluates both sides of the operation.
&& evaluates the left side of the operation, if it's true, it continues and evaluates the right side.


&& == logical AND

& = bitwise AND


& is bitwise AND operator comparing bits of each operand.
For example,

int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100


&& is logical AND operator comparing boolean values of operands only. It takes two operands indicating a boolean value and makes a lazy evaluation on them.


'&' performs both tests, while '&&' only performs the 2nd test if the first is also true. This is known as shortcircuiting and may be considered as an optimization. This is especially useful in guarding against nullness(NullPointerException).

if( x != null && x.equals("*BINGO*") {
  then do something with x...
}