2

In Java (or, to be honest, any computer language), to increment an int, you do as so:

// Option 1 - efficient
int x = 0;
x++;
// x = 1

// Option 2 - works, but is ugly
int y = 0;
y = y + 1;
// y = 1;

How would you do this to a boolean?

// Standard way to
// oppose a boolean
boolean isTrue = false;
if(isTrue){
    isTrue = false;
} else if(!isTrue){
    isTrue = true;
}

Is there not a shortcut to change a boolean? For example, if the boolean was true, is there a way to change it with just a small shortcut like x++;?

moffeltje
  • 4,521
  • 4
  • 33
  • 57
user3422952
  • 319
  • 2
  • 8
  • 17
  • I actually prefer `++/--` *not* being part of a language. They are very useful for "C-like" code, but can also lead to abuse in expressions. – user2864740 Apr 27 '14 at 17:31
  • Why so? You prefer typing `int a; a = a + 1;`? – user3422952 Apr 27 '14 at 17:34
  • Actually `a += 1` (in Java this is also an expression, although if I were designing a language all assignments would only be statements, but I digress). – user2864740 Apr 27 '14 at 17:38

2 Answers2

10

You can use ! to flip its value.

isTrue = !isTrue;

! inverts the value of a boolean.

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
2

No, there is no such shortcut in Java.

What you can do is use the logical complement operator to reverse the value

!isTrue

but you will have to reassign the result.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724