Blog

Assignment Operator

This operator is used to assign a value to a variable. The form of assignment will be like this var=expression

There are different ways to use assignment operators, let us discuss below

‘=’: This is assignment operator. It assigns the value of left operand to the right operand.

The below example assigns the integer 5 to x.

int x =5;

‘+=’: This operator adds the left and right operands and it assigns the result value to left operand.

The below example will add x+y(2+2) and assigns the result to x so the result will be 4

package com.test.basics;

public class TestAssignmentOperator {

	public static void main(String[] args) {
		
		int x=2;
		int y=2;
		
		x+=y;
		
		System.out.println("Printing the final value "+x);

	}

}

‘-=’: This operator subtracts the left and right operands and it assigns the result value to left operand.

The below example will subtract x-y(2-2) and assigns the result to x so the result will be 0

package com.test.basics;

public class TestAssignmentOperator {

	public static void main(String[] args) {
		
		int x=2;
		int y=2;
		
		x-=y;
		
		System.out.println("Printing the final value "+x);

	}

}

‘*=’: This operator multiplies the left and right operands and it assigns the result value to left operand.

The below example will multiply x*y(2+2) and assigns the result to x so the result will be 4

package com.test.basics;

public class TestAssignmentOperator {

	public static void main(String[] args) {
		
		int x=2;
		int y=2;
		
		x*=y;
		
		System.out.println("Printing the final value "+x);

	}

}

‘/=’: This operator divides the left by right operand and it assigns the result value to left operand.

The below example will divide x/y(2/2) and assigns the result to x so the result will be 1

package com.test.basics;

public class TestAssignmentOperator {

	public static void main(String[] args) {
		
		int x=2;
		int y=2;
		
		x/=y;
		
		System.out.println("Printing the final value "+x);

	}

}

‘%=’: This operator divides the left by right operand and it assigns the reminder/modulus value to left operand.

The below example will divide x%y(2%2) and assigns the result to x so the result will be 0

package com.test.basics;

public class TestAssignmentOperator {

	public static void main(String[] args) {
		
		int x=2;
		int y=2;
		
		x%=y;
		
		System.out.println("Printing the final value "+x);

	}

}

Therefore we have covered different types of assignment operators with examples above. Happy Learning in ITWhistle!!

Leave a Reply

Your email address will not be published. Required fields are marked *