Java Assignment Operators
In this page:
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 (=)
public class Main {
public static void main(String[] args) {
int x = 5 + 3; // evaluates the right side, stores into x
System.out.println(x);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: