Conditional and Type Comparison Operators

Introduction: Welcome to your last tutorial on Operators. The Operators we will be learning about today are Type Comparison and Conditionals. What are Conditional Operators? Condition Operators are used within if statements are are used to determine if multiple conditions are true, to check if one OR another condition is true and the final Conditional Operators is a shorthand version of the if else statement which can input straight in to a variable to determine it's value (or method return etc). What is the Type Comparison Operator? There is only one Type Comparison Operator and it is the keyword "instanceof". This checks to see if the word previous of the Operator is the type following the operator. Operator List: Conditional Operator:
&& AND
|| OR
?: Short Hand If Else Statement
Type Comparison: instanceof Example: Both of these operators are kind off hard to explain so here is a couple of examples... The following example checks if "a" and "b" are true. It then checks if "c" or "d" are true. Afterwards it set "f" to the opposite of "e".
  1. boolean a = true;
  2. boolean b = true;
  3. boolean c = false;
  4. boolean d = true;
  5. boolean e = false;
  6. boolean f = true;
  7. if (a && b) {
  8. System.out.println("Both a and b are true");
  9. if (c || d){
  10. System.out.println("c OR d are true");
  11. }
  12. }
  13. f = e ? true : false;
  14. System.out.println("F is " + f);
Which gives the output...
Both a and b are true
c OR d are true
F is false
The next example checks if the variable "p" is int or not...
  1. Integer p = 1;
  2. if (p instanceof Integer){
  3. System.out.println("P is int!");
  4. }else{
  5. System.out.println("P is int!");
  6. }
Which gives the output...
P is int!
Finished!

Add new comment