About if and switch Statements


  • The only legal expression in an if statement is a boolean expression, in other words an expression that resolves to a boolean or a Boolean variable.
  • Watch out for boolean assignments (=) that can be mistaken for boolean  equality (==) tests:
  • boolean x = false; if (x = true) { } // an assignment, so x will always be true!
  • Curly braces are optional for if blocks that have only one conditional statement. But watch out for misleading indentations.
  • switch statements can evaluate only to enums or the byte, short, int, and
  • char data types. You can't say,
  • long s = 30;
  • switch(s) { }
  • The case constant must be a literal or final variable, or a constant expression, including an enum. You cannot have a case that includes a nonfinal variable, or a range of values.
  • If the condition in a switch statement matches a case constant, execution will run through all code in the switch following the matching case statement until a break statement or the end of the switch statement is encountered. In other words, the matching case is just the entry point into the case block, but unless there's a break statement, the matching case is not the only case code that runs.
  • The default keyword should be used in a switch statement if you want to run some code when none of the case values match the conditional value.
  • The default block can be located anywhere in the switch block, so if no case matches, the default block will be entered, and if the default does not contain a break, then code will continue to execute (fall-through) to the end of the switch or until the break statement is encountered.