Question 325 of 481
1Z0-811 Arrays and Methods Practice Question
A developer writes a method that accepts an array and returns the sum of all elements. Which implementation is correct if the array might be null?
⚠ Common exam trap
The trap here is that candidates often focus on handling an empty array (length 0) but forget to handle a null array, leading them to choose Option A or D, which fail with a NullPointerException.
Answer choices
Why each option matters
Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.
Correct answer & explanation
✓
public int sum(int[] arr) { if (arr == null) return 0; int s=0; for (int n:arr) s+=n; return s; }
It explicitly checks for a null array before attempting to access its length or iterate over its elements. In Java, accessing `arr.length` or using an enhanced for loop on a null reference throws a `NullPointerException`. By returning 0 for null input, the method gracefully handles the edge case without crashing.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✗
public int sum(int[] arr) { if (arr.length==0) return 0; int s=0; for (int n:arr) s+=n; return s; }
Why it's wrong here
Does not handle null; arr.length throws NullPointerException.
- ✓
public int sum(int[] arr) { if (arr == null) return 0; int s=0; for (int n:arr) s+=n; return s; }
Why this is correct
Correctly handles null and empty arrays.
- ✗
public int sum(int[] arr) { try { int s=0; for (int n:arr) s+=n; return s; } catch(NullPointerException e) { return -1; } }
Why it's wrong here
Uses exceptions for flow control, which is inefficient and bad practice.
- ✗
public int sum(int[] arr) { int s=0; for (int n:arr) s+=n; return s; }
Why it's wrong here
Throws NullPointerException if arr is null.
About these practice questions
Courseiva creates original exam-style practice questions with explanations and wrong-answer analysis. It does not publish real exam questions, exam dumps, or protected exam content. Learn why practice questions differ from exam dumps →
Last reviewed: Jul 4, 2026
This 1Z0-811 practice question is part of Courseiva's free Oracle certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the 1Z0-811 exam.
Question Discussion
Share a tip, memory trick, or ask about the reasoning behind this question. Do not post real exam questions, leaked content, braindumps, or copyrighted exam material. Comments are moderated and may be removed without notice.
Sign in to join the discussion.