1

What exactly does a + symbol do in front of an expression in Java?

In Java, a mathematical expression can be lead by a - symbol, as well as the + symbol, like in the following:

System.out.println(-5); // Prints -5
System.out.println(+5); // Prints 5
System.out.println(-(3 + 2)); // Prints -5
System.out.println(+(3 + 2)); // Prints 5

The - symbol clearly negates the value of the following expression and the + symbol does nothing. So if the - symbol negates an expression, I'd expect the + symbol to force an expression to be positive, otherwise it'd have no use, but when I tested this...

    int pos = 5;
    System.out.println(-pos);// -5
    System.out.println(+pos);// 5
    System.out.println(+ + + + + + + +pos);// 5

    int neg = -5;
    System.out.println(-neg);// 5
    System.out.println(+neg);// -5
    System.out.println(+ + + + + + + +neg);// -5

    System.out.println(5);// 5
    System.out.println(-5);// -5
    System.out.println(+5);// 5
    System.out.println(-+5);// -5
    System.out.println(+-5);// -5

(The comment is what gets printed for that line.) It seems to me that the + sign in front of an expression is useless, but that makes me wonder why Java allows that code.

So my question is, what is the use of a + symbol in front of an expression in Java.

Aaya
  • 33
  • 1
  • 5
  • *So if the `-` symbol negates an expression, I'd expect the `+` symbol to force an expression to be positive*. But `-` doesn't force an expression to be negative. – shmosel Nov 28 '17 at 00:39
  • 1
    The operators do the same thing as in maths. Prefixing a number with a positive sign adds no information in Java nor in maths. – Dici Nov 28 '17 at 00:41
  • `+` sign is explicitly making the number positive. because even if you don't put `+` on a value, it is always positive unless you negate it with `-`. – msagala25 Nov 28 '17 at 00:42
  • 1
    Unary `+` converts the type to `int` when the starting type is `<= int`. Other than that, unary `+` can be seen as a no-op, as numbers without a specified sign are positive by default. – BackSlash Nov 28 '17 at 00:42
  • @BackSlash interesting, didn't know it would upcast to an `int` – Dici Nov 28 '17 at 00:44
  • @shmosel Yes, I know that `-` doesn't force an expression to be negative, but I couldn't find any other use for the `+` symbol and... it just kinda felt right... Anyways, that's why I came here. – Aaya Nov 28 '17 at 00:45
  • 2
    @Dici If you want to investigate on that, it's covered in [JLS 5.6.1](https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.6.1) - *If the operand is of compile-time type Byte, Short, Character, or Integer, it is subjected to unboxing conversion (§5.1.8). The result is then promoted to a value of type int by a widening primitive conversion (§5.1.2) or an identity conversion (§5.1.1).* – BackSlash Nov 28 '17 at 00:47
  • @BackSlash haha cool, not that this can or should be used too often but nice to know. Thanks :) – Dici Nov 28 '17 at 00:49

0 Answers0