Arithmetic Operators in Java
Arithmetic operators in Java perform basic mathematical operations such as addition, subtraction, multiplication, division, and modulus.
Addition (+)
The + operator adds two numbers. It also concatenates strings when used with string operands.
public class ArithmeticExample {
public static void main(String[] args) {
int x = 7;
int y = 3;
System.out.println("Sum: " + (x + y));
String greeting = "Hello";
String target = "Java";
System.out.println("Message: " + greeting + " " + target);
}
}
Subtraction (-)
The - operator subtracts the right operand from the left.
public class ArithmeticExample {
public static void main(String[] args) {
int num1 = 15;
int num2 = 4;
System.out.println("Difference: " + (num1 - num2));
}
}
Multiplication (*)
The * operator multiplies two values.
public class ArithmeticExample {
public static void main(String[] args) {
int factorA = 6;
int factorB = 8;
System.out.println("Product: " + (factorA * factorB));
}
}
Division (/)
The / operator divides the left operand by the right. Dividing by zero throws an ArithmeticException.
public class ArithmeticExample {
public static void main(String[] args) {
int dividend = 20;
int divisor = 4;
System.out.println("Quotient: " + (dividend / divisor));
try {
int result = dividend / 0;
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero");
}
}
}
Modulus (%)
The % operator returns the remainder of a division operation. Like division, using zero as the divisor causes an ArithmeticException.
public class ArithmeticExample {
public static void main(String[] args) {
int value = 17;
int modBase = 5;
System.out.println("Remainder: " + (value % modBase));
try {
int remainder = value % 0;
} catch (ArithmeticException e) {
System.out.println("Error: Modulo by zero");
}
}
}```