3.1 Operator Basics
Symbols used to process and calculate data in a program are called Operators. Java provides various operators for mathematical calculations, logical judgments, and more.
1. Operators and Operands
- Operator: A symbol that performs an operation (e.g.,
+,-,*,/) - Operand: The target of the operator's work (variables, constants, literals, expressions)
int result = x + 3;
// Operators: = , +
// Operands: result, x, 3
After an operator performs an operation with its operands, it always returns a 'result value'.
2. Types of Operators
Java's operators can be broadly classified into four major categories.
- Arithmetic Operators: Four basic arithmetic operations (
+,-,*,/) and the remainder operation (%) - Comparison Operators: Comparing for greater, smaller, or equal (
>,<,>=,<=,==,!=) - Logical Operators: Determining logical conditions like AND, OR, NOT (
&&,||,!) - Assignment Operators: Storing the value on the right side into the left side (
=,+=,-=)
In addition, there are operators for special purposes such as bitwise operators and the conditional operator (ternary operator).
3. Operator Precedence and Associativity
When an expression is complex, rules exist to determine which operation is performed first. It is similar to the general order of calculations in mathematics.
- Arithmetic > Comparison > Logical > Assignment: Assignment is performed last.
- Unary > Binary > Ternary: Operators with fewer operands take precedence in the processing of the expression.
- Operations inside parentheses
()are performed with the highest priority.
If you are confused about precedence, do not hesitate to explicitly specify the precedence using parentheses (). It forms a good coding habit that improves readability and reduces bugs.