K-12 CS Teacher Professional Development Workshop
1.) What does this program print?
public static void main(String[] args) {
int a = 4;
int b = 2;
int e = 4;
int g = 3;
if (a <= b) {
b = a;
}
g = e;
a = b;
System.out.println((a + b) + "" + e + g);
}
a. 844
b. 444
c. 644
d. 443
e. 16
B is the correct option because the if statement does not run, g which was 3 becomes e which was 4 making both g and e 4. Then, a, which was 4, becomes b, which was 2, making both a and b equal to 2. Then, the print statement follows order of operations. The parentheses means that a and b add together to add 2, then from left to right, they are concatenated to become a string, and then they add to e and g as strings to make "444" as the print output.
2.) What does this program output?
public static void main(String[] args) {
boolean g = true;
long a = 2;
short num = 3;
if (g == true) {
System.out.println(a + 2 + num);
}
else {
System.out.println(a + num);
}
}
a. 5
b. 9
c. 7
d. 7
5
e. 7true
C is the correct option. The if statement checks if g is true. Because this condition is satisfied, then a + 2 + num executes adding 2 + 2 + 3 which equals 7. The else statement is then skipped because it only is executed if the if statement is not executed. Thus, the only output is 7.