• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is the advantage of Arithmetic Assignment Operators like += over normal arithmetic operator?

 
Halley Thomas
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which is better?

a+=b;

or

a=a+b;

Can you please explain why also?
 
Anupam Jain
Ranch Hand
Posts: 61
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Halley Thomas wrote:Which is better?

a+=b;

or

a=a+b;

Can you please explain why also?


As far as I've found out and understood...
While incrementing by a variable as above... They are both same.
But if you are incrementing by some constant value say 1 like this :

i = i + 1;

and

i += 1;

Then the later one is more efficient...

This can be explained by using javap command..

javap -c <class name>

 
Halley Thomas
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator




Found this. It means there is no improvement in performance if use the += operator if I have two variables, right?
 
Anupam Jain
Ranch Hand
Posts: 61
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Halley Thomas wrote:
It means there is no improvement in performance if use the += operator if I have two variables, right?


Yeah right... I found the same thing when using another variable b.

But try replacing b with some constant number say 1 or 2. You'll see the difference then...
 
Halley Thomas
Greenhorn
Posts: 9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code when b is replaced by a constant.


Yes. I'm just posting it here for others who might want to see.
Thanks a lot!
 
Matthew Brown
Bartender
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The only real advantage is clarity - use += if and when it makes your code easier to read. I think most people would say x += 5 is more easily read than x = x + 5, and x++ is more easily read than x += 1. Once you're used to the notation, anyway.
 
Rob Spoor
Sheriff
Pie
Posts: 20512
54
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another advantage of using += is you don't need any casting when you use bytes:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic