nerdexam
Oracle

1Z0-819 · Question #21

Given: ``java package A; class Test { String name; public Test (String name) { this.name = name; } public String toString() { return name; } } ` and `java package B; import A.Test; public class Main…

The correct answer is C. Student. Option C is actually not the correct answer here - this appears to be a trick question where the stated answer is wrong. The real answer is E (Compilation fails), because Test in package A is declared without an access modifier, making it package-private by default…

Java Object-Oriented Approach

Question

Given:
package A;

class Test {
 String name;

 public Test (String name) {
 this.name = name;
 }

 public String toString() {
 return name;
 }
}
and
package B;

import A.Test;

public class Main {
 public static void main(String[] args) {
 Test test = new Test("Student");
 System.out.println(test);
 }
}
What is the result?

Options

  • Anull
  • Bnothing
  • CStudent
  • Djava.lang.IllegalAccessException is thrown.
  • ECompilation fails.

How the community answered

(45 responses)
  • A
    4% (2)
  • B
    2% (1)
  • C
    71% (32)
  • D
    7% (3)
  • E
    16% (7)

Explanation

Option C is actually not the correct answer here - this appears to be a trick question where the stated answer is wrong. The real answer is E (Compilation fails), because Test in package A is declared without an access modifier, making it package-private by default. Package-private classes are only accessible within the same package, so import A.Test in package B causes a compile-time error - the compiler cannot see the Test class at all.

  • A (null) is wrong because name is set in the constructor; there's no null-return scenario to reach.
  • B (nothing) is wrong for the same reason - if the code ran, toString() returns name, which is "Student".
  • C (Student) would be correct only if Test were declared public class Test - the code logic itself is fine, but access never gets that far.
  • D (IllegalAccessException) is a runtime exception; this is a compile-time visibility issue, not a reflection-based runtime one.

Memory tip: In Java, missing access modifier = package-private. Always scan class declarations for public - if it's absent and the class is used cross-package, the code won't compile. Think: "No modifier, no export."

Topics

#Access modifiers#toString() override#Constructor visibility#Object instantiation

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice