University of Cincinnati logo and link  
Conditionals
 
  UC ingot 

As with (nearly) all programming languages, Java has the conditional statement.  It comes in two flavors:

  • The if test: tests if a condition in the parenthesis following the if is true.  If so, executes the code in the block surrounded by {} after the test.
    • It has an optional else if, again followed by a comparison in parenthesis.  If the previous tests failed, the else if block executes.  Again, if the argument evaluates to true, the code in the block is executed.  If not, it continues on to the next test or exits.
    • It also has an optional else, without an argument in parenthesis.  This executes if all previous tests failed.  You can consider this the 'default'.
    • Note, if tests can be nested.
    • Example 1: Take a look at the  PromptMe example we discovered earlier.
    • Example 2: It works in a similar way as JavaScript. Let's take a look at some slides I adapted from Internet II.
  • The often frowned-upon switch-case statement.
    • Start with switch(), and put some variable in the parenthesis.
    • Follow with the case statement, and a value.  Each case evaluates whether that argument equals the value.
      • They must be exactly equal.  You cannot use > or <; == is assumed.
      • You can only use byte and int types.  Be warned!
    • Code will execute until it sees a break;.  Always double-check breaks.
      • With break, only execute current statements.
      • Without break, the execution will cascade down the list.
      • default does not need a break.   It is the last statement.
    • switch, case, default, break.
    • See the example in  StringManip

    •