Core Java Fundamentals ยท Operators
Learn how to assign and modify values of variables using basic and compound assignment operators.
public class AssignmentOperatorsDemo {
public static void main(String[] args) {
// Basic assignment operator =
int num = 10;
System.out.println("Initial value: " + num);
// Add and assign operator +=
num += 5; // equivalent to num = num + 5;
System.out.println("After += 5: " + num);
// Subtract and assign operator -=
num -= 3; // equivalent to num = num - 3;
System.out.println("After -= 3: " + num);
// Multiply and assign operator *=
num *= 2; // equivalent to num = num * 2;
System.out.println("After *= 2: " + num);
// Divide and assign operator /=
num /= 4; // equivalent to num = num / 4;
System.out.println("After /= 4: " + num);
}
}num and use the basic assignment operator = to assign it the value of 10.num (10) is printed to the console.+= (add and assign) operator adds 5 to the current value of num and assigns the result back to num. This is a shorthand for num = num + 5;. The value becomes 10 + 5 = 15.num (15) is printed.-= (subtract and assign) operator subtracts 3 from num and assigns the result back. This is a shorthand for num = num - 3;. The value becomes 15 - 3 = 12.num (12) is printed.*= (multiply and assign) operator multiplies num by 2. This is a shorthand for num = num * 2;. The value becomes 12 * 2 = 24.num (24) is printed./= (divide and assign) operator divides num by 4. This is a shorthand for num = num / 4;. The value becomes 24 / 4 = 6.num (6) is printed.