aspose file tools*
The moose likes Beginning Java and the fly likes What is the advantage of Arithmetic Assignment Operators like += over normal arithmetic operator? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What is the advantage of Arithmetic Assignment Operators like += over normal arithmetic operator?" Watch "What is the advantage of Arithmetic Assignment Operators like += over normal arithmetic operator?" New topic
Author

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

Halley Thomas
Greenhorn

Joined: Nov 17, 2008
Posts: 9
Which is better?

a+=b;

or

a=a+b;

Can you please explain why also?
Anupam Jain
Ranch Hand

Joined: Mar 16, 2010
Posts: 61

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

Joined: Nov 17, 2008
Posts: 9




Found this. It means there is no improvement in performance if use the += operator if I have two variables, right?
Anupam Jain
Ranch Hand

Joined: Mar 16, 2010
Posts: 61

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

Joined: Nov 17, 2008
Posts: 9
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

Joined: Apr 06, 2010
Posts: 4422
    
    8

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

Joined: Oct 27, 2005
Posts: 19723
    
  20

Another advantage of using += is you don't need any casting when you use bytes:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: What is the advantage of Arithmetic Assignment Operators like += over normal arithmetic operator?