What does ! means in java? (With Examples)

Last updated:9th Sep 2022

In java, ! is a unary operator. it is known as NOT operator. you can reverse any boolean result of the operand (or condition) by using ! (not operator) operator. for example, !false returns true, and !true returns false.

what is a unary operator?

The operator will require only a single operand for performing any action on it and return a new value called the unary operator.

syntax:
!(operand)

Example of !(logical not) operator

class demonstration {
    public static void main(String[] args) {
        boolean flag = true;
        System.out.println(!(flag));  // false
    }
}
output
false

in the above program, we have declared flag value true but you get output as false because we have use ! operator.


! operator used with a comparison operator

In this example, we will use ! operator with if condition or comparison operator.

public class NotOperator {
    public static void main(String args[]) {

     int x = 200, y = 10;
     System.out.println("x: "+ x + " y: " + y);
     if(!(x < y)){
          System.out.println("inside if statement x < y");
     }
     System.out.println(" !(x > y) : " + !(x > y));
     System.out.println(" !(x < y) : " + !(x < y));
    }
}
output
x: 200 y: 10
inside if statement x < y
!(x > y) : false
!(x < y) : true