INTRODUCTION TO PROGRAMMING IN JAVA: EXAMPLE OF DISTINCTION BETWEEN & AND &&

The code given in Table 1 may be run to demonstarte the distinction between a logical & and &&. Table 2 gives the output produced by the code. From the output it can be seen that when method1 evaluates to false the second method (method2) is not called in the case of the && operator, while it is always called in the case of the & operator.

 
// LOCICAL AND APPLICATION
// Frans Coenen
// Monday 4 July 2005
// The University of Liverpool, UK
    
class LogicalAndApp{ 

    // ------------------- FIELDS ------------------------    
    
    /* None */
    
    // ----------------- METHODS ------------------

    /* Main method */
    
    public static void main(String[] args) {
        testMethod(true,true);
	testMethod(true,false);
	testMethod(false,true);
	testMethod(false,false);
	}

    /* TEST METHOD */
    
    private static void testMethod(boolean value1, boolean value2) {
        System.out.println("\nTEST USING: value1 = " + value1 + ", vlaue2 = " +
		value2);
		
        // Test using && operator
	System.out.println("*** Test Using \"&&\" operator ***");
	if (method1(value1) && method2(value2)) 
		System.out.println("\"&&\" operator = true");
	else System.out.println("\"&&\" operator = false");	
	
        // Test using & operator
	System.out.println("*** Test Using \"&\" operator ***");
	if (method1(value1) & method2(value2)) 
		System.out.println("\"&\" operator = true");
	else System.out.println("\"&\" operator = false");	
	}

    /* METHOD 1 */
    
    private static boolean method1(boolean value) {
    	System.out.println("Method 1 evaluated");
	
	return(value);
	}

    /* METHOD 2 */
    
    private static boolean method2(boolean value) {
    	System.out.println("Method 2 evaluated");
	
	return(value);
	}
    }

Table 1: Logical and operator evaluation program

TEST USING: value1 = true, vlaue2 = true
*** Test Using "&&" operator ***
Method 1 evaluated
Method 2 evaluated
"&&" operator = true
*** Test Using "&" operator ***
Method 1 evaluated
Method 2 evaluated
"&" operator = true

TEST USING: value1 = true, vlaue2 = false
*** Test Using "&&" operator ***
Method 1 evaluated
Method 2 evaluated
"&&" operator = false
*** Test Using "&" operator ***
Method 1 evaluated
Method 2 evaluated
"&" operator = false

TEST USING: value1 = false, vlaue2 = true
*** Test Using "&&" operator ***
Method 1 evaluated
"&&" operator = false
*** Test Using "&" operator ***
Method 1 evaluated
Method 2 evaluated
"&" operator = false

TEST USING: value1 = false, vlaue2 = false
*** Test Using "&&" operator ***
Method 1 evaluated
"&&" operator = false
*** Test Using "&" operator ***
Method 1 evaluated
Method 2 evaluated
"&" operator = false

Table 2: Output from code presented in Table 1




Created and maintained by Frans Coenen. Last updated 04 July 2005