Search code examples
javavariable-assignmentprimitive

Shortcut to assign a negative value to primitives


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?


Solution

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

    i *= -1;
    i = -i;