TheBlueCat
TheBlueCat

Reputation: 1195

What does an exclamation mark mean in 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"?

Upvotes: 10

Views: 69510

Answers (6)

Josephine Mary
Josephine Mary

Reputation: 31

In java,exclamation mark (!) that is used for inverted the value and also we call Boolean negation operator (!= being not equal to).

example:if(string variable!=null) here check whether string variable is null or not.null means if block is not executed.otherwise it will be executed.

Upvotes: -2

Willi Mentzel
Willi Mentzel

Reputation: 29844

! is a unary operator that switches the boolean value of an expression.

Consider the following piece of code:

boolean b = true;

System.out.println(!b); // outputs: false
System.out.println(!!b); // outputs: true

b = !b; // first switch: b is false now
b = !b; // second switch: b is true now

So:

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

Yes!

Upvotes: 0

ACV
ACV

Reputation: 10562

To precisely answer your question: no. This operator != is not negation. It means NOT IDENTICAL and is the opposite of == which stands for identity.

Upvotes: 0

Jean-Rémy Revy
Jean-Rémy Revy

Reputation: 5677

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());

Upvotes: 20

AlanFoster
AlanFoster

Reputation: 8306

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

Upvotes: 12

Miquel
Miquel

Reputation: 15675

Yes. The exclamation mark negates the boolean that appears next to it.

Upvotes: 0

Related Questions