UF 06: JAVA¶

Boolean Expressions and If Statements¶

Alta Formazione Professionale - ITT Marconi

January 2021

3.1. Boolean Expressions¶

1) Testing Equality (==)

between primitive types

between references

2) Relational Operators (<, >)

  • <
  • >
  • <=
  • >=
  • ==
  • !=

3) Testing with mod (%)

In [1]:
18 % 5  // the remainder is ....
Out[1]:
3

Test if a number is even ?

Test if a number is odd ?

3.2. if Statements and Control Flow¶

1) Relational Operators in if Statements

condition

if¶

In [2]:
boolean isRaining = true;

System.out.println("BEFORE");

if (isRaining) {
   System.out.println("  THEN BRANCH");
}

System.out.println("AFTER");
BEFORE
  THEN BRANCH
AFTER
In [3]:
boolean isRaining = false;

System.out.println("BEFORE");

if (isRaining) {
   System.out.println("THEN BRANCH");
}

System.out.println("AFTER");
BEFORE
AFTER

Testing for equality¶

  • if (x == y) // JAVA
  • if (x === y) // JAVASCRIPT
  • if (x = y) // BAD

3.3. Two-way Selection: if-else Statements¶

condition-else

if else¶

In [4]:
boolean isRaining = true;

System.out.println("BEFORE");
if (isRaining) {
    System.out.println("  THEN BRANCH");
} else {
    System.out.println("  ELSE BRANCH");
}

System.out.println("AFTER");
BEFORE
  THEN BRANCH
AFTER
In [5]:
boolean isRaining = false;

System.out.println("BEFORE");
if (isRaining) {
    System.out.println("  THEN BRANCH");
} else {
    System.out.println("  ELSE BRANCH");
}

System.out.println("AFTER");
BEFORE
  ELSE BRANCH
AFTER

Nested Ifs and Dangling Else¶

In [6]:
boolean condA = true;
boolean condB = false;

if (condA) {
   if (condB) {
       System.out.println("condA and condB");
   } else {
       System.out.println("only condA");
   }
} else {
   
}
only condA
In [7]:
boolean condA = true;
boolean condB = true;

if (condA) {
   if (condB) {
       System.out.println("condA and condB");
   } else {
       System.out.println("only condA");
   }
} else {
   
}
condA and condB

3.4. Multi-Selection: else-if Statements¶

if-cascade

if cascade¶

In [8]:
int x = -5;

if (x < 0) {
   System.out.println("x is negative");
}
else if (x == 0) {
   System.out.println("x is zero");
}
else {
   System.out.println("x is positive");
}
x is negative

3.5. Compound Boolean Expressions¶

1) And (&&), Or (||), and Not (!)¶

2) Truth Tables¶

AND: &&¶

a b a && b
false false false
false true false
true false false
true true true

OR: ||¶

a b a || b
false false false
false true true
true false true
true true true

NOT: !¶

a !a
false true
true false

Guess booleans¶

  1. !(true && false)
    
  2. (!true) || (!(true || false))
    
  3. !(!true)
    
  4. !(true && (false || true))
    
  5. !(!(!false))
    
  6. true && (!(!((!false) && true)))
    
  7. false || (false || ((true && true) && (true && false)))
    

Booelans: which x,y give true ?¶

NOTE: there can be many combinations that produce true, find them all

  1. x || (!x)
    
  2. (!x) && (!y)
    
  3. x && (y || y)
    
  4. x && (!y)
    
  5. (!x) ||  y
    
  6. y || !(y && x)
    
  7. x && ((!x) || !(y))
    
  8. (!(!x)) && !(x && y)
    
  9. x && (x || (!(x) || !(!(x || !(x)))))
    

Booelans: which x,y give false ?¶

QUESTION: For each of these expressions, for which values of x && y they give false?

NOTE: there can be many combinations that produce false, find them all

  1. x || ((!y) || z)
    
  2. x || (!y) || (!z)
    
  3. !(x && y && (!z))
    
  4. !(x && (!y) && (x || z))
    
  5. y || ((x || y) && (!z))
    

3) Short Circuit Evaluation ?¶

false && superComplicatedBooleanExpression

true && superComplicatedBooleanExpression

a b a && b
false false false
false true false
true false false
true true true

3) Short Circuit Evaluation ?¶

false || superComplicatedBooleanExpression

true || superComplicatedBooleanExpression

a b a || b
false false false
false true true
true false true
true true true

Short circuits to avoid errors ...¶

Let's pick an error:

1/0
---------------------------------------------------------------------------
java.lang.ArithmeticException: / by zero
    at .(#119:1)

Let's create a faulty boolean expression:

1/0 == 5
---------------------------------------------------------------------------
java.lang.ArithmeticException: / by zero
    at .(#119:1)

Short circuits to avoid errors ?¶

  • true && (1/0 == 5)
  • false && (1/0 == 5)
  • true || (1/0 == 5)
  • false || (1/0 == 5)

EXERCISE¶

Write some code which puts true in boolean var isSecB if the second character of the string s is the character 'B'. Otherwise, stores false.

  • DO NOT USE if statements
//  01234
   String s = "ABACO";  // true         
// String s = "BIRBA";  // false

// write here
boolean isSecB = 

System.out.println(isSecB);

More short circuits¶

  1. true || (1/0==5 && true)
    
  2. (!false) || !(1/0==5)
    
  3. true && 1/0==5 && true
    
  4. (!true) || 1/0!=5 || true
    
  5. true && (!true) && 1/0==5
    

3.6. Equivalent Boolean Expressions (De Morgan’s Laws)¶

1) De Morgan’s Laws

  • !(a && b) is equivalent to !a || !b

  • !(a || b) is equivalent to !a && !b

2) Truth Tables

