nerdexam
Oracle

1Z0-803 · Question #130

Given the code fragment: Which two code fragments, inserted independently, enable the code to compile?

The correct answer is A. t.fvar = 200; D. t.fvar = 200;. To assign a value to an instance variable fvar of an object t, accessing it directly through the object reference t.fvar is a valid method.

Java Basics

Question

Given the code fragment:

Which two code fragments, inserted independently, enable the code to compile?

Exhibit

1Z0-803 question #130 exhibit

Options

  • At.fvar = 200;
  • Bfvar = 200;
  • Cthis.fvar = 200;
  • Dt.fvar = 200;
  • Ethis.fvar = 200;

How the community answered

(34 responses)
  • A
    71% (24)
  • B
    3% (1)
  • C
    18% (6)
  • E
    9% (3)

Why each option

To assign a value to an instance variable `fvar` of an object `t`, accessing it directly through the object reference `t.fvar` is a valid method.

At.fvar = 200;Correct

The code fragment `t.fvar = 200;` correctly assigns the value 200 to the instance variable `fvar` of the object referenced by `t`. This is the standard way to access and modify an instance variable of a specific object, particularly from a static context or from outside the object's immediate scope.

Bfvar = 200;

`fvar = 200;` attempts to access `fvar` directly without an object reference. This would only compile if `fvar` were a static variable or if the assignment was within a non-static method of the class defining `fvar` without explicit object reference.

Cthis.fvar = 200;

`this.fvar = 200;` attempts to assign to `fvar` using the `this` keyword. The `this` keyword refers to the current object instance and can only be used within a non-static context, such as a non-static method or constructor.

Dt.fvar = 200;Correct

The code fragment `t.fvar = 200;` is identical to option A and also correctly assigns the value 200 to the instance variable `fvar` of the object referenced by `t`.

Ethis.fvar = 200;

`this.fvar = 200;` is identical to option C and attempts to assign to `fvar` using the `this` keyword, which is only valid within a non-static context.

Concept tested: Accessing instance variables

Source: https://docs.oracle.com/javase/tutorial/java/javaOO/variables.html

Topics

#instance variables#object reference#field access#compilation errors

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice