Java Operators
Java Operators
o Java Expressions
o Java Operators
o Arithmetic Operators
o Increment and Decrement Operators
o Assignment Operators
o Relational Operators
o Logical Operators
o Operator Precedence
o Exercise in Operators
Java Expressions
• An expression produces a result and returns a value.
• Purposes of expressions:
• to compute values
• to assign values to variables
• to control the flow of execution
Examples:
x = 5;
y = x;
z = x * y;
Java Operators
• Operators are special symbols that perform specific operations on one, two,
or three operands, and then return a result.
x = 6; // assign 6 to x
y = 4; // assign 4 to y
x = x + 2; // x is equal to 8
y = y - 3; // y is equal to 1
z = x * y; // z is equal to 8
z = x / y; // z is equal to 8
z = x % y; // z is equal to 0
Increment and Decrement
Operators
++ Pre/Post-Increment
-- Pre/Post-Decrement
if num = 5
z = num++ // z = 5
z = ++num // z = 6
Assignment Operators
= Assignment
+= Addition
-= Subtraction
a = 8; *= Multiplication
/= Division
b = 12;
%= Remainder
c = 3;
d = 15;
b += 1; // same as (b=b+1)
a -= 2; // same as (a=a-2)
c *= 2; // same as (c=c*2)
d /= 5; // same as (d=d/5)
Relational Operators
Expression Result
== Equal to
< Less than
3+4 == 7 true
> Greater than
<= Less than or equal to 3+4 != 7 false
>= Greater than or equal to 3+4 != 2+6 true
!= Not equal to
3+4 < 10 true
3+4 <= 10 true
3+4 == 4+4 false
3+4 >= 7 true
3+4 >= 8 false
Logical Operators
&& AND
|| OR
^ Exclusive-OR
! NOT
Assume: m=10
a. 3 – 2 + 5 + 6 – 1 = _______
b. 4 * (5 + 4) / 2 = _______
c. 5 % 2 + (2 * 8) = _______
d. !((((m-2)*4)+15 / 5) == (15%3)*7)) result = _______
e. !(m == 10) && (m+3 == 13) result = _______
1. x = a + b * c / d – a
2. x = a % 2 + c * a * b – b / d
3. x = (a * b * (a + (c * d * (c * b / (d) ) ) ) )
4. x = ! ((a == b) || (b != d))
5. x = (b == a) && (b < d)
6. x = a < b + c || c – b > d
7. x = !(!(a==b) && (a + b * c / d – a > a % 2 + c * a * b – b / d))
8. x = !( (a * b * (a + (c * d * (c * b / (d) ) ) ) == a + b * c / d))
9. ! ( a % 2 >= c)
10. ! (a + b * c / d – a == 1) && ! (T)