nerdexam
Oracle

1Z0-811 · Question #10

Given the code fragment: class Course { String name; static int count = 0; Course(String name) { this.name = name; count++; } } public class App { public static void main(String[] args) { Course c =…

The correct answer is C. System.out.println(c.name + ":" + Course.count). Option C works because c.name correctly accesses the instance variable through an object reference, and Course.count correctly accesses the static variable through the class name - the canonical and unambiguous way to reference statics in Java. Option A fails because name and…

Object-Oriented Programming Principles

Question

Given the code fragment: class Course { String name; static int count = 0; Course(String name) { this.name = name; count++; } } public class App { public static void main(String[] args) { Course c = new Course("Java Programming"); // line n1 } } Which code fragment, when inserted at line n1, enables the code to print Java Programming:1?

Options

  • ASystem.out.println(name + ":" + count);
  • BSystem.out.println(c.name + ":" + count);
  • CSystem.out.println(c.name + ":" + Course.count);
  • DSystem.out.println(Course.name + ":" + c.count);

How the community answered

(41 responses)
  • A
    10% (4)
  • B
    2% (1)
  • C
    80% (33)
  • D
    7% (3)

Explanation

Option C works because c.name correctly accesses the instance variable through an object reference, and Course.count correctly accesses the static variable through the class name - the canonical and unambiguous way to reference statics in Java.

Option A fails because name and count are bare identifiers with no class or object context; they are not in scope inside main, which is a method of App, not Course.

Option B fails for the same scoping reason: count alone is not resolvable inside main - you need either a class prefix (Course.count) or an object reference to reach it.

Option D fails because name is an instance variable (not static), so Course.name won't compile - you can only access instance members through an object, never through the class name directly.

Memory tip: Match the modifier to the accessor - static → ClassName.member, instance → objectRef.member. If you mix them (class name for instance, or bare name from outside the class), the compiler rejects it.

Topics

#static variables#instance variables#member access#class vs instance scope

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice