Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between =+ and += in Java? [duplicate]

Tags:

java

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?

like image 394
d0001 Avatar asked Nov 28 '16 19:11

d0001


Video Answer


2 Answers

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

like image 121
ΦXocę 웃 Пepeúpa ツ Avatar answered Sep 29 '22 01:09

ΦXocę 웃 Пepeúpa ツ


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

like image 20
Daniel Williams Avatar answered Sep 29 '22 02:09

Daniel Williams