Assignment operators in Java

(Last Updated On: February 25, 2019)

Learn about assignment operator in java with example and easy explanation. Also, learn assignment operator combined with arithmetic operators in java like +=, *= etc. with example.

 

= Assignment operator in java

Assignment operator in java program is used to assign a value to a variable.

For example,
int a = 10;
Also, value of one variable can be assigned to another variable. For example, if two variables are a and b, value of b can be assigned to a as

a = b; // right hand side value will be assigned to left hand variable.

Note that right hand side variable must be initialized, means, it must have some value.

 

NOTE: Assignment (=) operator can be combined with other operators like +=, -=, *= and /= in java language

Examples below.

+= , -=, *=, /=

e.g.
if variable is int a =10;
then n += 5; will result into 15.

 

+= Java Example

n += 5; is same as n = n+5.
Java Code Example

Output:

n =15

 

Similarly, others -=, *= and /= works

 

-= Java Example

note that n -= 5; is same as n=n-5;

Output:
n =5

 

*= java examples

n *= 5; is same as n=n*5;

Java Code example

Output:
n =50

 

/= Java Examples

n /= 5; is same as n=n/5;

Java Code example

Output:
n =2

 

%= Java Examples

n %= 5; is same as n=n%5;

Java Code example

Output:
n =0