Skip to content

Mathematical - Relational Operators

Estimated time to read: 2 minutes

Assignment Operator

inti i, j;

i = 42; // i takes the value of 42
j = 21; // j takes the value of 21
i = 21; // old value overwritten. i now takes the value of 21
i = i + j; // i takes the value of 42, i + j, 21 + 21

Mathematical Operators

Java's mathematical operators are fairly standard.

  • (+) Addition*
  • (-) Subtraction*
  • (*) Multiplication
  • (/) Divison
  • (%) Modulus (for whole numbers)

*There are also unary versions of + and -

Precedence of binary operators, named as such because they take in two values; one on the left and one on the right, is:

Multiply, divide, modulo, add, subtract

BODMAS - Yay.

Unary Operators

Java has prefix and postfix increment and decrement operators

Prefix

Prefix increment (++i) increments i by 1 and the uses it in the expression. Prefix decrement (--i) decrement i by 1 and the uses it in the expression.

Postfix

Postfix increment (i++) uses i in the expression and the increments it by 1. Postfix decrement (i--) uses i in the expression and then decrements it by 1.

Example of usage

Using i as an array index. Do you want to:

Increment the array index first, then use the incremented value. ++i

Or use the value first and then increment if for a subsequent use. i++

Relational Operators

Java has the following relational operators:

Relational Operator Example Comparison meaning
< a < b a is less than b
<= a <= b a is less than or equal to b
== a == b a is equal to be
!= a != b a is not equal to b
>= a >= b a is greater than or equal to b
> a > b a is greater than b

The operators result in a boolean value (true / false) which is normally used in branching or looping statements.