Home Java Java-tips Data Expressions Extended Assignment Operators

Ask Questions?

View Latest Questions

Advertisement


 
 

Extended Assignment Operators
Posted on: July 26, 2006 at 12:00 AM
It can not be used with the logical short-circuit operators && and ||, but you can use the & and | versions.

Java Notes: Extended Assignment Operators

 

In this tutorial you will learn how to use the extended assignment operators.

 

It's very common to see statement like the following, where you're adding something to a variable.

 

sum = sum + currentValue;
i = i + 2;

 

A shortcut way to write assignments like this is to use the += operator.

 

It's one operator symbol so don't put blanks between the + and =.

 

With this notation it isn't necessary to repeat the variable that is being assigned to.

 

// Same as "sum = sum + currentValue"
sum += currentValue;   

// Same as "i = i + 2"
i += 2;                

Commonly used with arithmetic operators

You can use this style with all arithmetic operators (+, -, *, /, and even %).

measurementRange /= 2;         // Divides measurementRange by 2.
accountBalance -= withdrawal;  // Subtracts withdrawal from accountBalance.

Four ways to add one

There are four ways to add one to a variable. Many languages only support the first way. Current compilers translate them into equivalent code, so there's no efficiency difference, unlike early C compilers where ++ was more efficient.

i = i + 1;        // Common in all languages.
i += 1;           // Common when adding values other than one.
i++;              // Most common, but only works for adding one.
++i;              // Least common.

Can be used with most computational operators

This notation can also be used with the bit operators (^, &, |). It can not be used with the logical short-circuit operators && and ||, but you can use the & and | versions. It can only be used with binary (two operand) operators, not unary operators.

Where it makes a difference

For simple variables, which kind of assignment to use is mainly a style or readability difference. However, when assigning to l-values that require computation, there is a real difference, both in performance and possible side-effects.

a[f(x)] = a[f(x)] + 1;   // Calls f(x) twice!
a[f(x)] += 1;            // Calls f(x) only once.
Advertisement


DMCA.com