Java 11 Certification Practice Questions (Answers below)
Topic: Controlling Program Flow
Create and use loops, if/else, and switch statements
Q1. Which of the following options can be inserted within the main() method for the output to be 1234?
public static void main(String[] args) {
int[] nums = { 1, 2, 3, 4 };
// insert code
}
Choices
A. for (var i : nums) { System.out.print(i); }
B. for (int i : nums) { if(i<nums.length) System.out.print(i); }
C. for (int i=0; i<=nums.length; ++i) { System.out.print(nums[i]); }
D. for (int j=0,i=j; i<=nums.length-1; i++) { System.out.print(nums[i]); }
Answer
A and D are correct. In these two cases, the for loop correctly iterates the array and prints 1234. B is incorrect because only 123 is printed. C is incorrect because it causes ArrayIndexOutOfBoundsException.
Reference
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html