Overview of Operators in Java
Introduction to Java Operators
Previously, we've gained insights into conditionals and booleans, and saw a limited usage of mostly relational(comparison) operators.
Now, we'll delve deeper into the vast world of Java operators. Crucially, these elements are responsible for data manipulation and calculations and serve as the foundation for constructing complex expressions.
We'll introduce you to the various types, showcase their mechanics, and provide examples to ensure a comprehensive understanding of their application. Let's start things off with a bit of arithmetic.
Arithmetic Operators
You've probably done basic arithmetic, and find these operators quite familiar. They're used to perform essential mathematical operations such as addition, subtraction, multiplication, division, and modulo.
Let's dive into an elaborate example to see these operators in action and understand how they can be applied.
class Main {
public static void main(String[] args) {
int num1 = 10; // Declare and initialize num1
int num2 = 5; // Declare and initialize num2
// Perform various arithmetic operations
int sum = num1 + num2;
int difference = num1 - num2;
int product = num1 * num2;
int quotient = num1 / num2;
int remainder = num1 % num2;
// Print the results with explanations
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
System.out.println("The difference between " + num1 + " and " + num2 + " is: " + difference);
System.out.println("The product of " + num1 + " and " + num2 + " is: " + product);
System.out.println("The quotient of " + num1 + " and " + num2 + " is: " + quotient);
System.out.println("The remainder of " + num1 + " divided by " + num2 + " is: " + remainder);
}
}
/*
Output:
The sum of 10 and 5 is: 15
The difference between 10 and 5 is: 5
The product of 10 and 5 is: 50
The quotient of 10 and 5 is: 2
The remainder of 10 divided by 5 is: 0
*/
As you can see, we performed operations on two integer variables and printed out the results with explanatory messages for clarity. Also, keep in mind that when we use the division operator with integers, the result will be truncated. To obtain a precise result, opt for floating-point numbers instead.
Assignment Operators
More or less, we used the assignment operators in multiple examples in the Java Basics series. Simply put, we utilize them to assign values to variables. They come in various flavors, including = (assignment), += (addition assignment), -= (subtraction assignment), *= (multiplication assignment), /= (division assignment), and %= (modulus assignment).
To clarify this hefty listing, we'll demonstrate their individual effects in an all-encapsulating, neat example.
class Main {
public static void main(String[] args) {
int num1 = 10; // Declare and initialize num1
int num2 = 5; // Declare and initialize num2
// Use various assignment operators
int result1 = num1 += num2;
int result2 = num1 -= num2;
int result3 = num1 *= num2;
int result4 = num1 /= num2;
int result5 = num1 %= num2;
// Print the results with explanations
System.out.println("The value of num1 after using addition assignment is: " + result1);
System.out.println("The value of num1 after using subtraction assignment is: " + result2);
System.out.println("The value of num1 after using multiplication assignment is: " + result3);
System.out.println("The value of num1 after using division assignment is: " + result4);
System.out.println("The value of num1 after using modulus assignment is: " + result5);
}
}
/*
Output:
The value of num1 after using addition assignment is: 15
The value of num1 after using subtraction assignment is: 10
The value of num1 after using multiplication assignment is: 50
The value of num1 after using division assignment is: 10
The value of num1 after using modulus assignment is: 0
*/
While assignment operators offer concise syntax and performance optimization, we should consider a few key caveats.
Pay attention to the order of evaluation, as it can impact your results. Also, be cautious with type coercion when working with operands of different types to avoid unexpected outcomes or loss of precision.
Lastly, remember that some objects, like String
objects for instance, are immutable. Using assignment operators with such objects can create new instances rather than modifying the original, which might lead to performance issues if not managed well.
Relational Operators
Relational operators, also known as comparison operators, allow us to compare two values in Java. As we can see in the example below, they come in several forms: == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to).
class Main {
public static void main(String[] args) {
int num1 = 10; // Declare and initialize num1
int num2 = 5; // Declare and initialize num2
// Use various relational operators
boolean result1 = num1 == num2;
boolean result2 = num1 != num2;
boolean result3 = num1 > num2;
boolean result4 = num1 < num2;
boolean result5 = num1 >= num2;
boolean result6 = num1 <= num2;
// Print the results with explanations
System.out.println("Is num1 equal to num2? " + result1);
System.out.println("Is num1 not equal to num2? " + result2);
System.out.println("Is num1 greater than num2? " + result3);
System.out.println("Is num1 less than num2? " + result4);
System.out.println("Is num1 greater than or equal to num2? " + result5);
System.out.println("Is num1 less than or equal to num2? " + result6);
}
}
/*
Output:
Is num1 equal to num2? false
Is num1 not equal to num2? true
Is num1 greater than num2? true
Is num1 less than num2? false
Is num1 greater than or equal to num2? true
Is num1 less than or equal to num2? false
*/
We should note that in the case of objects, the comparison evaluates the memory address, not the content. When comparing objects, you should use methods like equals()
to compare their contents appropriately.
Logical Operators
With these operators, we can combine multiple conditions, and introduce more complex decision-making in our codebases. You might already be familiar with the three common ones: && (AND), || (OR), and ! (NOT).
class Main {
public static void main(String[] args) {
int num1 = 10; // Declare and initialize num1
int num2 = 5; // Declare and initialize num2
int num3 = 7; // Declare and initialize num3
// Use logical operators to combine conditions
boolean result1 = (num1 > num2) && (num1 > num3);
boolean result2 = (num1 > num2) || (num1 < num3);
boolean result3 = !(num1 == num2);
// Print the results with explanations
System.out.println("Is num1 greater than num2 AND num3? " + result1);
System.out.println("Is num1 greater than num2 OR less than num3? " + result2);
System.out.println("Is num1 NOT equal to num2? " + result3);
}
}
/*
Output:
Is num1 greater than num2 AND num3? true
Is num1 greater than num2 OR less than num3? true
Is num1 NOT equal to num2? true
*/
When working with logical operators, remember that they use short-circuit evaluation. In the case of the logical AND &&, if the left operand is false
, the right operand won't be evaluated since the result will always be false. Similarly, for the logical OR ||, if the left operand is true
, the right operand won't be evaluated as the result is guaranteed to be true.
Bitwise Operators
When the need for manipulating individual bits of data values arises, we leverage bitwise operators. These nifty operators are & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), and >> (right shift).
Bitwise operators find their place in low-level programming tasks such as encryption, compression, and hardware control. However, as a beginner, you should only focus on being aware of them, as a basis that you'll update later on in your learning path.
Still curious? Feel free to find out more here
Unary Operators
Unary operators work with a single operand and are quite handy for a variety of tasks in Java. Among them, you'll find ++ (increment), -- (decrement), + (positive), - (negative), and ! (logical NOT).
class Main {
public static void main(String[] args) {
int num1 = 10; // Declare and initialize num1
int num2 = -5; // Declare and initialize num2
boolean result1 = true; // Declare and initialize result1
boolean result2 = false; // Declare and initialize result2
// Perform unary operations
num1++;
num2--;
result1 = !result1;
result2 = !result2;
// Print the results with explanations
System.out.println("The value of num1 after incrementing by 1 is: " + num1);
System.out.println("The value of num2 after decrementing by 1 is: " + num2);
System.out.println("The negation of result1 is: " + result1);
System.out.println("The negation of result2 is: " + result2);
}
}
/*
Output:
The value of num1 after incrementing by 1 is: 11
The value of num2 after decrementing by 1 is: -6
The negation of result1 is: false
The negation of result2 is: true
*/
Bear in mind that the increment (++) and decrement (--) operators have two forms: pre-increment/decrement (e.g., ++num) and post-increment/decrement (e.g., num++). These forms can yield different results in certain contexts, so be cautious when using them.
Precedence and Associativity
The evaluation order of operators within an expression is governed by their precedence and associativity. An operator with higher precedence is evaluated before those with lower. When operators share the same precedence level, their associativity determines the evaluation order. Understanding operator precedence and associativity are key to accurately interpreting expressions and obtaining the desired results.
Precedence | Operators |
---|---|
postfix | expr++, expr-- |
unary | ++expr, --expr, +expr, -expr, ~, ! |
multiplicative | *, /, % |
additive | +, - |
shift | <<, >>, >>> |
relational | <, >, <=, >=, instanceof |
equality | ==, != |
bitwise AND | & |
bitwise exclusive OR | ^ |
bitwise inclusive OR | |
logical AND | && |
logical OR | |
ternary | ?: |
assignment | =, +=, -=, *=, /=, %=, &=, ^=, |
Generally speaking, it's a good practice to use parentheses to explicitly specify the order of evaluation in complex expressions.
Summary
So far, we've provided a comprehensive overview of the broadly-defined six types of operators. We've examined their syntax and functionality, with examples to showcase their use. Additionally, we've discussed the importance of operator precedence and associativity in determining the evaluation order of expressions.
As you continue to explore the language, remember to check out the available resources and documentation found below.
Useful Resources
Understanding the Boolean Data Type in Java
Conditional Statements in Java