Operators
Primitives
Equal to: ==
Not Equal to: !=
Arithmetic
Greater than: >
Less than: >
Greater than or equal to: >=
Less than or equal to: <=
All operators give a true or False value
Operators SHOULD NOT be used on String. String comparisons should be done using .equal or .compareTo
This is because
In Java, strings should not be compared using the == operator because it checks for reference equality, not content equality.
When you use == with objects (including strings), it checks if the references to the objects are the same. In other words, it checks if they point to the same location in the memory.
String literals in Java are stored in a special memory area called the "String Pool". When you create a string literal, Java checks if a string with the same content already exists in the pool. If it does, it returns a reference to that existing string; if not, it creates a new string.
Comparing Numbers
Select two numbers and check their relation: First Number: Relation: Second Number:
public class Test { public static void main(){ String a = “Hello”; String b = new String(“Hello”);
System.out.println(a == b);
} } Test.main()
false
3.2 3.3 and 3.4 Learning Objective
Represent branching logical processes by using conditional statements
We all know how if and else statements work
We all know how if and else statements work Syntax Interactive Flip Cards if-else Syntax
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
else-if Syntax
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else if (condition3) {
// Code to be executed if condition3 is true
} else {
// Code to be executed if none of the conditions are true
}