nerdexam
Oracle

1Z0-809 · Question #100

Given the code fragment class Test2 { int fvar; static int cvar; public static void main(String[] args) { Test2 t = new Test2(); // insert code here to write field variables } } Which code…

The correct answer is B. cvar = 400; t.fvar = 200. Option B compiles because both statements use valid access patterns in a static context: cvar = 400 directly references the static field by name (permitted within the same class's static method), and t.fvar = 200 accesses the instance field through an object reference, which is…

Question

Given the code fragment class Test2 { int fvar; static int cvar; public static void main(String[] args) { Test2 t = new Test2(); // insert code here to write field variables } } Which code fragments, inserted independently, enable the code compile?

Options

  • At.fvar = 200; cvar = 400;
  • Bcvar = 400; t.fvar = 200;
  • Cthis.fvar = 200; this.cvar = 400;
  • Dt.var = 200; Test2.cvar = 400;
  • Et.fvar = 200; Test2.cvar = 400;
  • Fthis.fvar = 200; Test2.cvar = 400;

How the community answered

(35 responses)
  • A
    3% (1)
  • B
    74% (26)
  • D
    9% (3)
  • E
    3% (1)
  • F
    11% (4)

Explanation

Option B compiles because both statements use valid access patterns in a static context: cvar = 400 directly references the static field by name (permitted within the same class's static method), and t.fvar = 200 accesses the instance field through an object reference, which is the required approach when no this keyword is available.

Why the distractors fail:

  • C and F both use this.fvar or this.cvar - this refers to the current instance, but main is a static method with no associated instance, so this is illegal here and causes a compile error.
  • D references t.var, which doesn't exist - the field is named fvar, not var, so this fails with a "cannot find symbol" error.
  • A is actually a trick: it's the same two statements as B, just in reverse order, so it also compiles - if the exam marks only B as correct, suspect a question flaw or that it expects multiple selections.
  • E (t.fvar = 200; Test2.cvar = 400;) also compiles, since accessing a static field via the class name is valid and idiomatic.

Memory tip: In a static method, ban this immediately (no instance exists), then ask yourself "how do I reach each variable?" - instance fields need an object reference (t.fvar), static fields can use the class name (Test2.cvar) or bare name within the same class (cvar). Any option with this in a static method is always wrong.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice