Difference between & and && in Java?

Mxyk picture Mxyk · Aug 26, 2011 · Viewed 469.4k times · Source

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?

Answer

Jeffrey picture Jeffrey · Aug 26, 2011

& 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.