Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Unary plus operator

The expression +x returns the value of x after unary numeric promotion. It neither changes the sign nor increments x, but it can change the result type: byte, short, and char are promoted to int.

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

Syntax

+x

The operator +x acts on one numeric operand. It preserves its promoted value, so applying +x to a negative x still produces a negative number. It is not two-operand addition, string concatenation, or increment ++x.

Unary numeric promotion converts byte, short, and char to int; int, long, float, and double remain unchanged. Numeric wrapper types are unboxed first. Unboxing null throws NullPointerException. Operands of type boolean or String are not allowed and cause a compile-time error.

The result is a value, not a variable, so +x cannot be an assignment target. The operator itself does not write anything to x; evaluating a more complex operand can nevertheless have its own side effects.

In the example, x has type byte, while result gets type int through promotion. Casting to Object boxes the result as Integer, allowing its type to be displayed. The last line confirms that x is still -7.

Examples

public class UnaryPlusDemo {
    public static void main(String[] args) {
        byte x = -7;
        var result = +x;
        System.out.println(result);
        System.out.println(((Object) result).getClass().getSimpleName());
        System.out.println(x);
    }
}

Result

-7
Integer
-7

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