What does ! mean in Java with examples

According to Oracle Java docs, ! is a unary operator. It is called a 'NOT' operator. It can be used to convert false to true or vice versa. By using this operator, the logical state of an operand is reversed. In simple words, it inverts the value of a boolean.

Read Also: What does \n and \t mean in Java

What are Unary operators?

Unary operators are those operators which require a single operand.

Syntax
 !(operand) 

Examples of ! in Java

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

// initializing variables int a = 100, b = 10; boolean visible = true; // Printing variable values System.out.println("Is visible: " + visible); System.out.println("a: "+ a + " b: " + b); // Using unary operator ! System.out.println("Is visible: "+ !visible); System.out.println(" !(a > b) : " + !(a > b)); System.out.println(" !(a < b) : " + !(a < b)); } }


Output:
Is visible: true
a: 100 b: 10
Is visible: false
!(a > b) : false
!(a < b) : true

Compiler Error

If the expression to the right of the ! operator doesn't evaluate to a boolean, then it will throw a compiler error 'bad operand type for unary operator' as shown below:
 public class UnaryNotOperator2 {
    public static void main(String args[]) {
     // initializing variables a and b     
     int a = 1, b = 10;
 
     // Printing variable values
     System.out.println("a: "+ a + " b: " + b);
     
     // Using unary operator !
     System.out.println(" !(a + b) : " + !(a + b));
    }
}


Output:
/UnaryNotOperator2.java:10: error: bad operand type int for unary operator '!'
          System.out.println(" !(a + b) : " + !(a + b));
                                                                    ^ 
1 error


Explanation:

The cause of this error is that (a+b) is a numeric expression that will return an integer value. We all know ! is a unary operator and it expects a boolean value. Since (a+b) expression is evaluating to int and ! operator is expecting boolean, so the above code is giving the compilation error.

Equality operator !=

This operator is pronounced as not equal to operator. I have explained this in detail here.

That's all for today, please mention in the comments in case you have any questions related to the what does ! operator mean in Java with examples.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry