Witscale Test Center

5.2 Conditional statements: if, if-else and switch > 5.2.3 Argument to the if statement


5.2.3 Argument to the if statement

The argument to an if() statement is always boolean. If you are giving an expression as an argument, you must see to it that the expression is always evaluated as a boolean value. For example:

int a = 6;

int b = 8;

if(a < b) {

}

The argument to if() is the expression a < b, even if this expression involves two values of int type, its result is boolean . The value of expression  (a < b) is either true or false. You can also use a single boolean argument in if() statements as:

 

    boolean isCheap = price < 10;

    if(isCheap) {

      // do something

    }

 

In some programming languages, boolean values can be represented in numbers. Say for instance, 0 for false and 1 for true. However, in Java, that is not the case. 0 and 1 are values of int type. They cannot be used as boolean. Table 5.1 summarizes some sample valid and invalid expressions which can be used as an argument in if() statements.

 

Table 5.1 Some valid and invalid arguments to the if() statement 

 

Valid Arguments

Invalid Arguments

if(true) {}

if(1){}

if(false) {}

if(0){}

int a = 0;

if (a==0) {}

int a = 0;

if (a) {}

int a = 0;

if (a > 6) {}

int a = 0;

if (a = 6) {}

boolean checked = false;

if(checked=true) { }

int number  = 8;

if(number = 8) { }

 

You may be surprised as to why (number=8) is invalid boolean expression and (checked=true) is a valid one. In Java, the assignment statement returns the assigned value. Therefore when if(checked=true) is executed, the variable checked is assigned to true and the assigned value, true, is returned. Therefore the if(checked=true) becomes if(true) which if perfectly valid. On the other hand, in if(number = 8), the number variable is assigned the value of 8 and this assigned value 8 is returned. So if(number = 8) becomes if(8). This is invalid as if() must have a boolean value as its argument.

 

Be careful with exam questions that have an assignment statement as an argument to the if statement. For example, if (a = 0) {}.  The if statement usually takes conditions which return boolean value as argument. But an assignment statement or any expression (even a method call) that returns boolean value is valid argument to if. Therefore carefully check the type of the expression passed to the if statement while answering such questions.