nerdexam
Oracle

1Z0-803 · Question #227

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. The code demonstrates how object references are passed by value in Java, allowing methods to modify the state of the original object.

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

(30 responses)
  • A
    17% (5)
  • B
    3% (1)
  • C
    70% (21)
  • D
    10% (3)

Why each option

The code demonstrates how object references are passed by value in Java, allowing methods to modify the state of the original object.

A0 unknown

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

B1200 Strawberry

This option is identical to option C and represents the correct output after the first method call, indicating the question likely expects this specific print output.

C1200 StrawberryCorrect

When bake1(c) is called, the reference to the Cake object is passed by value. Inside bake1, the original object's flavor is set to 'Strawberry' and model to 1200. The first System.out.println then prints these updated values.

DCompilation fails

The code is syntactically correct and will compile without errors, as method signatures and return statements are valid.

Concept tested: Java object pass-by-value of references, object state modification

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

Topics

#object state#constructors#method calls#object references

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice