Tuesday, July 3, 2012

JAVA Basics 8: Java Relational Operators


A relational operator compares two values and determines the relationship between them. For example, != returns true if its two operands are unequal. Relational operators are used to test whether two values are equal, whether one value is greater than another, and so forth. The relation operators in Java are: ==!=<><=, and >=. The meanings of these operators are:
UseReturns true if
op1 > op2op1 is greater than op2
op1 >= op2 op1 is greater than or equal to op2
op1 op2 op1 is less than to op2
op1 <= op2 op1 is less than or equal to op2
op1 == op2 op1 and op2 are equal
op1 != op2 op1 and op2 are not equal
Variables only exist within the structure in which they are defined. For example, if a variable is created within a method, it cannot be accessed outside the method. In addition, a different method can create a variable of the same name which will not conflict with the other variable. A java variable can be thought of

The main use for the above relational operators are in CONDITIONAL phrases The following java program is an example, RelationalProg, that defines three integer numbers and uses the relational operators to compare them. 
public class RelationalProg {
 public static void main(String[] args) {

 //a few numbers
 int i = 37;
 int j = 42;
 int k = 42;

 //greater than
 System.out.println("Greater than...");
 System.out.println(" i > j = " + (i > j)); //false
 System.out.println(" j > i = " + (j > i)); //true
 System.out.println(" k > j = " + (k > j)); //false
 //(they are equal)

 //greater than or equal to
 System.out.println("Greater than or equal to...");
 System.out.println(" i >= j = " + (i >= j)); //false
 System.out.println(" j >= i = " + (j >= i)); //true
 System.out.println(" k >= j = " + (k >= j)); //true

 //less than
 System.out.println("Less than...");
 System.out.println(" i < j = " + (i < j)); //true
 System.out.println(" j < i = " + (j < i)); //false
 System.out.println(" k < j = " + (k < j)); //false

 //less than or equal to
 System.out.println("Less than or equal to...");
 System.out.println(" i <= j = " + (i <= j)); //true
 System.out.println(" j <= i = " + (j <= i)); //false
 System.out.println(" k <= j = " + (k <= j)); //true

 //equal to
 System.out.println("Equal to...");
 System.out.println(" i == j = " + (i == j)); //false
 System.out.println(" k == j = " + (k == j)); //true

 //not equal to
 System.out.println("Not equal to...");
 System.out.println(" i != j = " + (i != j)); //true
 System.out.println(" k != j = " + (k != j)); //false
 }
}

No comments:

Post a Comment