Difference between logical operators in Java.

UPDATED: 15 October 2010
We all using logical operators in programming language but still some of you don't know difference between " | "(Single OR) and " || "(Double OR) like wise for " & ". Lets take a look on below code.

package com.javaquery.examples;
public class logical_opr {
     public static void main(String[] args) {
        int x = 2, y = 5;
        if(++x > 2 | ++y > 3){
            System.out.println("Value of X:"+x +" Value of Y:" +y);
        }
        x = 2 ;
        y = 5 ;
        if(++x > 2 || ++y > 3){
            System.out.println("Value of X:"+x +" Value of Y:" +y);
        }
    }
}
/*
Output:
Value of X:3 Value of Y:6
Value of X:3 Value of Y:5 //Value of Y is not changed in " || ".
*/

When we use "|" in program it'll check both the condition where in "||" the program checks for the first condition and if it satisfy the logic for "||" it'll not waste time to check next condition and go to next code.

- Use of " & " and  " && " is same like above. When we use " && " if first condition is FALSE then it'll not check second condition and save time.

0 comments :