Home
Examples
Labs
Assignment
Marks
Midterm
Final Exam
Resources

About Decision Statements

  • the java programming language has two types of decision statements: the if-else statement, and the switch statement.
  • decision statements make it possible for us to write conditional code - code that is only executed sometimes.
  • specifically, conditional code is only executed when a particular condition is met, or found to be true.
  • conditions are typically represented using boolean expressions.


Basic if Statement

This is the simplest form of the if statement in java.  If the particular condition is true, then the java statement is executed.  If the condition is false, then the java statement is skipped.  Notice that there is no semicolon after the condition!
         if (condition)
              java statement;
For example: print the message, "Not a positive number" only if the value in i is less than zero.
         if (i < 0)
              System.out.println("Not a positive number.");
To conditionally execute multiple statements, package the statements together using begin and end braces.
         if (condition) {
              java statement;
              java statement;
              java statement;
            } // end if
For example: if the value in i is not a positive number do three things - warn the user, make i positive, and tell the user that you changed the value of i.
         if (i < 0) {
              System.out.println("Not a positive number.");
              i = Math.abs(i);
              System.out.println("Now " + i + " is positive.");
           } // end if


Relational Operators

Relational operators are used in boolean expressions.  Relational operators compare two values and return either true or false.  For this class you should know the following relational operators :

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



Boolean Expressions

Boolean expressions are expressions that evaluate to either true or false.  Most often, you will use boolean expressions to represent a condition, but you can also save the result of a boolean expression in a boolean variable.  Here are some examples of simple boolean expressions.

(3 < 4)
(4 <= 4)
(5 == 4)
(1 != 0)
(4 < 4)
(4 == 4)
(5 > 4)
evaluates to true
evaluates to true
evaluates to false
evaluates to true
evaluates to false
evaluates to true
evaluates to true


Boolean expressions can also include variables.  In fact, you will almost always use a variable when you program a boolean expression.  For the following examples, variables i, j and k are assigned the values i = 3, j = 4, and k = 5.

(i < 4)
(i < j)
(k > i)
(j != i)
(j >= 11)
(k == 4)
(j <= 5)
evaluates to true
evaluates to true
evaluates to true
evaluates to true
evaluates to false
evaluates to false
evaluates to true



if-else Statement

Optionally, if statements in java may contain an else.   The else describes what we should do if the condition is false.   Here are the general forms of if-else in java.   Remember to package multiple statements together using begin and end braces.
          if (condition)
                java statement;
          else 
                java statement;


          if (condition) {
                java statement;
                java statement;
                java statement;
            } // end if
          else {
                java statement; 
                java statement;
                java statement;
            } // end else
For example: if i is equal to zero print a message telling the user that we "can't divide by zero".  Otherwise, (if i is any number but zero) do the division, and display the result.
         if (i == 0)
             System.out.println("Can't divide by zero.");
         else {
             int answer = 10 / i;
             System.out.println("10 / i = " + answer);
           } // end else


Mathematical Expressions in the Condition

