Saturday 1 February 2014

Conditional operators

Conditional operators determine if one operand is greater than, less than, equal to, or not equal to another operand.

Operator             Description
    ==                     equal to
    !=                      not equal to
    >                       greater than
    >=                     greater than or equal to
    <                       less than
    <=                     less than or equal to

Conditional operators takes two operands and return true, if the condition evaluates to true, otherwise return false.

Example
class ConditionalEx{
 public static void main(String args[]){
  int a = 10, b=11;
  
  System.out.println("is a equals to a " + (a==a));
  System.out.println("is a equals to b " + (a==b)); 
  System.out.println("is a not equals to a " + (a!=a));
  System.out.println("is a not equals to b " + (a!=b));
  System.out.println("is a less than a " + (a<a));
  System.out.println("is a less than b " + (a<b));
  System.out.println("is a less than or equal to a " + (a<=a));
  System.out.println("is a less than or equal b " + (a<=b));
  System.out.println("is a greater than a " + (a>a));
  System.out.println("is a greater than b " + (a>b));
  System.out.println("is a greater than or equal to a " + (a>=a));
  System.out.println("is a greater than or equal to b " + (a>=b));
 }
}

Output
is a equals to a true
is a equals to b false
is a not equals to a false
is a not equals to b true
is a less than a false
is a less than b true
is a less than or equal to a true
is a less than or equal b true
is a greater than a false
is a greater than b false
is a greater than or equal to a true
is a greater than or equal to b false

Some points to remember

1. You can compare one type of data with another if types are compatible.
class ConditionalEx{
 public static void main(String args[]){
  int a = 10;
  float b = 1.09f;
  char c = 'a';
  
  System.out.println("a less than b " + (a<b));
  System.out.println("a less than c " + (a<c));
 }
}
Output    

a less than b false
a less than c true
   
2. If you try to compare two incompatible type values, compiler will throw error.
class ConditionalEx{
 public static void main(String args[]){
  int a = 10;
  boolean b = true;
  
  System.out.println("a less than b " + (a<b));
 }
}
    

If you try to compile the above program, you will get the below error
ConditionalEx.java:8: error: bad operand types for binary operator '<'
 System.out.println("a less than b " + (a<b));
 ^
 first type: int
 second type: boolean
1 error
   


Arithmetic Operators                                                 Not equal to operator                                                 Home

No comments:

Post a Comment