Java Assignment Operators

The Java Assignment operators are used to assign the values to the declared variables. The equals ( = ) operator is the most commonly used assignment operator. For example:

int i = 25;

The table below displays all the assignment operators in the Java programming language.

OperatorsExampleExplanation
=x = 9Value 25 is assigned to x
+=x += 9This is same as x = x + 9
-=x -= 9This is same as x = x – 9
*=x *= 9This is same as x = x * 9
/=x /= 9This is same as x = x / 9
%=x %= 9This is same as x = x % 9

Java Assignment Operators example

In this Java Program, we use two integer variables, a and Sum. Next, we will use these two variables to show the working functionality of all the Assignment Operators.

import java.util.Scanner;

public class AssignmentOperators {
	private static Scanner sc;
	public static void main(String[] args) {
		int a, Sum;
		sc = new Scanner(System.in);
		System.out.println(" Please Enter any integer Value: ");
		a = sc.nextInt();
		System.out.println(" Please Enter any integer Value for Total: ");
		Sum = sc.nextInt();
		
		System.out.format(" Value of Sum = %d \n", Sum += a );
		System.out.format(" Value of Sum = %d \n", Sum -= a );
		System.out.format(" Value of Sum = %d \n", Sum *= a );
		System.out.format(" Value of Sum = %d \n", Sum /= a );
		System.out.format(" Value of Sum = %d \n", Sum %= a );
	}
}
Java Assignment Operators 1

Within this example, the tenth line statement will ask the user to enter an integer value. Next, in this Java Program, we will assign the user input value to integer variable a.

The 12th line of the Java statement will ask the user to enter the integer value Sum. And then, we are going to assign the user input value to the integer variable Sum.

Next line, we performed all the assignment operations on a and Sum variables using available assignment operators. Let us see the functionality of the Assignment Operators in the Java Programming Language.

Sum += a means
Sum = Sum + a ==> 25 + 4 = 29

Sum -= a means
Sum = Sum – a ==> 29 – 4 = 25

Sum *= a means
Sum = Sum * a ==> 25 * 4 = 100

Sum /= a means
Sum = Sum/ a ==> 100 / 4 = 25

Sum%= a means
Sum= Sum% a ==> 25 % 4 = 1 (Remainder of 25 / 4 is = 1)