Chapter 4 Making Decisions Notes Flashcards

1
Q

STATEMENTS AND BLOCKS

A

a Java statement is a complete unit of execution in Java, terminated with a semicolon (;).

// Single statement
patrons++;

a block of code in Java is a group of zero or more statements between balanced braces ({}) and can be used anywhere a single statement is allowed.

// Statement inside a block
{
   patrons++;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

The structure of an if statement

A
if (booleanExpression) {
    // Branch if true
}
  1. if keyword
  2. Parentheses (required)
  3. Curly braces required for block of multiple statements, optional for single statement

!NOTES: VERIFYING THAT THE IF STATEMENT EVALUATES TO A BOOLEAN EXPRESSION

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

WATCH INDENTATION AND BRACES

A

In Java tabs are just whitespace and are not evaluated as part of the execution. When you see a control flow statement in a question, be sure to trace the open and close braces of the block, ignoring any indentation you may come across.

if(hourOfDay < 11)
   System.out.println("Good Morning");
   morningGreetingCount++; // will always execute the increment operation.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

The structure of an else statement

A
if (booleanExpression) {
    // Branch if true
} else {
    // Branch if false
}
  1. if keyword
  2. Parentheses (required)
  3. Curly braces required for block of multiple statements, optional for single statement
  4. Optional else statement
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

else if statement

A

else if statement

if(hourOfDay < 11) {
   System.out.println("Good Morning");
} else if(hourOfDay < 15) {
   System.out.println("Good Afternoon");
} else {
   System.out.println("Good Evening");
}

Unreachable statement

if(hourOfDay < 15) {
   System.out.println("Good Afternoon");
} else if(hourOfDay < 11) {
   System.out.println("Good Morning");  // COMPILES BUT IS UNREACHABLE
} else {
   System.out.println("Good Evening");
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

The structure of a switch statement

A
switch (variableToTest) {
    case constantExpression1:
 	           // Branch for case1;
 	           break;
    case constantExpression2:
 	           // Branch for case2;
 	           break;
		...
		default:
 	           // Branch for default;
}
  1. switch keyword required
  2. Parentheses (required)
  3. Beginning curly brace (required)
  4. switch statement may contain 0 or more case branches
  5. Optional break
  6. Optional default that may appear anywhere within switch statement
  7. Ending curly brace (required)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Proper Switch Syntax

int month = 5; 
switch month {  // DOES NOT COMPILE
   case 1: System.out.print("January");
} 
switch (month)  // DOES NOT COMPILE
   case 1: System.out.print("January"); 
switch (month) {
   case 1: 2: System.out.print("January"); // DOES NOT COMPILE
} 
switch (month) {
   case 1 || 2: System.out.print("January"); // DOES NOT COMPILE
}
A
  • The first switch statement does not compile because it is missing parenthesesaround the switch variable.
  • The second statement does not compile because it is missing braces around the switch body.
  • The third statement does not compile because the case keyword is missing before the 2: label.
  • Each case statement requires the keyword case, followed by a value and a colon (:).
  • Finally, the last switch statement does not compile because 1 || 2 uses the short-circuit boolean operator, which cannot be applied to numeric values. A single bitwise operator (|) would have allowed the code to compile, although the interpretation of this might not be what you expect. It would then only match a value of month that is the bitwise result of 1 | 2, which is 3, and would not match month having a value 1 or 2. You don’t need to know bitwise arithmetic for the exam, but you do need to know proper syntax for case statements.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Valid?

switch (month) {}
A

Valid

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Data types supported by switch statements:

A
  • int and Integer
  • byte and Byte
  • short and Short
  • char and Character
  • String
  • enum values
  • var (if the type resolves to one of the preceding types)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Java 12 launched with a Preview release of a powerful new feature called Switch Expressions, a construct that combines switch statements with lambda expressions and allows switch statements to return a value.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Switch Control Flow

A

The exam creators are fond of switch examples that are missing break statements! When evaluating switch statements on the exam, always consider that multiple branches may be visited in a single execution.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Acceptable Case Values

A

First off, the values in each case statement must be compile-time constant values of the same data type as the switch value.
This means you can use only literals, enum constants, or final constant variables of the same data type.
By final constant, we mean that the variable must be marked with the final modifier and initialized with a literal value in the same expression in which it is declared.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q
final int getCookies() { return 4; }
void feedAnimals() {
   final int bananas = 1;
   int apples = 2;
   int numberOfAnimals = 3;
   final int cookies = getCookies();
   switch (numberOfAnimals) {
      case bananas:
      case apples:  // DOES NOT COMPILES
      case getCookies():  // DOES NOT COMPILE
      case cookies :  // DOES NOT COMPILE
      case 3 * 5 :
   }
}
A
  • The bananas variable is marked final, and its value is known at compile-time, so it is valid.
  • The apples variable is not marked final, even though its value is known, so it is not permitted.
  • The next two case statements, with values getCookies() and cookies, do not compile because methods are not evaluated until runtime, so they cannot be used as the value of a case statement, even if one of the values is stored in a final variable.
  • The last case statement, with value 3 * 5, does compile, as expressions are allowed as case values, provided the value can be resolved at compile-time. They also must be able to fit in the switch data type without an explicit cast. We’ll go into that in more detail shortly.
  • Next, the data type for case statements must all match the data type of the switch variable. For example, you can’t have a case statement of type String, if the switch statement variable is of type int, since the types are incomparable.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q
private int getSortOrder(String firstName, final String lastName) {
   String middleName = "Patricia";
   final String suffix = "JR";
   int id = 0;
   switch(firstName) {
      case "Test":
         return 52;
      case middleName:  // DOES NOT COMPILE
         id = 5;
         break;
      case suffix:
         id = 0;
         break;
      case lastName:    // DOES NOT COMPILE
         id = 8;
         break;
      case 5:           // DOES NOT COMPILE
         id = 7;
         break;
      case 'J':         // DOES NOT COMPILE
         id = 10;
         break;
      case java.time.DayOfWeek.SUNDAY:  // DOES NOT COMPILE
         id=15;
         break;
   }
   return id;
}
A
  • The first case statement, “Test”, compiles without issue since it is a String literal and is a good example of how a return statement, like a break statement, can be used to exit the switch statement early.
  • The second case statement does not compile because middleName is not a constant value, despite having a known value at this particular line of execution. If a final modifier was added to the declaration of middleName, this case statement would have compiled.
  • The third case statement compiles without issue because suffix is a final constant variable.
  • In the fourth case statement, despite lastName being final, it is not constant as it is passed to the function; therefore, this line does not compile as well.
  • Finally, the last three case statements do not compile because none of them has a matching type of String, the last one being an enum value.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Numeric Promotion and Casting

short size = 4;
final int small = 15;
final int big = 1_000_000;
switch(size) {
   case small:
   case 1+2 :
   case big:  // DOES NOT COMPILE
}
A
  • the compiler can easily cast small from int to short at compile-time because the value 15 is small enough to fit inside a short. This would not be permitted if small was not a compile-time constant. Likewise, it can convert the expression 1+2 from int to short at compile-time.
  • On the other hand, 1_000_000 is too large to fit inside of short without an explicit cast, so the last case statement does not compile.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

The structure of a while statement

A
while (booleanExpression) {
    // Body
}
  1. while keyword
  2. Parenthese (required)
  3. Curly braces required for block of multiple statements, optional for single statement.
17
Q

The structure of a do/while statement

A
do {
    // Body
} while (booleanExpression);

a do/while loop purposely orders the body before the conditional expression so that the body will be executed at least once

  1. do keyword
  2. Curly braces requires for block of multiple statements, optional for single statement
  3. while keyword
  4. Parenthese (required)
  5. Semicolon (required)
18
Q

The structure of a basic for loop

A
for (initialization; booleanExpression; updateStatement) {
    // Body
}
1. Initialization statement executes
2. If booleanExpression is true continue, else exit loop
3. Body executes
4. Execute updateStatement
5. Return to Step 2
  1. for keyword
  2. Parenthese (required)
  3. Semicolons (required)
  4. Curly braces requires for block of multiple statements, optional for single statement
19
Q

Starting with Java 10, you may now see var used in a for loop

A
for (var counter = 5; counter > 0; counter--) {
   System.out.print(counter + " ");
}
20
Q

Working with for Loops

A

1. Creating an Infinite Loop
components of the for loop are each optional.
semicolons are required

for( ; ; )
   System.out.println("Hello World");

2. Adding Multiple Terms to the for Statement

int x = 0;
for(long y = 0, z = 4; x < 5 && y < 10; x++, y++) {
   System.out.print(y + " "); }
System.out.print(x + " ");

3. Redeclaring a Variable in the Initialization Block

int x = 0;
for(int x = 4; x < 5; x++) {   // DOES NOT COMPILE, x already being declared
   System.out.print(x + " ");
}

4. Using Incompatible Data Types in the Initialization Block
initialization block must all be of the same type

int x = 0;
for(long y = 0, int z = 4; x < 5; x++) { // DOES NOT COMPILE
System.out.print(y + " ");
}

5. Using Loop Variables Outside the Loop

for(long y = 0, x = 4; x < 5 && y < 10; x++, y++) {
System.out.print(y + " ");
}
System.out.print(x); // DOES NOT COMPILE, x is out of scope
21
Q

Modifying Loop Variables

A

> [!NOTE]
Java does let you modify loop variables

for(int i=0; i<10; i++) //infinite loop, never reach i<10
    i = 0;
		
for(int j=1; j<10; j++) //infinite loop, never reach j<10
    j--;

for(int k=0; k<10; ) //executes the loop exactly 10 times
    k++;

> [!NOTE]
As a general rule, it is considered a poor coding practice to modify loop variables due to the unpredictability of the result. It also tends to make code difficult for other people to read. If you need to exit a loop early or change the flow, you can use break, continue, or return

22
Q

There are also some special considerations when modifying a Collection object within a loop. For example, if you delete an element from a List while iterating over it, you could run into a ConcurrentModificationException.

A
23
Q

The structure of an enhanced for-each loop

A

The for-each loop is a specialized structure designed to iterate over arrays and various Collection Framework classes

for (datatype instance : collection) {
    // Body
}
  1. for keyword
  2. Parenthese (required)
  3. datatype of collection member
  4. Colon (required)
  5. Iterable collection of objects
  6. Curly braces requires for block of multiple statements, optional for single statement

The for-each loop declaration is composed of an initialization section and an object to be iterated over.

The right side of the for-each loop must be one of the following:

  • A built-in Java array
  • An object whose type implements java.lang.Iterable

The left side of the for-each loop must include a declaration for an instance of a variable whose type is compatible with the type of the array or collection on the right side of the statement. A var may also be used for the variable type declaration, with the specific type determined by the right side of the for-each statement.

24
Q

for-each loop example:

A
final String[] names = new String[3];
names[0] = "Lisa";
names[1] = "Kevin";
names[2] = "Roger";
for(String name : names) {
    System.out.print(name + ", ");
}

The code will compile and print the following:
Lisa, Kevin, Roger,

Like the regular for loop, the for-each loop also accepts var for the loop variable, with the type implied by the data type being iterated over.

List<String> values = new ArrayList<String>();
values.add("Lisa");
values.add("Kevin");
values.add("Roger");
for(var value : values) {
    System.out.print(value + ", ");
}

The code will compile and print the following:
Lisa, Kevin, Roger,

25
Q

Why does this fail to compile?

String names = "Lisa";
for(String name : names) { // DOES NOT COMPILE
    System.out.print(name + " ");
}
A

String names is not an array, nor does it define a list of items, so the compiler will throw an exception

26
Q

Why does this fail to compile?

String[] names = new String[3];
for(int name : names) { // DOES NOT COMPILE
    System.out.print(name + " ");
}
A

This code will fail to compile because the left side of the for-each statement does not define an instance of String.

Notice that in this last example, the array is initialized with three null pointer values.
In and of itself, that will not cause the code to not compile, as a corrected loop would just output null three times.

27
Q

COMPARING FOR AND FOR-EACH LOOPS

A

enhanced for-each loops are extremely convenient in a variety of circumstances.

standard for loop if you need fine-grained control.

28
Q

NESTED LOOPS

A

A nested loop is a loop that contains another loop including while, do/while, for, and for-each loops.

int[][] myComplexArray = {{5,2,1,3},{3,9,8,9},{5,7,12,7}};
for(int[] mySimpleArray : myComplexArray) {
    for(int i=0; i<mySimpleArray.length; i++) {
        System.out.print(mySimpleArray[i]+"\t");
    }
    System.out.println();
}

following output:
~~~
5 2 1 3
3 9 8 9
5 7 12 7
~~~

int hungryHippopotamus = 8;
while(hungryHippopotamus>0) {
    do {
        hungryHippopotamus -= 2;
    } while (hungryHippopotamus>5);
    hungryHippopotamus--;
    System.out.print(hungryHippopotamus+", ");
}

The result is that the code will output the following:
3, 0,

29
Q

ADDING OPTIONAL LABELS

A

Not on the exam 815</br>

A label is an optional pointer to the head of a statement that allows the application flow to jump to it or break from it. It is a single identifier that is proceeded by a colon (:).</br>

Labels follow the same rules for formatting as identifiers.
For readability, they are commonly expressed using uppercase letters, with underscores between words, to distinguish them from regular variables.

int[][] myComplexArray = {{5,2,1,3},{3,9,8,9},{5,7,12,7}};
OUTER_LOOP: for(int[] mySimpleArray : myComplexArray) {
    INNER_LOOP: for(int i=0; i<mySimpleArray.length; i++) {
        System.out.print(mySimpleArray[i]+"\t");
    }
System.out.println();
}

legal but bad example:

int frog = 15;
BAD_IDEA: if(frog>10)
EVEN_WORSE_IDEA: {
frog++;
}
30
Q

The structure of a break statement

A

break statement transfers the flow of control out to the enclosing statement.

optionalLabel: while () {
    // Body
    // Somewhere in the loop
    break optionalLabel;
}
  1. Optional reference to the head of the loop
  2. Colon (required if optionalLabel is present)
  3. break keyword
  4. semicolon (required)
31
Q
public class FindInMatrix {
    public static void main(String[] args) {
        int[][] list = {{1,13},{5,2},{2,2}};
        int searchValue = 2;
        int positionX = -1;
        int positionY = -1;
        PARENT_LOOP: for(int i=0; i<list.length; i++) {
            for(int j=0; j<list[i].length; j++) {
                if(list[i][j]==searchValue) {
                    positionX = i;
                    positionY = j;
                    break PARENT_LOOP;
                }
            }
        }
        if(positionX==-1 || positionY==-1) {
            System.out.println("Value "+searchValue+" not found");
        } else {
            System.out.println("Value "+searchValue+" found at: " + "("+positionX+","+positionY+")");
        }
    }
}
A

When executed, this code will output the following:
Value 2 found at: (1,1)

32
Q

The structure of a continue statement

A

continue statement transfers control to the boolean expression that determines if the loop should continue. In other words, it ends the current iteration of the loop. Also, like the break statement, the continue statement is applied to the nearest inner loop under execution using optional label statements to override this behavior.

optionalLabel: while () {
    // Body
    // Somewhere in the loop
    continue optionalLabel;
}
  1. Optional reference to the head of the loop
  2. Colon (required if optionalLabel is present)
  3. continue keyword
  4. semicolon (required)
33
Q
1: public class CleaningSchedule {
2:     public static void main(String[] args) {
3:         CLEANING: for(char stables = 'a'; stables<='d'; stables++) {
4:             for(int leopard = 1; leopard<4; leopard++) {
5:                 if(stables=='b' || leopard==2) {
6:                     continue CLEANING;
7:                 }
8:             System.out.println("Cleaning: "+stables+","+leopard);
9: } } } }
A

The following is printed:

Cleaning: a,1
Cleaning: c,1
Cleaning: d,1
34
Q
public class FindInMatrixUsingReturn {
    private static int[] searchForValue(int[][] list, int v) {
        for (int i = 0; i < list.length; i++) {
            for (int j = 0; j < list[i].length; j++) {
                if (list[i][j] == v) {
                    return new int[] {i,j};
                }
            }
        }
        return null;
    }

    public static void main(String[] args) {
        int[][] list = { { 1, 13 }, { 5, 2 }, { 2, 2 } };
        int searchValue = 2;
        int[] results = searchForValue(list,searchValue);
        if (results == null) {
            System.out.println("Value " + searchValue + " not found");
        } else {
            System.out.println("Value " + searchValue + " found at: " + "(" + results[0] + "," + results[1] + ")");
        }
    }
}
A

return statements can be used to exit loops quickly and can lead to more readable code in practice, especially when used with nested loops.

35
Q
int checkDate = 0;
while(checkDate<10) {
    checkDate++;
    if(checkDate>100) {
        break;
        checkDate++; // DOES NOT COMPILE
    }
}
A

the compiler notices that you have statements (checkDate++) immediately following the break and will fail to compile with “unreachable code” as the reason. The same is true for continue and return statements too

36
Q

UNREACHABLE CODE

A

the compiler will report an error if it finds any code it deems unreachable, in this case any statements immediately following a break, continue, or return statement.

int minute = 1;
WATCH: while(minute>2) {
    if(minute++>2) {
        continue WATCH;
        System.out.print(minute); // DOES NOT COMPILE
    }
}
int hour = 2;
switch(hour) {
    case 1: return; hour++; // DOES NOT COMPILE
    case 2:
}
37
Q

Advanced flow control usage

A
  1. while
    Allows optional labels
    Allows break statement
    Allows continue statement
  2. do/while
    Allows optional labels
    Allows break statement
    Allows continue statement
  3. for
    Allows optional labels
    Allows break statement
    Allows continue statement
  4. switch
    Allows optional labels
    Allows break statement
    Not Allows continue statement