Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the following program in Java: class T{ A foo(B c, A d){ 5 c = new B();

ID: 3712982 • Letter: C

Question

Consider the following program in Java:

class T{

A foo(B c,  A d){

5          c = new B();      // The address of this object is 0x00000037

6          c.intField = 23;         

7          d.bField =c;

8          return d;

}

}

class A {

    public B bField;

}

class B{

public int  intField;

   public void main(String[] args){

1          T t = new T();   // Suppose the heap address of the object is 0x00000012

2          A a = new A(); // The address of this object is 0x00000025

3          B b = null;

4          A m =  t.foo(b,  a);

9          Systems.out.println(a.bField.intField);

        return;

  }

}

1.We all know that Java is a call-by-value language. Write down the values of the variables t, a, b, m, c, d at each indexed program point as well as the final output (i.e., the value printed in line 9).

2.Now let’s pretend that Java is a call-by-reference language. Write down the values of these six variables at each program point as well as the final output.

An example solution:

1  t: 0x00000012, a: ?, b: ?, m: ?, c: ?, d?,  final output: ?     (? means the value is unknown.)

2  t: 0x00000012, a: 0x00000025, b: ?, m: ?, c: ?, d?

3  …

4 …

5 …

6 …

7 …

8 …

9 …

Explanation / Answer

ans 1. t:T@0x00000012, a:A@0x00000025 , b: null, m:A@0x00000025 , c: B@0x00000037, d:A@0x00000025 ,  final output: 23

ans 2.The output will be an exception refer to the explanation. the flow will look like below.

t:T@0x00000012, a:A@0x00000025 , b: null, m:A@0x00000025 ,  c: B@0x00000037, d:null ,  final output: exception (Program will terminate).

Explanation:- for the second option assuming that if Java is a call-by-reference language and we are passing the the reference to the constructor A foo(B c,  A d) then instance c and instance d will be having the reference of instances b and a, which is the address at stack. Now if we are not assigning any heap memory i.e, we are not creating an object using 'new' keyword then our program wil end up with an exception for the above program we are allocating the heap memory for instance 'c' at line 5 but not for the instance d. so our program will end up with an exception(The local variable d may not have been initialized).