Question:
Assume that class BankAccount exists, and that it has a constructor that sets the private field balance, and that setBalance and getBalance are defined by class BankAccount and set and get double values.
Then what is the output of the following code?
BankAccount b1 = new BankAccount(600.0);
BankAccount b2 = b1;
b1.setBalance(300.0);
System.out.println(b2.getBalance() );
Answer:
300.0
Step-by-step explanation:
The given snippet of code is as follows:
=======================================
BankAccount b1 = new BankAccount(600.0);
BankAccount b2 = b1;
b1.setBalance(300.0);
System.out.println(b2.getBalance() );
=======================================
Line 1: An object b1 of the BankAccount class is created which sets the value of its balance to 600.0
Line 2: A second object, b2, is created referencing or pointing to the first object, b1 in memory. It could also be interpreted to mean that a second object b2 is created from the exact copy of the first object, b1. This is called object cloning. This by implication means that all the fields (including the contents of the fields) of the first object b1, are copied to b2 which also means that when there's a change in b1, an update is made to b2 also. If a change is made to b2, b1 also gets updated.
Line 3: Object b1 is updated by setting the value of its balance field to 300.0 using the setBalance() method. This will also update the same field for the second object b2.
Line 4: The value of the balance field of object b2 is being printed to the console. Since the value has been updated in line 3 when that of b1 was updated, 300.0 will be printed to the console.