programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Liutauras Vilda
• Tim Cooke
• Jeanne Boyarsky
• Paul Clapham
Sheriffs:
• Devaka Cooray
• Ron McLeod
• paul wheaton
Saloon Keepers:
• Tim Moores
• Piet Souris
• Tim Holloway
• Stephan van Hulst
• Carey Brown
Bartenders:
• Al Hobbs
• Frits Walraven
• Scott Selikoff

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

Greenhorn
Posts: 9
• Number of slices to send:
Optional 'thank-you' note:
Which is better?

a+=b;

or

a=a+b;

Can you please explain why also?

Ranch Hand
Posts: 61
• Number of slices to send:
Optional 'thank-you' note:

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
• Number of slices to send:
Optional 'thank-you' note:

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
• Number of slices to send:
Optional 'thank-you' note:

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
• 1
• Number of slices to send:
Optional 'thank-you' note:
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!

Bartender
Posts: 4568
9
• Number of slices to send:
Optional 'thank-you' note:
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.

Sheriff
Posts: 22701
129
• 1
• Number of slices to send:
Optional 'thank-you' note:
Another advantage of using += is you don't need any casting when you use bytes: