Java control flow quiz

  • Admin
  • 1 min read

Nine questions on if, switch, loops and arrays.

Java

Java control flow quiz

9 questions, instant feedback

Question 1 of 9
Question 1 of 9 Which condition is valid in an if statement?
Why this is the answer

Java requires a boolean expression in parentheses. An int does not convert to boolean, and = is assignment.

Question 2 of 9
Question 2 of 9 What does else if allow?
Why this is the answer

Each else if is checked only when the previous conditions were false, which makes the branches exclusive.

Question 3 of 9
Question 3 of 9 Which switch type is allowed in modern Java?
Why this is the answer

switch works with integers, enums, strings and a few other types, but not double or boolean.

Question 4 of 9
Question 4 of 9 What happens when a switch case has no break?
Why this is the answer

Without break, control continues into the following case. Arrow-style switch avoids the problem.

Question 5 of 9
Question 5 of 9 How many times does for (int i = 0; i < 3; i++) run?
Why this is the answer

i takes the values 0, 1 and 2, so the body runs three times.

Question 6 of 9
Question 6 of 9 What is the difference between while and do-while?
Why this is the answer

A do-while body always runs once, because the condition is tested at the end.

Question 7 of 9
Question 7 of 9 What does an array of int default to when created with new int[5]?
Why this is the answer

Array elements are initialised to the type's default: 0 for int, false for boolean, null for objects.

Question 8 of 9
Question 8 of 9 What is the valid index range for new int[4]?
Why this is the answer

Java arrays are zero-indexed, so four elements are at indexes 0, 1, 2 and 3. Index 4 throws.

Question 9 of 9
Question 9 of 9 Which loop is best when the number of items is known?
Why this is the answer

A for loop puts the counter's start, condition and step in one line, which reads well for a known count.

Your answers stay in this browser. Nothing is sent to a server.