nerdexam
Oracle

1Z0-803 · Question #145

Given: class Cake { int model; String flavor; Cake() { model = 0; flavor = "Unknown"; } } public class Test { public static void main(String[] args) { Cake c = new Cake(); bake1(c); System.out.println

The correct answer is C. 1200 Strawberry. This code demonstrates object modification via methods, where changes made to the object through a passed reference persist and are reflected in subsequent print statements.

Working with Methods and Encapsulation

Question

Given: class Cake { int model; String flavor; Cake() { model = 0; flavor = "Unknown"; } } public class Test { public static void main(String[] args) { Cake c = new Cake(); bake1(c); System.out.println(c.model + " " + c.flavor); bake2(c); System.out.println(c.model + " " + c.flavor); } public static Cake bake1(Cake c) { c.flavor = "Strawberry"; c.model = 1200; return c; } public static void bake2(Cake c) { c.flavor = "Chocolate"; c.model = 1230; return; } } What is the result?

Options

  • A0 Unknown
  • B1200 Strawberry
  • C1200 Strawberry
  • DCompilation fails

How the community answered

(26 responses)
  • A
    4% (1)
  • B
    8% (2)
  • C
    77% (20)
  • D
    12% (3)

Why each option

This code demonstrates object modification via methods, where changes made to the object through a passed reference persist and are reflected in subsequent print statements.

A0 Unknown

The constructor initializes `model` to 0 and `flavor` to 'Unknown', but these values are modified by the `bake1` method before the first print statement.

B1200 Strawberry

This choice is textually identical to the correct answer C, but C is specified as the correct option.

C1200 StrawberryCorrect

After `bake1(c)` is called, the `model` and `flavor` of the `Cake` object `c` are updated to 1200 and 'Strawberry' respectively, making the first print statement output '1200 Strawberry'.

DCompilation fails

The code is syntactically correct and will compile without errors as `bake2` correctly declares `void` for no return value.

Concept tested: Java object pass by reference, mutability

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

Topics

#pass by value#object references#method parameters

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice