-1

I remember reading somewhere in Java, possibly Oracle documentation that there is a shortcut to assign a flip value of a primitive.

Similar to:

int i = 0;
i += 3;
System.out.println(i);

Output is 3, but what if I wanted -3? Or if given -3, make it positive 3? Rather than doing

i = -i;

Isn't there a shortcut to do it in just the assignment operator?

Otanan
  • 459
  • 3
  • 12

3 Answers3

2

You have lots of options:

i = -3;
i += -3;
i -= 3;

Or even

i = 3;
System.out.println("-" + i);
rgettman
  • 176,041
  • 30
  • 275
  • 357
1

If you want to reverse the sign of a number you can do one of the following things:

i *= -1;
i = -i;
BitNinja
  • 1,477
  • 1
  • 19
  • 25
0

int i = -3; is your easiest solution

peter.petrov
  • 38,363
  • 16
  • 94
  • 159