1Z0-811 · Question #6
Given the code fragment: 1. class App { 2. 3. } Which two code fragments are valid at line 2?
The correct answer is B. package p1. There appears to be an error in the listed correct answer - B (package p1;) is actually invalid at line 2, because package declarations must appear as the very first statement in a .java file, before any class declaration. Placing it inside a class body causes a compile error…
Question
- class App {
- }
Options
- Afor (int count = 0; count < 5; count++) { System.out.print(count); }
- Bpackage p1;
- Cimport java.util.*; public void display() { List<Integer> nums = new ArrayList<>(); }
- Dprivate int num;
How the community answered
(21 responses)- A5% (1)
- B95% (20)
Explanation
There appears to be an error in the listed correct answer - B (package p1;) is actually invalid at line 2, because package declarations must appear as the very first statement in a .java file, before any class declaration. Placing it inside a class body causes a compile error.
The genuinely valid fragment at line 2 (inside the class body) is D: private int num; - a field declaration, which is perfectly legal directly within a class body.
Why the other options fail:
- A - A bare
forloop is a statement, and statements can only live inside methods, constructors, or initializer blocks - not directly in a class body. - C -
import java.util.*;is a file-level directive; it cannot appear inside a class body. The method declaration following it would be fine on its own, but the combined fragment is invalid. - B - As noted,
packagedeclarations belong at the top of the source file, before any class declaration, not inside one.
Memory tip: Think of a Java source file as three zones stacked top-to-bottom - package → imports → class body. Each zone is strictly ordered; you cannot "reach back up" from inside a class to place package or import statements. Only members (fields, methods, constructors, nested types) live inside the braces.
Note for exam takers: If your source lists B as correct, flag it - this question likely contains an error. The correct single valid answer here is D.
Topics
Community Discussion
No community discussion yet for this question.