Witscale Test Center

9.3 Unary operators > 9.3.4 Logical complement ! operator


9.3.4 Logical complement ! operator

Like the bitwise complement operator, the logical complement operator ! also inverts a value. But it works only on boolean expressions and it inverts the boolean value. If the operand is evaluating to be true then this operator makes it false and if the operand is false then it inverts it to true. In the following code, the notABlockedEmail is a logical complement of isBlockedEmail.

 

String email =”johnq@example.com”;

boolean isBlockedEmail = email.equals("blocked@example.com");

boolean notABlockedEmail = ! isBlockedEmail;

 

Since logical complement returns a boolean value, it is commonly used to specify conditions. It is especially useful when you want to perform some operations only when the given condition is false. Table 9.4 compare the code fragments with and without the ! operator. Without the complement operator, the if statement is executed when specified condition is true.

 

Table 9.4 Usage of boolean complement operator !

 

Without complement operator (

With complement operator

if(email.equals("blocked@example.com"))

  // do nothing

else {

 // process email 

 // send acknowledgment

}

if(!email.equals("blocked@example.com")) {

 // process email 

 // send acknowledgment

}

 

 

Since we do not want to do anything when the condition is true, the if statement does nothing. It is added only to specify the condition. We can eliminate the need of such if statement by negating the condition with the complement operator.