3) Simplifying Boolean Expressions

De Morgan - questions¶

Look at following expressions, and try to rewrite them in equivalent ones by using De Morgan laws, simplifying the result wherever possible. Then verify the translation produces the same result as the original for all possible values of x && y.

  1. (!x) || y
    
  2. (!x) && (!y)
    
  3. (!x) && (!(x || y))
    

Example:

boolean x = false, y = false;
//boolean x = false, y = true;
//boolean x = true, y = false;
//boolean x = true, y = true;

boolean orig = x || y;
boolean trans = !((!x) && (!y));
System.out.println("orig=" + orig);
System.out.println("trans=" + trans);

3.7. Comparing Objects¶

  • == vs equals
import java.util.Date;  // (note this class is actually deprecated)

Date d1 = new Date(121,0,28);
Date d2 = new Date(121,0,28);

System.out.println(d1 == d2);       // ?
System.out.println(d1.equals(d2));  // ?
import java.util.Date;

Date d1 = new Date(121,0,28);
Date d2 = d1;

System.out.println(d1 == d2);       // ?
System.out.println(d1.equals(d2));  // ?
import java.util.Date;

Date d1 = new Date(121,0,28);
Date d2 = new Date(682,7,14);

System.out.println(d1 == d2);       // ?
System.out.println(d1.equals(d2));  // ?
import java.util.Date;

Date d1 = new Date(121,0,28);
Date d2 = new Date(121,0,28);
d2.setYear(300);

System.out.println(d1 == d2);       // ?
System.out.println(d1.equals(d2));  // ?

A better date..¶

  • See Java 8 java.time.LocalDate
  • immutable
  • threadsafe

1) String Equality¶

WARNING: DON'T use == with strings

Strings are immutable and cached !

2) Equality with New Strings

In [9]:
String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
false
true
In [10]:
// WARNING: Java caches strings !
// This very particular behaviour happens *ONLY* because we have strings !!

String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
true
true

Boxed primitives¶

... are immutable

... are they cached?

Integer i1 = new Integer(3);
Integer i2 = new Integer(3);

System.out.println(i1 == i2);       // ?
System.out.println(i1.equals(i2));  // ?
Integer i1 = 3;  // autoboxed 
Integer i2 = 3;

System.out.println(i1 == i2);        // ?
System.out.println(i1.equals(i2));   // ?

3) Comparing with null¶

a == b

  • left ?
  • right ?

a.equals(b)

  • left ?
  • right ?

Exercise - The drone¶

You have a map of an island where zones in which a treasure could be are marked in green (ignore other colors). A drone which can land and drill the terrain. Strong winds could move the drone away from the target, so the drone needs to know whether or not is on a zone it should drill. Given the map side length d and two coordinates x and y, RETURN true if the place is to drill (that is, the drone is on a green zone), otherwise return false. ASSUME THE ORIGIN (0,0) IS AT THE CENTRE OF THE MAP

treasure-island

In [14]:
public class MyClass {
  
    private static int d = 10;

    /** RETURN true if the place is to drill, otherwise return false. */
    public static boolean to_drill(double x, double y){ 
        
        throw new UnsupportedOperationException("TODO IMPLEMENT ME!");                
    }
    
    public static void check(boolean expected, boolean actual){
        if (expected != actual){
            throw new AssertionError("ERROR! Expected: " + expected + "   Actual: " + actual);
        }
    }
    
    public static void main(String[] args) {  
        
        // inner radius
        check(true, to_drill(0,0));
        check(true, to_drill(0.2*d,0));
        check(true, to_drill(0,0.1*d));
        check(true, to_drill(0,-0.03*d));
        check(true, to_drill(-0.01*d,-d*0.05));        
        // corona
        check(false, to_drill(0,-0.3*d));
        check(false, to_drill(0.35*d,0));
        check(false, to_drill(0.4*d,0.27*d));
        check(false, to_drill(0.31*d,-0.4*d));
        check(false, to_drill(-0.31*d,0.4*d));
        check(false, to_drill(-0.3*d,-0.38*d));        
        // corners
        check(true, to_drill(0.49*d,0.49*d));
        check(false, to_drill(0.45*d,-0.46*d));
        check(false, to_drill(-0.48*d,0.45*d));
        check(true, to_drill(-0.49*d,-0.47*d));
    }
}
---------------------------------------------------------------------------
java.lang.UnsupportedOperationException: TODO IMPLEMENT ME!
    at MyClass.to_drill(#38:1)
    at MyClass.main(#38:1)
    at .(#39:1)

3.12. Magpie Chatbot Lab¶

In [15]:
public class Magpie
{
   public String getGreeting() {
     return "Hello, let's talk.";
   }

   public String getResponse(String statement) {     
     String response = getRandomResponse();     
     return response;
   }

   private String getRandomResponse() {
     String response = "Interesting, tell me more.";     
     return response;
   }

   private void answer(String msg) {
       System.out.println(">" + msg);
       System.out.println(this.getResponse(msg));
   }

   public static void check(boolean expected, boolean actual) {
        
   }

   public static void main(String[] args) {
     Magpie maggie = new Magpie();

     System.out.println(maggie.getGreeting());
     
     maggie.answer("My mother and I talked last night.");
   }
}
In [ ]: