In this tutorial, we are going to talk about operators in Java. Simply put, an operator is a special symbol we can apply to a set of variables, values, or literals and returns a result.
Additionally, we use them to perform different operations on variables and values. For example, if we would like to sum two numerical values, we would use the addition operator (+).
Furthermore, in Java, we distinguish three different operator types: unary, binary, and ternary. Additionally, we can assign them to one, two, or three operands, respectively.
1. Order of Operator Precedence
Before we dive in, let us see how operators are evaluated. In the real world, arithmetic operators (in math) are evaluated from left-to-right order – unless overridden with parentheses. However, the same rule applies in Java.
Java operators follow the order of operation. Furthermore, if two operators have the same level of precedence, then Java guarantees left-to-right evaluation.
Operator |
Symbol |
Post-unary operator |
expression++, expression– |
Pre-unary operator |
++expression, –expression |
Other unary operators |
+, -, ! |
Multiplication, division, modulus |
*, /, % |
Addition, subtraction |
+, – |
Relational operators |
<, >, <=, >=, instanceof |
Equal to, not equal to |
==, != |
Logical operators |
&, ^, | |
Short-circuit operators |
&&, || |
Ternary operator |
boolean expression ? expression1 : expression2 |
Assignment operators |
=, +=, -=, *=, /=, %= |
2. Unary Operators
Now, let us see what unary operators are. By definition, a unary operator is one that requires exactly one operand (variable). To put it differently, we use these operators on a single variable.
Operator |
Description |
++ |
Increases value by 1. |
— |
Decreases value by 1. |
! |
Changes boolean value. |
– |
Indicates a literal number is negative or negates an expression. |
+ |
Indicates a number is positive. In Java, all numbers are assumed to be positive by default. |
2.1. Increment and Decrement Operators
We can use increment (++) and decrement (–) operators with numeric operands and have the highest order of precedence. In other words, they are often applied first to an expression.
It is important to note these operators require special care – the order they are applied to their associated operands can make a difference in how an expression is processed.
If the operator (++ or –) is placed before the operand (++expression or –expression) we are talking about the pre-unary operators. Similarly, if it is placed after the operand (expression++ or expression–) then it is the post-unary operator.
Furthermore, with pre-increment and pre-decrement operators, the operator is applied first and the value return is a new value of the expression.
int x = 5; int y = ++x;
In the example above, the value of the y variable will be 6. The value of the variable x will increase by 1 and the new result will be stored in the y variable.
Alternatively, if the operator is placed after the operand, referred to as the post-increment operator and the post-decrement operator, then the original value of the expression is returned, with the operator applied after the value is returned.
int x = 5; int y = x++;
Here, unlike in the previous example, the value of the y variable will be 5. The post-increment operator returns the original value (5) as the result and then increases the value by 1.
Additionally, let us see a more complex example:
int x = 5; int y = --x * 2 / x++ + --x; System.out.println("x is " + x); System.out.println("y is " + y);
After the code executes the x will be 4 and y will be 6. Let us explain why.
At the beginning, the value of the variable x is 5. Now, it is important to keep in mind the order of operator precedence. Post-unary and pre-unary operators have the highest order of precedence and will be executed first if not overridden by parentheses.
We can simplify the expression to get the value of y:
int y = 4 (x decresed by 1) * 2 / 4 (return x and then the value increses to 5) + 4 (x is 5, but the value decreses and returns) int y = 4 * 2 / 4 + 4
Secondly, the multiplicative operators will execute before the additive operators:
int y = 8 / 4 + 4 = 2 + 4 = 6
Finally, we got the final value of y which is 6. The x variable has a value of 4.
3. Binary Operators
Additionally, we use binary operators when:
- performing arithmetical operations on variables
- creating logical expression
- assigning values to variables
3.1. Arithmetic Operators
They encountered in early mathematics and include addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).
Operator |
Symbol |
Multiplication |
* |
Division |
/ |
Modulus |
% |
Addition |
+ |
Subtraction |
– |
int x = 10; int y = 3; int sum = x + y; // 13 int difference = x - y; // 7 int product = x * y; // 30 int quotient = x / y; // 3 int remainder = x % y; // 1
However, we can use arithmetic operators within any primitive data type (except boolean).
3.2. Relational Operators
Let us move to relational operators. They compare two expressions and return a boolean value. Additionally, the result can be either true or false.
Furthermore, we often use them in conditional statements and loops to make decisions based on the result of comparisons.
Operator |
Description |
< |
Strictly less than |
<= |
Less than or equal to |
> |
Strictly greater than |
>= |
Greater than or equal to |
However, the relational operators from the table above can be only applied to numeric primitive data types.
int a = 5; int b = 7; boolean isLessThan = (a < b); // true boolean isGreaterThan = (a > b); // false
3.3. Equality Operators
Determining equality in Java can be tricky. There is a difference between “two objects are the same” and “two objects are equivalent“. Furthermore, complications arise since there is no such distinction between primitive data types.
However, let us start with the basics – the equals (==) and not equals (!=) operators.
Operator |
Symbol |
equals to |
== |
not equals to |
!= |
Additionally, they compare two values and return a boolean value.
Moreover, the equality operators are used when comparing:
- Two numeric primitive types. If the numeric values are of different data types, the values are automatically promoted as previously described. For example, 5 == 5.00 returns true since the left side is promoted to a double.
- Two boolean values.
- Two objects, including null and String values.
int a = 5; int b = 7; boolean isEqual = (a == b); // false boolean isNotEqual = (a != b); // true
3.4. Logical Operators
Next, we use logical operators to perform logical operations on boolean values. They allow us to combine or manipulate boolean values to make decisions in our code.
Furthermore, we can use logical operators on both, numerical and boolean data types. When we use them within numerical types, we call them bitwise operators. Additionally, when we use them with logical (boolean) data types, we call them logical operators.
Java has three main logical operators:
Operator |
Symbol |
Description |
AND |
&, && |
Returns true if both operands are true. |
OR |
|, || |
Returns true if at least one of the operands is true. |
NOT |
! |
Inverts the boolean value of the operand. |
For example:
boolean isJavaFun = true; boolean isLearning = true; boolean bothAreTrue = isJavaFun && isLearning; // true boolean eitherIsTrue = isJavaFun || isLearning; // true boolean isNotFun = !isJavaFun; // false
The && and the || are conditional operators and are also known as short-circuit operators. Java will evaluate the right side of the expression only if the result cannot be determined with the left side of the expression:
boolean isJavaFun = true; boolean isLearning = false; boolean eitherIsTrue = isJavaFun || isLearning; // true
From the example, we use the || operator that returns true if one of the operands is true. Since the isJavaFun variable returns true, there is no need to check the value of the isLearning variable – we already know the result of the expression will return true.
Moreover, let us try another example:
boolean isJavaFun = false; boolean isLearning = true; boolean eitherIsTrue = isJavaFun || isLearning; // true
Here, the isJavaFun variable returns false. Thus, we need to evaluate the isLearning variable as well to determine the result.
4. Assignment Operator
We already use the assignment operator within our previous code snippets. Furthermore, it is the most commonly used operator.
Moreover, we use it when we want to assign a value to a variable:
int x = 10; int y = 5; x = y; // x now holds the value 5
Furthermore, it can be used in combination with arithmetical operators:
int x = 10; int y = 5; y += 10; // y = y + 10
5. Ternary Operator
The last operator we are going to discuss is the ternary operator. It differs from other operators. Furthermore, it is a conditional operator and it is the only operator that takes three operands.
booleanExpression ? expression1 : expression2
Moreover, the first operand must be a boolean expression, and the second and third can be any expression that returns a value.
int y = 10; int x = (y == 10) ? 2 : 3;
However, let us translate the code snippet. If y is equal to 10, then the value 2 will be assigned to the x variable, otherwise, the x will be 3.
What’s more, the data types of expression1 and expression2 do not have to be the same. It is important to be the same if we want to save the result in the variable:
String animal = "Dog"; System.out.println(animal.equals("Dog") ? "Wuf" : false);
If the value of the animal variable is “Dog”, we will write “Wuf” in the console. If it is not equal, we will simply write false.
However, if we would like to store the result in the variable, we will encounter the compiler error:
String result = animal.equals("Dog") ? "Wuf" : false;
Thus, we cannot store the boolean value in a variable of String type.
6. Key Takeaways
In this tutorial, we covered the operators in Java.
To sum up, operators are an integral part of Java programming, enabling you to perform a wide range of tasks efficiently and effectively. By understanding and mastering these operators, you’ll have the foundation to write more complex and sophisticated Java programs.
Stay tuned for future blog posts where we’ll dive deeper into each category of operators, exploring their nuances and practical applications in Java programming.