OOP Lec 4
OOP Lec 4
OOP Lec 4
Java Operators
• Operator in Java is a symbol that is used to perform operations.
• For example:
• +,
• -,
• *,
• / etc.
Java Operators
• Operators are used to perform
operations on variables
• Although the + operator is often used to add
and values.
• In the example below, we use together two values, like in the example
the + operator to add together above, it can also be used to add together a
two values variable and a value, or a variable and another
variable:
public class Main {
public static void main(String[] args) { Example
int x = 100 + 50; int sum1 = 100 + 50; // 150 (100 + 50)
System.out.println(x); int sum2 = sum1 + 250; // 400 (150 + 250)
} int sum3 = sum2 + sum2; // 800 (400 + 400)
}
Types of operators
Java divides the operators into the following groups:
1. Arithmetic operators
2. Unary operators
3. Assignment operators
4. Comparison operators/Relational Operators
5. Logical operators
6. Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical
operations.
Operator Name Description Example
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
Java Comparison Operators
• Comparison operators are used to compare two values (or
variables).
• This is important in programming, because it helps us to find
answers and make decisions.
• The return value of a comparison is either true or false.
• These values are known as Boolean values, and you will learn
more about them in the Booleans and If..Else chapter.
• In the following example, we use the greater than operator
(>) to find out if 5 is greater than 3
Example
int x = 5; int y = 3;
System.out.println(x > y); //
returns true, because 5 is higher
than 3
A simple example
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x > y);
// returns true, because 5 is higher than 3
}
}
Comparison of Relational Operators
Operator Name Example
== Equal to x == y
!= Not equal x != y
! Logical Reverse the result, returns false !(x < 5 && x < 10)
NOT if the result is true
Truth Tables of Logical operators
LOGICAL OR LOGICAL AND
1 1 1
1 1 1
1 0 1 1 0 0
0 1 1 0 1 0
0 0 0 0 0 0
A simple program of Logical Operators
class Test {
public static void main(String[] args) {
int x = 5;
System.out.println(x > 3 && x < 10);
// returns true because 5 is greater than 3 AND 5 is less than 10
System.out.println(x > 3 || x < 4);
// returns true because one of the conditions are true (5 is greater than 3, but 5 is not less than 4)
System.out.println(!(x > 3 && x < 10));
// returns false because ! (not) is used to reverse the result
}
}
Exercises
• Write programs on all operators and take values at runtime.