Problem 1
Accumulator With Conditional
What is printed when the following code executes?
int[] vals = {3, 7, 2, 8, 5, 1};
int result = 0;
for (int i = 0; i < vals.length; i++)
{
if (vals[i] > 4)
{
result += vals[i];
}
}
System.out.println(result);
Only values greater than 4 are added: 7 + 8 + 5 = 20. Values 3, 2, and 1 are skipped by the condition.
Problem 2
In-Place Modification
What does the array contain after this code executes?
int[] data = {10, 20, 30, 40, 50};
for (int i = 0; i < data.length - 1; i++)
{
data[i] = data[i + 1];
}
// What is data now?
Each element is replaced by the one to its right. The last element (50) is never overwritten because the loop stops at
length - 1. This is a left-shift pattern.Problem 3
Swap Adjacent Pairs
What does the array contain after execution?
int[] arr = {1, 2, 3, 4, 5, 6};
for (int i = 0; i < arr.length - 1; i += 2)
{
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
// What is arr now?
The loop increments by 2, swapping pairs: (1,2) becomes (2,1), (3,4) becomes (4,3), (5,6) becomes (6,5).
Problem 4
Nested Condition With Count
What is printed?
int[] scores = {85, 92, 78, 95, 88, 76, 91};
int count = 0;
for (int k = 0; k < scores.length; k++)
{
if (scores[k] >= 90)
{
count++;
}
}
System.out.println(count);
Values >= 90: 92, 95, 91. Three elements meet the condition.
Problem 5
Reverse Traversal With String Building
What is printed?
String[] letters = {"A", "B", "C", "D"};
String result = "";
for (int i = letters.length - 1; i >= 0; i--)
{
result += letters[i];
}
System.out.println(result);
The loop starts at the last index (3) and decrements to 0, concatenating each element in reverse order.
Want More Exam-Level Practice?
The 4-Week Cram Kit includes daily trace drills for every unit.
Get the Cram Kit — $29.99 1-on-1 TutoringProblem 6
Aliasing Trace
What is printed?
int[] x = {5, 10, 15};
int[] y = x;
y[1] = 99;
System.out.println(x[1]);
y = x makes both variables point to the same array. Changing y[1] also changes x[1]. This is aliasing.Problem 7
Find Index of Minimum
What is printed?
int[] nums = {14, 7, 23, 3, 18};
int minIdx = 0;
for (int i = 1; i < nums.length; i++)
{
if (nums[i] < nums[minIdx])
{
minIdx = i;
}
}
System.out.println(minIdx + " " + nums[minIdx]);
The minimum value is 3 at index 3. The loop finds the index, not the value — a common exam distinction.