Operators (Cont.)


Comparison Operators
Comparison operators are used to compare two values:

Operator Name Example Operator Name Example
== Equal to x == y != Not equal x != y
> Greater than x > y < Less than x < y
>= Greater than or equal to x >= y <= Less than or equal to x <= y

Logical Operators
Logical operators are used to determine the logic between variables or values:

Operator Name Description Example
&& Logical and Returns true if both statements are true. x < 5 && x < 10
|| Logical or Returns true if one of the statements is true. x < 5 || x < 4
! Logical not Reverses the result, and returns false if the result is true. !(x < 5 && x < 10)

Miscellaneous Operators
There are few other operators supported by Java language:

Operator Name Description Example
? : Ternary operator variable x = (expression) ? value if true : value if false b = (a == 1) ? 20 : 30;
instanceof instanceof operator ( Object reference variable ) instanceof (class/interface type) boolean result = name instanceof String;

Car.java (instanceof operator)
// A superclass of Car
class Vehicle {
  public String engine;
  public int    year;
}

// A subclass of Vehicle
public class Car extends Vehicle {
  public static void main( String args[ ] ) {
    int     year  = Integer.parseInt( args[1] );
    Vehicle lexus = new Car( args[0], year );
    if ( lexus instanceof Vehicle )
      System.out.println( lexus.engine );
    else
      System.out.println( lexus.year );
  }

  // A constructor
  public Car( String eng, int y ) {
    engine = eng;
    year   = y;
  }
}
shell> java Car      

Output:           Result:




      Despite all the failures, one must never quit because the third time will be a charm.