Arithmetic Operators
Arithmetic operators are the foundation of mathematical processing in Java. They allow you to perform common mathematical operations like addition, subtraction, multiplication, division, and finding the remainder.
Basic Arithmetic Operators
Java provides five basic arithmetic operators:
| Operator | Name | Description | Example |
|---|---|---|---|
+ |
Addition | Adds two values | x + y |
- |
Subtraction | Subtracts one value from another | x - y |
* |
Multiplication | Multiplies two values | x * y |
/ |
Division | Divides one value by another | x / y |
% |
Modulo | Returns the division remainder | x % y |
Click Run to execute your code
Integer vs. Floating-Point Division
It's crucial to understand how division works depending on the operand types.
- Integer Division: If both operands are integers (e.g.,
int), the result is an integer. Any decimal part is truncated (thrown away), not rounded.
Example:5 / 2equals2(not 2.5). - Floating-Point Division: If at least one operand is a
floating-point type (e.g.,
doubleorfloat), the result is a floating-point number.
Example:5.0 / 2equals2.5.
The Modulo Operator (%)
The modulo operator returns the remainder of a division operation. It's incredibly useful for checking if a number is even or odd, or for cycling through values.
int remainder = 10 % 3; // Result is 1 (10 / 3 = 3 with remainder 1)
int isEven = 4 % 2; // Result is 0 (4 divides perfectly by 2)
Increment and Decrement
Java provides shortcut operators to increase or decrease a variable's value by 1.
| Operator | Description | Example (assume x = 5) |
|---|---|---|
++x (Prefix) |
Increments x, then uses the new value | int y = ++x; (x is 6, y is 6) |
x++ (Postfix) |
Uses the current value of x, then increments it | int y = x++; (y is 5, x is 6) |
--x (Prefix) |
Decrements x, then uses the new value | int y = --x; (x is 4, y is 4) |
x-- (Postfix) |
Uses the current value of x, then decrements it | int y = x--; (y is 5, x is 4) |
Summary
- Math operations work as expected:
+,-,*. - Division
/truncates decimals if both numbers are integers. - Modulo
%gives the remainder. ++and--are shortcuts for adding/subtracting 1.- Be careful with postfix vs. prefix increment when using the result in an expression.
Enjoying these tutorials?