Java Assignment Operators

You are already familiar with the assignment operator (=), which assigns a value to a variable.

 int x = 12;

This assigned the value 12 to a variable called x of type int.
Java provides a number of assignment operators to make it easier to write code.
Addition and assignment (+=):

int a = 5;
int b = 25;
b += a; // b = b + a;
// b is 30 and a is 5
Subtraction and assignment (-=):
int a = 5;
int b = 20;
b -= a; // b = b - a;

// b is 15 and a is 5
Multiplication and assignment (*=):
int a = 5;
int b = 20;
b *= a; // b = b * a;

// b is 100 and a is 5
Division and assignment (/=):
int a = 5;
int b = 20;
b /= a; // b = b / a;

// b is 4 and a is 5
Remainder and assignment (%=):
int a = 4;
int b = 27;
b %= a; // b = b % a;

// b is 3 and a is 4
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s