Operators

Operators are used to perform certain operations on variables and values. For example, addition (+) and subtraction (-) are both operators.

Java offers a number of different operators for different data types. Based on their functions, we can divide operators into the following categories:

  • Arithmetic operators
  • Assignment operator
  • Compound assignment operators
  • Increment and decrement operator
  • Relational operators
  • Logical operators

Let’s discuss them one by one.

Arithmetic operators

These are the kind of operators that we use in simple mathematical equations involving integers and decimal numbers. We will go into the details about these operators in the next lesson. For now, the following table summarizes different arithmetic operators.

Operator Function Example
+ Addition 9 + 2 results in 11
- Subtraction 9 - 2 results in 7
* Multiplication 9 * 2 results in 18
/ Division 9 / 2 results in 4
% Remainder from division 9 % 2 results in 1

Assignment operator

You have already seen this operator. This operator is used to assign a value to a variable. It is represented using the “equal to” sign, i.e., =.

Compound assignment operators

We use compound assignment operators as a shorthand for an arithmetic operator and assignment operator’s combined effect. Adding = next to each arithmetic operator gives us the corresponding compound assignment operators. We will look at some examples in an upcoming lesson.

Increment and decrement operator

As a shorthand for adding or subtracting 11 from a variable, we have two specialized operators:

  • Increment operator: ++
  • Decrement operator: --

The ++ operator, when added next to the variable, results in the addition of 11 in that variable. The -- operator, however, results in the subtraction of 11. We’ll look at some examples in a lesson ahead.

Relational operators

To compare two numbers, integer or decimal, we have relational operators in mathematics. We have the same operators in Java as well. Again, we will see the details and examples ahead. But for now, have a look at the following table for a quick overview.

Operator Function Example
> Greater than 9 > 2 evaluates to true
< Less than 9 < 2 evaluates to false
>= Greater than or equal to 9 >= 9 evaluates to true
<= Less than or equal to 9 <= 10 evaluates to true
== Equal to 9 == 9 evaluates to true
!= Not equal to 9 != 9 evaluates to false

Logical operators

Remember that we have logical operators for boolean algebra, such as AND, OR, etc. We have all these operators in Java as well. We’ll again see examples and more detail in a lesson ahead. For now, refer to the following table for a quick overview of a couple of logical operators.

Operator Function Example
&& Conditional AND true && false evaluates to false
\|\| Conditional OR true \|\| false evaluates to true
! Conditional NOT !true evaluates to false

Get hands-on with 1200+ tech skills courses.