In Java, you can use the !
operator to negate a boolean value. The !
operator is often used in an if
statement to execute a block of code if a condition is false
.
Here is an example of how to use the !
operator in an if
statement to check if a number is not positive:
int number = 10; if (!(number > 0)) { System.out.println("The number is not positive."); }
In this example, the condition number > 0
is evaluated to true
, so the !
operator negates it to false
. As a result, the code inside the curly braces is skipped and the message is not printed to the console.
You can also use the !
operator in an if-else
statement to execute different blocks of code based on whether a condition is true
or false
. The syntax for the if-else
statement is as follows:
if (condition) { // code to execute if the condition is true } else { // code to execute if the condition is false }
Here is an example of how to use the !
operator in an if-else
statement to check if a number is positive or not positive:
int number = 10; if (number > 0) { System.out.println("The number is positive."); } else { System.out.println("The number is not positive."); }
In this example, the condition number > 0
is evaluated to true
, so the code inside the first set of curly braces is executed and the message "The number is positive." is printed to the console.
It is important to carefully consider the conditions and actions in your if
and if-else
statements to ensure that your code is correct and easy to understand.