Java TUTORIAL - relational operator
In the if else java tutorial we compared two numbers and took some action based upon the result of the comparison. The comparison was done using a relational operator > ( greater than sign). Java has a number of other relational operators. A relational operator is used to compare two values or values of two variables.
The Table lists out the main Java relational operators,
Java Operators
Operator | Meaning |
== | Equal to |
!= | Not Equal to |
< | Less than |
> | Greater than |
>= | Greater than or equal to |
< | Less than |
<= | less than or equal to |
Let us now write a java code that will make use of the relational operator greater than or eqaul to (>=) to find if the height of a person is more than 6 feets
|
If you compile and run this program, you will get the output as follows
C:\Program Files\Java\jdk1.7.0_17\bin>java relationaloperator The height is greater than or equal to 6 ft You are Tall ! C:\Program Files\Java\jdk1.7.0_17\bin> System.out.println("The height is greater than or equal to 6 ft"); |
Exercises
Here are some exercises for you
Exercise 1
Change the value of height in the above program such that it prints "you are less that 6 feet".
Exercise 2
Define two integer variables x and y and assign them some constant values. Write a program that compares them if they are not equal. Make use of the inequality operator !=.
Result of a relational comparison is a Boolean Type
The result of a relational comparison is boolean and it returns the result which is either true or false. So what is a boolean type ? It is another type similar to the integer type or double type that takes value true or false. Take a look at the following example
|
The purpose of the above example was three fold.
1. Introduce you to new type - boolean type. In the above example we have declared the variable c as the boolean variable
boolean c;
2. The boolean c is assigned the value of the comparison x != y. So basically we are asking - Is x not eqaul to y ? Since x is not equal to y, c is assigned value true
c = (x !=y);
3. Finally we have used the System.out.println statememt to print the value of a boolean variable. It prints true or false depending upon the state of the boolean variable.
System.out.println(c);
You may have guessed by now. The program produces the following output
C:\Program Files\Java\jdk1.7.0_17\bin>java relationaloperator The state of c is true |
Exercise 3
In the previous if else tutorial page we had written an example that printed maximum of three given numbers. Rewrite the example so that it prints the minimum in place of the maximum of the three numbers.