Java Arithmetic Operators
In Java, arithmetic operators are used to perform a variety of common mathematical operations.
The arithmetic operators include, addition, subtraction, multiplication, division, and remainder.
The following table showcases the arithmetic operators in Java:
Operator | Name | Description | Example |
+ | Addition | Adds two values | a + b |
– | Subtraction | Subtracts one value from another | a – b |
* | Multiplication | Multiplies two values | a * b |
/ | Division | Divides one value by another | a / b |
% | Remainder | Remainder of a division operation. Sometimes called ‘modulo’ | a % b |
Sometimes, unary operators like increment ‘++‘ and decrement ‘—‘ are included in the arithmetic operators, but the Java literature differentiates them, so we do here as well.
The Addition Operator
The arithmetic operator adds two values together, and uses the plus ‘+‘ symbol. The operands may be numbers, or they may be variables that store numeric types.
Here’s an example of the addition operator:
int sum = 5 + 10; // sum is 15
The Subtraction Operator
The subtraction operator subtracts the second value from the first, and it uses the minus ‘–‘ symbol.
Here’s an example of the subtraction operator:
int diff = 12 - 5; // diff is 7
The Multiplication Operator
The multiplication operator multiplies two numbers together, producing the product. It uses the asterisk ‘*’ symbol.
int product = 11 * 5; // product is 55
The Division Operator
The division operator is used to divide one number from another, and it uses the forward-slash ‘/’ symbol.
int quotient = 12 / 3; // quotient is 4
The Remainder Operator
The remainder operator produces the remainder of a division operator and is commonly called ‘modulus‘. It uses the percent ‘%‘ symbol.
int remainder = 13 % 3; // remainder is 3
In the above example, we are evaluating the expression ’13 % 3′. The result of 13 divided by 3 is: two, with a remainder of 3. This means that the result of the remainder operation is 3.