Introduction
Arithmetic operators help you do math with numbers in your program. They let you add, subtract, multiply, divide, and find remainders easily.
Arithmetic operators help you do math with numbers in your program. They let you add, subtract, multiply, divide, and find remainders easily.
result = value1 + value2; // addition result = value1 - value2; // subtraction result = value1 * value2; // multiplication result = value1 / value2; // division result = value1 % value2; // remainder (modulus)
Use + to add numbers.
Use % to get the remainder after division.
int sum = 5 + 3; // sum is 8
int difference = 10 - 4; // difference is 6
int product = 7 * 2; // product is 14
int quotient = 20 / 5; // quotient is 4 int remainder = 20 % 3; // remainder is 2
This program shows how to use all the basic arithmetic operators with two numbers, 15 and 4. It prints the results of each operation.
public class ArithmeticOperatorsDemo { public static void main(String[] args) { int a = 15; int b = 4; int sum = a + b; int difference = a - b; int product = a * b; int quotient = a / b; int remainder = a % b; 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); } }
Division between two integers gives an integer result, cutting off any decimal part.
Use parentheses () to control the order of operations if needed.
Arithmetic operators let you do basic math in Java.
They include +, -, *, /, and %.
Remember integer division drops decimals.
%.a and b?*.int result = a * b; correctly multiplies a and b.int x = 10; int y = 3; System.out.println(x / y);
x and y are integers, so division drops the decimal part.int a = 5; int b = 0; int c = a / b; System.out.println(c);
a by b, where b is zero.result after execution?int a = 15; int b = 4; int result = a / b + a % b * 2;
Pass the test and this pattern moves unknown