Note that we can use mathematical expressions as part of boolean expressions.  For example:
          if ((i % 2) == 0)
              System.out.println("That is an even number.");
          else
              System.out.println("That is an odd number.");  


          if ((feet * 12 + inches) < 52)
              System.out.println("You are too short to ride
                                    the roller coaster");


Compound Boolean Expressions

A logical operator joins two boolean expressions to make a compound boolean expression.   The logical operators that we will use in this course are && and ||.
  • &&   -   logical AND, returns true if both sides are true.
  • ||   -   logical OR, returns true if at least one side is true.

For Example: Use logical AND to check if i meets both of two conditions.
      System.out.print("Enter an integer between 1 and 10 > ");
      int i = Integer.parseInt(kb.readLine());

      if ((i >= 1) && (i <= 10))
          System.out.println("Thank you");
      else
          System.out.println("Must be between 1 and 10");

Another Example: Use logical OR to check if i meets at least one of two conditions.
     System.out.print("Enter a non zero number > ");
     int i = Integer.parseInt(kb.readLine());

     if ((i > 0) || (i < 0))
           System.out.println("Thank you");
     else
           System.out.println("Error: You entered zero!");
 

The Negation Operator

The negation operator in java is !.  We use negation to make the value of a boolean expression the opposite of what it is at present.  For example :

          !false     is the same as:   true
          !true     is the same as:   false
          !(x == 0)     is the same as:   (x != 0)
          !(y > 6)     is the same as:   (y <= 6)
          !(A || B)     is the same as:   (!A && !B)



Precedence / Priority of Operators Revisited

Remember that expressions are evaluated starting with the highest priority operations, and working down to the lowest priority operations.  Brackets have the highest priority, and assignment has the lowest priority.   Operators with equal priority are evaluated working from right to left.  The following shows the order of operations in java including relational and logical operators.
1.
2.
3.
4.
5.
6.
7.
8.
9.
( )
++
*
+
>
==
&&
||
=

--
/
-
<
!=




!
%

>=








<=







Multiple Cascaded if-else Statements

We can cascade if-else statements together as shown in the following example.   The important thing to remember about cascaded if-else statements is that only one conditional code segment is executed.   The first condition that is found to be true has its statement(s) carried out.   Subsequent conditions are not checked.
        if (studentMark >= 95.0f)
             System.out.print(" That's an A+ ");
        else if (studentMark > 85.0f)
             System.out.print(" That's an A ");
        else if (studentMark > 70.0f)
             System.out.print(" That's a B ");
        else if (studentMark > 60.0f)
             System.out.print(" That's a C ");
        else if (studentMark >= 50.0f)
             System.out.print(" That's a D ");
        else if (studentMark < 50.0f)
             System.out.print(" That's an F ");


Multiple Independent if Statements

In the case of multiple if statements that appear in succession, each if statement is completely independent.  Every condition is checked!  Each if statement knows nothing about the result of the other if statements.
        if (studentMark >= 95.0f)
               System.out.print(" That's an A+ ");

        if ((studentMark > 85.0f) && (studentMark < 95.0f))
             System.out.print(" That's an A ");

        if ((studentMark > 70.0f) && (studentMark <= 85.0f))
             System.out.print(" That's a B "); 

        if ((studentMark > 60.0f) && (studentMark <= 70.0f))
             System.out.print(" That's a C ");

        if ((studentMark >= 50.0f) && (studentMark <= 60.0f))
             System.out.print(" That's a D ");

        if (studentMark < 50.0f)
             System.out.print(" That's an F ");


Nested if Statements

We can nest if statements inside of each other.  That is, if statements may appear as part of the conditional code inside of an outer if statement.  Nested if statements can be used instead of a compound condition.   For example :
    if (x > 0)
       if (x <= 10) {
           System.out.println("x is greater than 0");
           System.out.println("x is less that or equal to 10");
           System.out.println("The value of x is " + x);
         } // end inner if
is the same as :
      if ((x > 0) && (x <= 10)) {
          System.out.println("x is greater than 0");
          System.out.println("x is less that or equal to 10");
          System.out.println("The value of x is " + x);
        } // end if


Code Blocks

A block of code is any group of java statements that starts with a left curly brace and ends with a right curly brace.  Anything declared inside of a code block will only exist in memory as long as we are executing inside of the block.  Once execution moves past the close brace, everything declared inside of the block is thrown away.  Remember though, blocks nested inside of other blocks can access anything declared in the outer block.



The Special Case for String Comparison

Recall that Strings are represented in java as objects.  Applying relational operators to Strings will not have the expected effect.  Relational operators look at what is stored in the variable.  For objects, all that is in the variable is a reference describing where to find the object.  Usually, you will want to compare the character sequence of two Strings, not their object reference.  String objects have special methods for doing this.
  • equals(String str)
    Returns true if the character sequence of the specified String str is exactly equal to the character sequence of this String.


  • equalsIgnoreCase(String str)
    Returns true if the character sequence of the specified String str is the same as the character sequence of this String irrespective of capitalisation.


  • compareTo(String str)
    Returns the lexicographical difference between this String and the specified String str.   The comparison is based on the Unicode value of each character in the Strings.   Zero is returned if both Strings are equal.

            // Lexicographic difference of s1 and s2 is 2
               String s1 = "cat";
               String s2 = "car";
               int lexDif = s1.compareTo(s2);


            // Lexicographic difference of s1 and s2 is -1
               String s1 = "a";
               String s2 = "b";
               int lexDif = s1.compareTo(s2);


            // Lexicographic difference of s1 and s2 is 32
               String s1 = "a";
               String s2 = "A";
               int lexDif = s1.compareTo(s2);



The char Primitive Data Type

Another one of java's primitive data types is char.  The char data type can hold a single unicode character.  Because chars are primitive data types, we can use relational operators on them with the expected effect.  Recall that String objects represent a sequence of individual characters.  We can use the charAt() method to extract a particular character from a String.

The char type is useful for representing a user's menu choice.  Consider the following example.  Notice that literal char values are inclosed in single quotes.

        // Display a menu for the user to pick from
           System.out.println(" Menu ");
           System.out.println(" A - Add a List of Numbers ");
           System.out.println(" M - Display Multiplication Table ");
           System.out.println(" S - Calculate Square Root ");
           System.out.println();
           System.out.print(" Choice > ");

        // Read in the user's choice in as a String
           String inputString = kb.readLine();

        // Convert the choice to a single uppercase character
           inputString = inputString.toUpperCase();
           char choice = inputString.charAt(0); 

        // Use an if statement to figure out what the user selected
           if (choice == `A')
                  . . .
           else if (choice == `M')
                  . . .
           else if (choice == `S')
                  . . .


The boolean Primitive Data Type

Another primitive data type in java is the boolean.  We can store the result of a boolean expression in a boolean variable.  We can also explicitly assign boolean variables the value of either true or false.  This is useful for setting up boolean flags - boolean variables that record when a particular event happened (like the user entering a `Q' for quit).

        // We are not done, so done = false
           boolean done = false;

        // Get the user's choice
           String inputString = kb.readLine();
           inputString = inputString.toUpperCase();
           char choice = inputString.charAt(0); 

        // Are we done now?
           if (choice == `Q')
                  done = true;


switch Statement

A switch statement can be used instead of multiple if-else statements.  The switch statement is designed to conditionally switch between multiple outcomes.  The value of the switch expression must be an ordinal type.  Ordinal types have values within a countable set.  Primitive data types like boolean, char, and int are ordinal types.  The following is the general form of the switch statement in java.  If none of the cases match the expression, then the default case is executed.   Note however, that a default case is optional.
           switch (expression) {
               case constant1 : java statement;
                                         java statement;
                                         break;
               case constant2 : java statement;
                                         java statement;
                                         break;
                  . . .    . . .    . . .

               case constantN : java statements;
                                         java statement;
                                         break;
               default : java statement;
                                  java statement;
                                  break;
           } // end case 

For Example : Print the word that corresponds to the integer value stored in number if the value is 1, 2, or 3.  Otherwise, warn the user that the number was outside of the expected range.
           switch (number) {
               case 1  : System.out.print("One");
                         break;
               case 2  : System.out.print("Two");
                         break;
               case 3  : System.out.print("Three");
                         break;
               default : System.out.print("Out of Range 1 to 3.");
                         break;
           } // end case