← Back to Core Java Course | Chapter 3: Operators | Lesson 6 of 9

Java Assignment Operators

Simple Assignment (=)

The plain = operator evaluates whatever's on its right side and stores that result into the variable named on the left -- it's the only operator that actually performs assignment rather than just computing a value.

Example: Simple Assignment (=)

java
public class Main {
	public static void main(String[] args) {
		int x = 5 + 3; // evaluates the right side, stores into x
		System.out.println(x);
	}
}

Add and Subtract Assignment

+= and -= combine an arithmetic step with the assignment in one token, so count += 5 both adds 5 to count's current value and writes that new total back into count.

Example: Add and Subtract Assignment

java
public class Main {
	public static void main(String[] args) {
		int count = 10;
		count += 5; // adds 5, writes the total back into count
		count -= 3;
		System.out.println(count);
	}
}

Multiply and Divide Assignment

*= and /= work the same way for multiplication and division -- price *= 1.1 applies a 10% increase to price and stores the result back into price itself.

Example: Multiply and Divide Assignment

java
public class Main {
	public static void main(String[] args) {
		double price = 100;
		price *= 1.1; // applies a 10% increase, stores it back
		System.out.println(price);
	}
}

Modulo and Bitwise Assignment

%= computes the remainder of dividing the variable by a value and stores that remainder back into the variable, which is a compact way to keep a counter wrapping within a fixed range.

Example: Modulo and Bitwise Assignment

java
public class Main {
	public static void main(String[] args) {
		int counter = 8;
		counter %= 5; // keeps counter wrapping within a fixed range
		System.out.println(counter);
	}
}

Shift Assignment Operators

<<=, >>=, and >>>= apply a bit shift to a variable and immediately save the shifted result back into it, which is common in low-level code that packs or unpacks multiple values into a single integer.

Example: Shift Assignment Operators

java
public class Main {
	public static void main(String[] args) {
		int packed = 0b0010;
		packed <<= 2; // shifts left, saves result back into packed
		System.out.println(packed);
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.