nerdexam
Oracle

1Z0-819 · Question #2

Given: public class DNASynth { int aCount; int tCount; int cCount; int gCount; void setACount(int cCount) { cCount = cCount; } void setTCount() { this.tCount = tCount; } int setCCount() { return…

The correct answer is A. setAllCounts C. setTCount. There is an error in the provided answer key. The correct answers should be A and E, not A and C. Here is why: setAllCounts (A) clearly modifies fields: the chain assignment aCount = tCount = this.cCount = setGCount(x) writes to three fields, and the call to setGCount(x) also…

Java Object-Oriented Approach

Question

Given: public class DNASynth { int aCount; int tCount; int cCount; int gCount; void setACount(int cCount) { cCount = cCount; } void setTCount() { this.tCount = tCount; } int setCCount() { return cCount; } int setGCount(int g) { gCount = g; return gCount; } void setAllCounts(int x) { aCount = tCount = this.cCount = setGCount(x); } } Which two methods modify field values? (Choose two.)

Options

  • AsetAllCounts
  • BsetACount
  • CsetTCount
  • DsetCCount
  • EsetGCount

How the community answered

(33 responses)
  • A
    79% (26)
  • B
    3% (1)
  • D
    12% (4)
  • E
    6% (2)

Explanation

There is an error in the provided answer key. The correct answers should be A and E, not A and C. Here is why:

  • setAllCounts (A) clearly modifies fields: the chain assignment aCount = tCount = this.cCount = setGCount(x) writes to three fields, and the call to setGCount(x) also writes to gCount.
  • setGCount (E) modifies gCount via gCount = g; - a straightforward field assignment. This is the most obvious example in the class.
  • setTCount (C) is a trap: this.tCount = tCount looks like a setter, but there is no parameter named tCount, so the right-hand side refers to the field itself. It is a self-assignment (this.tCount = this.tCount) and changes nothing.
  • setACount (B) is another trap: the parameter is named cCount, shadowing the field. The line cCount = cCount is a self-assignment of the local parameter - no field is touched.
  • setCCount (D) is a getter in disguise: despite the "set" prefix, it simply returns cCount and modifies nothing.

Memory tip: "set" in a method name means nothing in Java - always check whether the body actually assigns to a field (this.field = param). Watch for parameter shadowing (same name as field without this.) and missing parameters (nothing to assign with).

Topics

#variable shadowing#instance fields#this keyword#field modification

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice