Java relational operators
Created By: chatGPT
In Java, relational operators are used to compare two values, returning a boolean result. Here's a look at the common relational operators available in Java with their respective functions:
1. Greater Than (>): Checks if the left operand is greater than the right operand.
int a = 5;
int b = 3;
boolean result = a > b; // true
2. Less Than (<): Checks if the left operand is less than the right operand.
int a = 5;
int b = 8;
boolean result = a < b; // true
3. Greater Than or Equal To (>=): Checks if the left operand is greater than or equal to the right operand.
int a = 5;
int b = 5;
boolean result = a >= b; // true
4. Less Than or Equal To (<=): Checks if the left operand is less than or equal to the right operand.
int a = 3;
int b = 5;
boolean result = a <= b; // true
5. Equal To (==): Checks if the left operand is equal to the right operand.
int a = 5;
int b = 5;
boolean result = a == b; // true
6. Not Equal To (!=): Checks if the left operand is not equal to the right operand.
int a = 5;
int b = 3;
boolean result = a != b; // true
These operators are essential for controlling the flow of the program using conditional statements. For example, they can be used in if-else conditions.
int a = 5;
if (a > 0) {
System.out.println("a is positive");
} else {
System.out.println("a is not positive");
}
When using relational operators, be aware of the data types being compared, as it may affect the outcome. For instance, comparing integers to floating points could lead to unexpected results.
int x = 7;
double y = 7.0;
boolean result = (x == y); // true