Introduction
Assignment operators help you store values in variables easily. They let you update variables quickly without writing long code.
Assignment operators help you store values in variables easily. They let you update variables quickly without writing long code.
variable = value; variable += value; variable -= value; variable *= value; variable /= value; variable %= value;
The = operator assigns a value to a variable.
Operators like += combine math and assignment in one step.
int x = 5;
x += 3; // same as x = x + 3;
x *= 2; // same as x = x * 2;
x %= 4; // same as x = x % 4;
This program shows how to use different assignment operators to change the value of score. It prints the value after each change.
public class Main { public static void main(String[] args) { int score = 10; System.out.println("Initial score: " + score); score += 5; System.out.println("After adding 5: " + score); score -= 3; System.out.println("After subtracting 3: " + score); score *= 2; System.out.println("After multiplying by 2: " + score); score /= 4; System.out.println("After dividing by 4: " + score); score %= 3; System.out.println("After modulo 3: " + score); } }
Assignment operators make code shorter and easier to read.
Be careful with division and modulo to avoid dividing by zero.
Assignment operators store or update values in variables.
Operators like +=, -=, *= combine math and assignment.
They help write cleaner and shorter code.
+= do in Java?+= operator+= operator adds the right-hand side value to the left-hand side variable.x += y means x = x + y [OK]num by 5 and assign the result back to num?*= multiplies and assigns in one step.num *= 5; which means num = num * 5;.*= for multiply and assign [OK]int a = 10;
a -= 3;
a += 2;
System.out.println(a);
a -= 3;a becomes 7.a += 2;a becomes 9.a, which is 9.int x = 5;
x + = 3;
System.out.println(x);
+= must not have spaces; + = is invalid.x is initialized and semicolons are correct.+ = has a space and is invalid -> Option Ctotal? int total = 20;
int discount = 5;
total -= discount *= 2;
System.out.println(total);
discount *= 2;total -= discount;Pass the test and this pattern moves unknown