Lab 4: Conditionals & Stack Diagrams
Objectives
The main goals for this lab are:
-
Practice drawing stack diagrams.
-
Practice reading code and evaluating logical expressions.
1. Stack Diagrams
For each of the follow programs, draw a stack diagram to trace out what happens as the program executes.
1.1 Add
class Add {
public static int add(int a, int b) {
int result = a + b;
return result;
}
public static void main(String[] args) {
int a = 4;
int b = 8;
int c = add(b, a);
System.out.println(a + " + " + b + " = " + c);
}
}
Draw the stack diagram below.
1.2 Add2
class Add2 {
public static int add(int a, int b) {
a = 2;
int result = a + b;
return result;
}
public static void main(String[] args) {
int a = 4;
int b = 8;
int c = add(a, b);
System.out.println(a + " + " + b + " = " + c);
}
}
Draw the stack diagram below.
TODO: Show Prof. Shiptoski your work before continuing on to the next section. ---
2. Expressions
For each expression, write down the value of the expression, and the date type of the expression.
int x = 5;
int y = 13;
int z = 15;
String message = "cat!";
boolean Done = false;
1: (x < 10) && (y < 10)
Answer:
2: (x < 10) || (y < 10)
Answer:
3: (x < 10) && (x > 0)
Answer:
4: (x > 10) || (x < 0)
Answer:
5: (5 / x) > 7.0
Answer:
6: (z / 2) > 7.0
Answer:
7: message.compareTo(“cats”) == 0
Answer:
8: !Done
Answer:
9: Done || (x < 6 && y > 10)
Answer:
TODO: Show Prof. Shiptoski your work before continuing on to the next section.
3. Colors
Consider the following code.
String colorName = "purple";
if (colorName.compareTo("red") != 0) {
System.out.println(colorName + " is not primary");
} else if (colorName.compareTo("blue") != 0 {
System.out.println(colorName + " is not primary");
} else if (colorName.compareTo("yellow") != 0) {
System.out.println(colorName + " is not primary");
} else {
System.out.println(colorName + " is primary");
}
1: What does the above code print out when colorName = "purple"?
Answer:
2: What does the above code print out when colorName = "red"?
Answer:
3: What does the above code print out when colorName = "yellow"?
Answer:
TODO: Show Prof. Shiptoski your work and then you are all done with lab 4.