Java Arithmetic Assingment Operators
This article is a complementary resource to the Learn Java Basics course.
This article is a complementary resource to the Learn Java Basics course.
Arithmetic assignment operators are shorthand operators in Java that combine arithmetic operations and assignments in a single step.
Suppose you want to increase the value of a variable by 1:
public class Main {
public static void main(String[] args) {
int counter = 10;
counter = counter + 1;
System.out.println(counter); // Output: 11
}
}
This code adds 1 to the value of i and assigns the updated value back to the i variable.
In such cases, you can use arithmetic assignment operators to make the operation clearer and more concise:
public class Main {
public static void main(String[] args) {
int counter = 10;
counter += 1;
System.out.println(counter); // Output: 11
}
}
Here, the +=
operator adds 1 to the variable i
and updates its value.
Java supports arithmetic assignment operators for all standard arithmetic operators. Here's the summary:
Operator | Example | Equivalent To |
---|---|---|
+= |
x += 5 |
x = x + 5 |
-= |
x -= 5 |
x = x - 5 |
*= |
x *= 5 |
x = x * 5 |
/= |
x /= 5 |
x = x / 5 |
%= |
x %= 5 |
x = x % 5 |
Let's see some of these operators in practice.
public class Main {
public static void main(String[] args) {
int total = 20;
total -= 5; // Equivalent to: total = total - 5;
System.out.println(total); // Output: 15
}
}
public class Main {
public static void main(String[] args) {
int value = 50;
value /= 5; // Equivalent to: value = value / 5;
System.out.println(value); // Output: 10
}
}
public class Main {
public static void main(String[] args) {
int number = 29;
number %= 4; // Equivalent to: number = number % 4;
System.out.println(number); // Output: 1
}
}