nerdexam
Oracle

1Z0-811 · Question #8

Given the code fragment: //line n1 public class App { public static void main(String[] args) { List<Double> nums = new ArrayList<>(); nums.add(Math.PI); nums.add(new Random().nextDouble()); } }…

The correct answer is B. The code compiles successfully. Note: There appears to be an error in this answer key - B is not actually correct. Without any import statements, this code would fail to compile because List, ArrayList, and Random all live in java.util, which is not automatically imported. D is the correct answer. Adding…

Java Basics

Question

Given the code fragment: //line n1 public class App { public static void main(String[] args) { List<Double> nums = new ArrayList<>(); nums.add(Math.PI); nums.add(new Random().nextDouble()); } } Which statement is true?

Options

  • AThe code results in a compilation error. To make it compile, insert at line n1: import java.lang.Math; import java.lang.Random; import java.util;
  • BThe code compiles successfully
  • CThe code results in a compilation error. To make it compile, insert at line n1: import java.lang; import java.util;
  • DThe code results in a compilation error. To make it compile, insert at line n1: import java.util.*;

How the community answered

(39 responses)
  • A
    3% (1)
  • B
    92% (36)
  • D
    5% (2)

Explanation

Note: There appears to be an error in this answer key - B is not actually correct. Without any import statements, this code would fail to compile because List, ArrayList, and Random all live in java.util, which is not automatically imported.

D is the correct answer. Adding import java.util.*; at line n1 resolves all three missing types (List, ArrayList, Random), while Math requires no import because it belongs to java.lang, the one package Java automatically imports in every program.

Why each distractor fails:

  • A is wrong on two counts: java.lang.Math doesn't need importing (auto-imported), and Random is in java.util, not java.lang. Also, import java.util; is invalid syntax - you cannot import a package name directly.
  • B (stated as correct, but wrong) - the code as written lacks the required java.util imports and will produce compilation errors.
  • C uses invalid import syntax: import java.lang; and import java.util; are not legal Java - you must specify either a class (import java.util.List;) or use a wildcard (import java.util.*;).

Memory tip: "Only java.lang gets a free pass." Everything else - including the commonly used java.util types like List, ArrayList, HashMap, and Random - must be explicitly imported. When you see ArrayList or Random with no imports, expect a compile error.

Topics

#imports#java.lang#java.util#package visibility

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice