In Java, arithmetic operators allow you to perform mathematical operations. Here are some common arithmetic operators:
+
Addition: Adds two values together./
Division: Divides one value by another.%
Modulus: Returns the remainder of a division.Let's look at an example that demonstrates the usage of arithmetic operators:
public class ArithmeticOperators{
public static void main(String[] args) {
int a = 10;
int b = 4;
int sum = a + b; // Sum: 14
int difference = a - b; // Difference: 6
int product = a * b; // Product: 40
int quotient = a / b; // Quotient: 2
int remainder = a % b; // Remainder: 2
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
System.out.println("Quotient: " + quotient);
System.out.println("Remainder: " + remainder);
}
}
a
and b
and store the results in separate variables.public class AssignmentOperators{
public static void main(String[] args) {
int x = 5;
int y = 10;
x += 3; // Equivalent to x = x + 3 -> x: 8
y *= 2; // Equivalent to y = y * 2 -> y: 20
System.out.println("x: " + x);
System.out.println("y: " + y);
}
}