Making decisions in a computer program

A computer program can make a 2 way decision:

import java.util.Scanner;  // Demo in BlueJ

public class ComputeArea
{
   public static void main(String[] args)
   {
      Scanner input = new Scanner(System.in); 
      double radius;
      double area;
 
      System.out.print("Enter a radius: ");
      radius = input.nextDouble();    

      if ( radius < 0 )
      {
         System.out.println("Illegal radius");
      }
      else
      {   // Print area of circle
          area = 3.14159 * radius * radius; 
          System.out.println(area);
      }
   }                       
}   

DEMO: demo/03-selections/01-intro/ComputeArea.java

The boolean data type and boolean expressions

  • The Boolean data type:

    • The Boolean data type in Java is used to represent logical values

      (Named after George Boole who studied logic)

  • The logical values are:

    • true     (a keyword in Java !)
    • false   (a keyword in Java !)

  • A boolean expression (a.k.a. a condition) is an expression that evaluates to either true or false

    Examples:

         radius < 0   // The result can only be true or false     
      

Define boolean variables and assigning to boolean variables

  • How to define a boolean variable in Java:

      boolean variableName ;
      boolean variableName = true ;  // With initialization
    

  • How to assign a logical result to a boolean variable:

      booleanVarName = boolean-expression ;
    

    Example:

      double radius = -1;
      boolean isNegative;
     
      isNegative = radius < 0; // Evaluate radius < 0 and
                               // assign result to isNegative
    

DEMO: demo/03-selections/01-intro/BooleanVar.java

Comparing 2 values

  • Java provides the following operators to compare two (2) values:

      Operator symbol     Operator name             Example use
     -----------------   -----------------------   --------------
            <             Less than                 radius <  0
            <=            Less than or equal        radius <= 0
            >             Greater than              radius >  0
            >=            Greater than or equal     radius >= 0
            ==            Equal to                  radius == 0
            !=            Not equal to              radius != 0
      

  • These operators are called:

    • Relational operators

Exercise:    Test if you understand the relational operators

What are the outputs of this Java program:

public class Quiz
{
   public static void main(String[] args)
   {
      double x = 1;    // Breakpoint here
      
      System.out.println( x > 0  );
      System.out.println( x < 0  );
      System.out.println( x != 0 );
      System.out.println( x >= 0 );
      System.out.println( x != 1 );
      System.out.println( x <= 1 );
      System.out.println( x > 1  );
   }        
} 

DEMO: demo/03-selections/01-intro/Quiz.java

Step through the program in BlueJ