<h2>Question:</h2>
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() );
<h2>
Answer:</h2>
300.0
<h2>
Explanation:</h2>
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() );
=======================================
<u><em>Line 1</em></u>: An object b1 of the BankAccount class is created which sets the value of its <em>balance </em> to 600.0
<u><em>Line 2</em></u>: A second object, <em>b2</em>, is created referencing or pointing to the first object, <em>b1 </em>in memory. It could also be interpreted to mean that a second object <em>b2</em> is created from the exact copy of the first object, b1. This is called <em>object cloning</em>. 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.
<u><em>Line 3</em></u>: Object <em>b1</em> is updated by setting the value of its <em>balance</em> field to 300.0 using the setBalance() method. This will also update the same field for the second object <em>b2.</em>
<em />
<u><em>Line 4</em></u>: The value of the <em>balance</em> 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, <em>300.0</em> will be printed to the console.
<em />
<em />