0
0
Javaprogramming~5 mins

Assignment operators in Java

Choose your learning style9 modes available
Introduction

Assignment operators help you store values in variables easily. They let you update variables quickly without writing long code.

When you want to save a value into a variable.
When you want to add or subtract a number from a variable's current value.
When you want to multiply or divide a variable by a number and save the result.
When you want to combine assignment with a math operation in one step.
When you want to update a variable based on its current value.
Syntax
Java
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.

Examples
Assign 5 to variable x.
Java
int x = 5;
Add 3 to x and save the result back to x.
Java
x += 3;  // same as x = x + 3;
Multiply x by 2 and save the result back to x.
Java
x *= 2;  // same as x = x * 2;
Set x to the remainder when x is divided by 4.
Java
x %= 4;  // same as x = x % 4;
Sample Program

This program shows how to use different assignment operators to change the value of score. It prints the value after each change.

Java
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);
    }
}
OutputSuccess
Important Notes

Assignment operators make code shorter and easier to read.

Be careful with division and modulo to avoid dividing by zero.

Summary

Assignment operators store or update values in variables.

Operators like +=, -=, *= combine math and assignment.

They help write cleaner and shorter code.