Quiz 3
Quiz 3: If/Else and Loops
Question 1
Write a method definition in Java syntax that defines a method called larger of type int
that takes in two integers, a
, and b
, and returns the larger one.
Answer
Either of the following: ```java public static int larger(int a, int b) { if (a > b) { return a; } return b; } ``` ```java public static int larger(int a, int b) { if (a > b) { return a; } else { return b; } } ```Question 2
In a sentence or two, explain how these two pieces of code are different, and identify which one accurately reflects the behavior you would expect based on the print statements.
if (x) {
System.out.println("x is true");
}
System.out.println("x is false");
if (x) {
System.out.println("x is true");
} else {
System.out.println("x is false");
}
Answer
In the first case, `x is false` prints regardless of the truth value of `x`, while in the second case, it will only print if `x` is false. Therefore, the second case better represents the expected behavior.Question 3
What will the following loop output?
for (int i = 0; i < 5; i++) {
System.out.println(i + " : " + i+2)
}