Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does an exclamation mark mean in Java?

Tags:

java

I'd like to confirm the meaning of != before a boolean expression in a control statement means the opposite:

For example:

if (!networkConnected()) 

Does that mean "if the network is not connected"?

like image 957
TheBlueCat Avatar asked Aug 05 '12 12:08

TheBlueCat


2 Answers

Yes it does mean the logical opposite. It works even with equals operator.

Assuming your method return a basic bool type

// means the Network is NOT connected
if (!NetworkConnected()) 

This is equivalent to

if (NetworkConnected() != true) 

So logically means

if (NetworkConnected() == false) 

Now assuming you method return a Boolean (indeed a real object), this means

// means the Network is NOT connected
if (! Boolean.TRUE.equals(NetworkConnected());

or

if (Boolean.FALSE.equals(NetworkConnected());
like image 75
Jean-Rémy Revy Avatar answered Sep 28 '22 19:09

Jean-Rémy Revy


Yes, it's boolean negation

So

true == true
!true == false
!!true == true
!!!true == false

Likewise with false

!false == true

The actual name for this unary operator is the Logical Complement Operator which inverts the value of a boolean

like image 43
AlanFoster Avatar answered Sep 28 '22 20:09

AlanFoster