Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Unary minus

The `-x` operator computes arithmetic negation after numeric promotion. It does not change `x`. At the minimum `int` or `long` value, overflow leaves the value unchanged.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

-x

-x means arithmetic negation of one operand, not subtraction of two operands. It does not assign the result to x.

The operand must be numeric or unbox to a numeric type. Unary numeric promotion converts byte, short, and char to int; int, long, float, and double retain their types. The result has the promoted type. Unboxing null throws NullPointerException.

Negating Integer.MIN_VALUE or Long.MIN_VALUE produces the same value: overflow throws no exception. For floating-point numbers, zero and infinity change sign, while NaN remains NaN.

The example demonstrates promotion from byte to int, unchanged x, overflow, and negative zero.

Examples

public class Main {
    public static void main(String[] args) {
        byte x = 7;
        int result = -x;
        System.out.println(result);
        System.out.println(x);
        System.out.println(-Integer.MIN_VALUE);
        System.out.println(-0.0);
    }
}

Result

-7
7
-2147483648
-0.0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources