Search Logic Blocks

Tuesday, January 7, 2020

Java: Relational Operators

Relational operators are also called the comparison operators. Comparison operators are used to compare two values of the same data type and to return the result as a single boolean value - true or false. Following is the chart of all relational / comparison operators.

Suppose, x = 8, y = 6 then:

Operator Comparison Operation Result
== Equality x == y false
!= Not Equal To x != y true
> Greater Than x > y true
< Less Than x < y false
>= Greater Than / Equal To x >= y true
<= Less Than / Equal To x <= y false

Below is an example, how to write comparison operator Greater Than (>) -
boolean blnGreater;

int x = 45, y = 70;
blnGreater = (x > y); // will return false

y = 35;
blnGreater = (x > y); // will return true
Example : What should be the result of the following java code? Let's see - 

Class Compare (Compare.java)
public class Compare {
    public static void main(String args[]) {
        int x = 50, y = 50;
        boolean blnResult = false;

        int result = x + (y / 2) - 10;
        blnResult = (result == 30);

        System.out.println("Result is equal to 30: " + blnResult);
        System.out.println("Result is: " + result);
    }
}
result = x + (y / 2) - 10 = 50 + (50 / 2) - 10 = 50 + 25 - 10 = 65
blnResult = (result == 30) = (65 == 30) = false

Result is equal to 30: false
Result is: 65

No comments: