7

Can anyone explain what is happening when you use =+ ?

int one = 1 ;
int two = 2 ;

int sum1 = 0 ;
int sum2 = 0 ;

sum1 =+ one ;
sum2 += two ;

sum1 =+ two ;
sum2 += one ;

System.out.println(sum1) ;
System.out.println(sum2) ;

Output:

2
3

Why is 1st line 2?

d0001
  • 2,162
  • 3
  • 20
  • 46
  • 1
    `sum1 =+ two` is similar to `sum1 = 0 + two`, `sum2 += one` is similar to `sum2 = sum2 + one`. There probably is duplicate with JLS for that already so I don't want to post it as answer. – Pshemo Nov 28 '16 at 19:33
  • 1
    `=+` does nothing; it's the same as `=` here. You have just written `sum1 = two`. `sum2 += one` on the other hand is essentially the same as `sum2 = sum2 + one`. – RaminS Nov 28 '16 at 19:33

2 Answers2

11

Doing this

sum1 += one ;

is the same as sum1 = (sum1_type)(sum1 + one);

and doing this

sum2 =+ two ;

is the same as

and doing this sum2 = two; (Unary plus operator; indicates positive value) and is not affecting the sign of variable two

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • 3
    "`sum1 += one ;` is the same as `sum1 = sum1 + one ;`" no, it is not the same, it is similar but not same. Counterexample can be found here: http://stackoverflow.com/questions/8710619/javas-compound-assignment-operators – Pshemo Nov 28 '16 at 19:40
  • they are both ints.... so it is the same... – ΦXocę 웃 Пepeúpa ツ Nov 28 '16 at 19:44
  • OK you are right about this case so `+1`, but it is worth remembering that it is not always the same for all cases. – Pshemo Nov 28 '16 at 20:08
3

Java doesn't care too much for white space. =+ is being interpreted as = for assignment and + for the unary plus operator which doesn't have any effect here. It is a little used operator and you can read about exactly what it does here http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.3

You can read more about the different operators in Java here https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html

Daniel Williams
  • 8,673
  • 4
  • 36
  • 47
  • 3
    I don't think `+` is conversion to a positive number. It doesn't seem to do anything at all. I tried `int a = -5; System.out.print(+a);` and it prints `-5`. `System.out,print(-a)`, however, does print `5`. – RaminS Nov 28 '16 at 19:40