-1

This is something i thougth about,if i'll set a boolean to the no of itself,it will just set the opposite.

boolean isRunning = true;

isRunning = !isRunning; //Changes to true.

isRunning = !isRunning; //Changes to false.

Now, my question is..there is something wrong using that? cause i see no one programming in this way.

Orel Biton
  • 3,478
  • 2
  • 15
  • 15
  • 3
    This is a perfectly valid statement and I've seen this quite frequently. – Mike Christensen Apr 12 '13 at 16:17
  • Thanks for the answer Mike.. i just wanted to know if it is valid – Orel Biton Apr 12 '13 at 16:17
  • This would normally be called toggling - you are toggling the value of the boolean. – Oded Apr 12 '13 at 16:18
  • If you know you are setting the boolean to `true` or `false`, then it is probably better to do that explicitly, instead of toggling. Even if you know the current value is opposite and toggling will do the same thing when you are writing the code, you or someone else reading the code later won't know/remember, and has to examine it carefully, if toggling is used. – hyde Apr 12 '13 at 20:10

3 Answers3

3

No, there is absolutely nothing wrong with this construct. In fact, it is pretty common.

See Cleanest way to toggle a boolean variable in Java?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

Not at all. The unary operators are used as shown by Java's tutorials, e.g. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html

blackpanther
  • 10,998
  • 11
  • 48
  • 78
0

Consider the alternative:

if (isRunning) {
    isRunning = false;
} else {
    isRunning = true;
}

Obviously what you have written is more clear and succinct.

GriffeyDog
  • 8,186
  • 3
  • 22
  • 34