1 min read

Java Number Operators

The number operators are pretty standard across programming languages.
Java Number Operators

Number Operators

Java supports addition, subtraction, multiplication, division, and modulus operators.

Addition

Addition is written using the + operator. This is used to add two numbers.

final var number = 2 + 3;  // 5

Subtraction

Subtraction is written with the - operator. This is used to subtract a number from another.

final var number = 5 - 2;  // 3

Multiplication

Multiplication is written with the * operator. This is used to multiply two numbers.

final var number = 3 * 3;  // 9

Division

Division is written with the / operator. This is used to divide a number by another number.

final var number = 10 / 3;  // 3

When working with division, you only get how many times the number is divided by another number. If you need the remainder, you use modulus instead.

Modulus

Modulus is written with the % operator. This is used to find the remainder of a division operation.

final var number = 10 / 3;  // 1

Number Assignment Operators

Assigning a new value using an existing variable value can be done with the following:

int x = 0;

// x = 3
x = x + 3;

Number assignment operators are used to provide a shorthand assignment to a variable. Using assignment operators, this can be shortened with the following:

int x = 0;

// x = 3
x += 3;

This can be used with any of the operators shown above.

Incrementing and Decrementing

You can increment and decrement number variables with the following.

int x = 0;

// increment
x += 1;
x = x + 1;

// decrement
x -= 1;
x = x - 1;

Incrementing and decrementing are common operations, so Java has built-in operators to simplify those operations. Java has the increment operator (++) and the decrement operator (--).

int x = 0;

// increment x by 1
x++;

// decrement x by 1
x--;

Conclusion

Java number operators are pretty standard and follow the same general order of operations as well.