1Z0-811 Primitives, Strings and Operators Practice Question
An integer counter variable is incremented in a loop that runs 3 billion times. Initially counter = 0. After the loop, the value is printed. Which code snippet correctly handles potential overflow?
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
✓
long counter = 0; for(long i=0; i<3000000000L; i++) counter++; System.out.println(counter);
Uses a long variable, which can hold the value up to 9e18, avoiding overflow. Options A and B use int and will silently overflow because 3e9 exceeds Integer.MAX_VALUE (2.147e9). Option C uses Math.addExact, which throws an ArithmeticException on overflow; while this detects overflow, the question asks for handling it gracefully, and using a long is the proper approach.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✗
int counter = 0; for(int i=0; i<3000000000L; i++) counter++; System.out.println(counter);
Why it's wrong here
int overflows at around 2.1e9.
- ✗
int counter = 0; for(int i=0; i<3000000000L; i++) counter += 1; System.out.println(counter);
Why it's wrong here
Same overflow issue as A.
- ✗
int counter = 0; for(int i=0; i<3000000000L; i++) counter = Math.addExact(counter, 1); System.out.println(counter);
Why it's wrong here
Throws exception on overflow, not graceful.
- ✓
long counter = 0; for(long i=0; i<3000000000L; i++) counter++; System.out.println(counter);
Why this is correct
long can hold 3e9 without overflow.
Go deeper
Related to this question
About these practice questions
This 1Z0-811 question is part of Courseiva's 481-question bank — original exam-style content with full explanations and wrong-answer analysis, never real exam questions or exam dumps. Learn why practice questions differ from exam dumps →
JA
Written by Johnson Ajibi, MSc IT Security
Senior Network & Security Engineer · founder of Courseiva
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.