Chapter 1 |
Operators in Java
An operator is a character that represents an action (e.g. + is an arithmetic operator that represents addition). In general, Java has seven types of operators:
- basic arithmetic operators
- assignment operators
- auto-increment and auto-decrement operators
- logical operators (will be covered in the next chapter)
- comparison (relational) operators (will be covered in the next chapter)
- bitwise operators (will not be covered in this material)
- ternary operator (will not be covered in this material)
1. Basic arithmetic operators
Operator | Meaning | Priority |
- | unary minus (negative values) | highest |
* | multiplication | middle |
/ | division | middle |
% | remainder | middle |
+ | addition | low |
- | subtraction | low |
PS! We can use parentheses ()
to force an evaluation to have a higher priority.
2.Assignment operators
Operator | Example | Equivalent |
= | x = y; | x = y; |
+= | x += y; | x = x + y; |
–= | x –= y; | x = x – y; |
*= | x *= y; | x = x * y; |
/= | x /= y; | x = x / y; |
%= | x %= y; | x = x % y; |
public class AssignmentDemo { public static void main(String args[]) { int num1 = 10; int num2 = 20; num2 = num1; System.out.println("= Output: "+num2); num2 += num1; System.out.println("+= Output: "+num2); num2 -= num1; System.out.println("-= Output: "+num2); num2 *= num1; System.out.println("*= Output: "+num2); num2 /= num1; System.out.println("/= Output: "+num2); num2 %= num1; System.out.println("%= Output: "+num2); } }
3. Auto-increment and auto-decrement operators
Operator | Example | Equivalent |
++ | x++; | x = x + 1; |
-- | x--; | x = x – 1; |
Useful link: Check examples here.
Operator precedence in Java
Just like in Python and math, operator precedence determines which operator needs to be evaluated first if an expression has more than one operator (e.g. is 2+3*4 equal to 20 or 14?). In table below, the operators with higher precedence are at the top and lower precedence at the bottom.
++ -- ! | unary operators |
* / % | multiplicative |
+ – | additive |
> >= < <= | relational |
== != | equality |
&& | logical AND |
|| | logical OR |
= += -= *= /= %= | assignment |
Summary: variables, data types, operators & common errors
Self-assessment
Chapter 1 |