nerdexam
Oracle

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…

Java Basics

Question

Given the code fragment:
  1. class App {
  2. }
Which two code fragments are valid at line 2?

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)
  • A
    5% (1)
  • B
    95% (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 for loop 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, package declarations 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

#Java file structure#Code placement rules#Package/import declarations#Class members

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice