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

Data structures: java 5. What does the following program print out. Explain why.

ID: 3599980 • Letter: D

Question

Data structures: java

5. What does the following program print out. Explain why. class Thing f public int a; public public int b; Thing (int a, int b)(this,a-a; this.b-b} public class Test public static void f (Thing x, int y) x.a++ public static void main(String[] args) Thing x -new Thing(1,1); int y - 1; f(x, y); System . out. print1n("x. a " + x. a + " and x.b System.out.print 1n(" y = " + y) ; " + x. b) ; 6. Suppose that we have classes A, B, C and D. Suppose that B is a subclass of A, that C is a subclass of B, and D is a subclass of A. Suppose that we make the following declarations A a1 - new A); A a2 - new CO; For each part below, explain what, if any, errors would be caused by the statement in that part. Be sure to consider both compile time and run time errors (a) A a3 new B(); (b) B b1 = new A(); (c) B b2 = (B) al; (d) B b3 = (B) a2 ; (e) B b4 (B) dl; (f) B b5-(C) (A)new DO;

Explanation / Answer

5) Output

Explanation

class Thing
{
public int a;
public int b;
public Thing(int a, int b)
{
this.a = a;
this.b = b;
}
}

public class Main{
public static void f(Thing x, int y)
{
x.a++;
y++;
}
public static void main(String[] args)
{
Thing x = new Thing(1,1);
// By this time we have an object having values a = 1 and b = 1
  
int y = 1;
f(x,y);
// When it is called, value of a is incremented by 1. Hence a = 2 and b is still 1. Objects are taken as reference.
// y is also incremented by 1 but that was limited to the method only
  
System.out.println("x.a = "+x.a+" and x.b = "+x.b);
System.out.println("y = "+y);
}
}

  x.a = 2 and x.b = 1  y = 1