3

In our java code i have encountred a line which i didnot understand why
total = + - valFromsp; or total = - + valFromsp; so I wrote small program and attached it here.

public class Test {

    public static void main (String... arg) {
        int total =  20;
        int valFromsp = 60 ; 
        total = + - valFromsp;

        System.out.println(total);  // prints -60

    }
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
sharief
  • 59
  • 7

2 Answers2

6

It just means this:

total = -valFromsp;

The line of code is an assignment statement with the right hand side expression being + - valFromsp. What does + - valFromsp mean? If we add brackets, it becomes +(-(valFromsp)).

The unary operator - operates on the operand valFromsp making it -60. And then the + unary operator operates on -60 to do nothing to it.

The + and - unary operators are specified in §15.15 of the Java language specification:

The operators +, -, ++, --, ~, !, and the cast operator (§15.16) are called the unary operators.

UnaryExpression: 
    PreIncrementExpression 
    PreDecrementExpression 
    + UnaryExpression
    - UnaryExpression 
    UnaryExpressionNotPlusMinus

The use of the + unary operator is further specified in §15.15.3:

Unary numeric promotion (§5.6.1) is performed on the operand. The type of the unary plus expression is the promoted type of the operand. The result of the unary plus expression is not a variable, but a value, even if the result of the operand expression is a variable.

But since you are using ints, which does not undergo unary numeric promotion, + does nothing. Even if you are using byte, short or char, the + will still do nothing, because the - unary operator also does promotion. So there really isn't any reason to use both + and - at the same time.

I suggest you just change it to:

total = -valFromsp;

to avoid confusion in the future.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

let me start explaining this with a simple example, consider

total = + valFromsp;

the above line means total = total + valFromsp;

similar to this total = - + valFromsp means

total = - (total + valFromsp);

Now you can again further expand this as total = total - (total + valFromsp)

consider below example which gives same output

    int total = 10;
    int val = 50;
    //total = - + val; //this is also equals to the below line
    total = total - (total + val);
    System.out.println(total); //output -50.
Syam Danda
  • 587
  • 3
  • 12
  • 34