Assignment operators in Java

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.

public class Sample {

	public static void main(String[] args) {

		int a = 10;
		int b ;
		// assign value of right variable to left	
		b = a;	
		
		System.out.println("b =" + b);
		System.out.println("a =" + a);
		
	}
}

 

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

public class Sample {

	public static void main(String[] args) {

		int n = 10;
		
		n += 5; // same as n = n+5;
		System.out.println("n =" + n);	
		
	}
}

Output:

n =15

 

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

 

-= Java Example

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

public class Sample {

	public static void main(String[] args) {

		int n = 10;
		
		n -= 5; // same as n = n-5;		

		System.out.println("n =" + n);	
		
	}
}

Output:
n =5

 

*= java examples

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

Java Code example

public class Sample {

	public static void main(String[] args) {

		int n = 10;
		
		n *= 5; // same as n = n*5;		

		System.out.println("n =" + n);	
		
	}
}

Output:
n =50

 

/= Java Examples

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

Java Code example

public class Sample {

	public static void main(String[] args) {

		int n = 10;
		
		n /= 5; // same as n = n/5;		

		System.out.println("n =" + n);	
		
	}
}

Output:
n =2

 

%= Java Examples

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

Java Code example

public class Sample {

	public static void main(String[] args) {

		int n = 10;
		
		n %= 5; // same as n = n%5;		

		System.out.println("n =" + n);	
		
	}
}

Output:
n =0



Leave a Comment