nerdexam
Oracle

1Z0-811 · Question #13

Given the code fragment: class Ball { double weight; } public class App { public static void main (String[] args) { //line n1 } } Which code fragment can be inserted at line n1 to enable the code to…

The correct answer is D. Ball b = new Ball(). Option D works because Java automatically provides a default no-argument constructor when no constructor is explicitly defined. When new Ball() is called, the instance field weight (a double) is automatically initialized to 0.0 - Java's default value for all double fields…

Object-Oriented Programming Principles

Question

Given the code fragment: class Ball { double weight; } public class App { public static void main (String[] args) { //line n1 } } Which code fragment can be inserted at line n1 to enable the code to print 0.0?

Options

  • ABall b = null; b.weight = 0.0;
  • BBall.weight = 0.0;
  • CBall b = new Ball(0.0);
  • DBall b = new Ball();

How the community answered

(18 responses)
  • C
    6% (1)
  • D
    94% (17)

Explanation

Option D works because Java automatically provides a default no-argument constructor when no constructor is explicitly defined. When new Ball() is called, the instance field weight (a double) is automatically initialized to 0.0 - Java's default value for all double fields - making it printable.

Why the distractors fail:

  • A declares b as null then immediately dereferences it (b.weight), causing a NullPointerException at runtime - nothing prints.
  • B treats weight as a static field using Ball.weight, but it's an instance field; this is a compile error.
  • C calls new Ball(0.0), but no constructor accepting a double exists in Ball; this is also a compile error.

Memory tip: When a Java class has no explicit constructor, the compiler silently adds one - ClassName() with no args. Primitive instance fields (int, double, boolean, etc.) always get zero-equivalent defaults (0, 0.0, false) upon object creation. If you see new ClassName() with no args and no constructor defined, it compiles and zeroes out the fields.

Topics

#object instantiation#instance variables#default values#constructors

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice