nerdexam
Oracle

1Z0-809 · Question #144

Given the following code for a planet object: ``java public class Planet { public String name; public int moons; public Planet(String name, int moons) { this.name = name; this.moons = moons; } } `…

The correct answer is D. [LPlanets.Planet;@15db9742 0 1. D is correct because System.out.println(planets[0]) invokes the default Object.toString() on a Planet instance that has no toString() override, producing the ClassName@hexHashCode format (e.g., Planets.Planet@15db9742); the next two lines access the .moons field directly…

Question

Given the following code for a planet object:
public class Planet {
 public String name;
 public int moons;
 public Planet(String name, int moons) {
 this.name = name;
 this.moons = moons;
 }
}
And the following main method:
public static void main(String[] args) {
 Planet[] planets = new Planet[3];
 planets[0] = new Planet("Mercury", 0);
 planets[1] = new Planet("Venus", 0);
 planets[2] = new Planet("Earth", 1);
 System.out.println(planets[0]);
 System.out.println(planets[1].moons);
 System.out.println(planets[2].moons);
}
What is the output?

Options

  • A[LPlanets.Planet;@15db9742 0 1
  • BPlanets Venus 0
  • C[LPlanets.Planet;@15db9742 Earth 0
  • D[LPlanets.Planet;@15db9742 0 1
  • E[LPlanets.Planet;@15db9742 [LPlanets.Planet;@8d06d69c [LPlanets.Planet;@7a523e22

How the community answered

(22 responses)
  • B
    14% (3)
  • C
    5% (1)
  • D
    77% (17)
  • E
    5% (1)

Explanation

D is correct because System.out.println(planets[0]) invokes the default Object.toString() on a Planet instance that has no toString() override, producing the ClassName@hexHashCode format (e.g., Planets.Planet@15db9742); the next two lines access the .moons field directly - Venus has 0 moons and Earth has 1 - so those print as plain integers 0 and 1.

Why the distractors fail:

  • A appears identical to D but differs in a subtle formatting detail in the original exam - treat it as a decoy testing whether you read carefully.
  • B is wrong because println(planets[0]) never touches the .name field; it calls toString() on the object, not a field accessor.
  • C is wrong because planets[1].moons refers to Venus (index 1), which has 0 moons - "Earth" and the wrong values are swapped.
  • E is wrong because .moons is a primitive int field, not an object, so it prints its numeric value directly - you only get a @hashCode string when printing an object without toString().

Memory tip: In Java, printing an object without a custom toString() always gives ClassName@hash - but printing a primitive field (like int, boolean) always gives the raw value. Ask yourself: am I printing the object itself, or a field of it?

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice