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

Question.1 What is printed by the code fragment below? Rectangle r = new Rectang

ID: 3792744 • Letter: Q

Question

Question.1

What is printed by the code fragment below?

Rectangle r = new Rectangle(10, 10);
int n = 4;
shrink(r);
shrink( n );
System.out.print(r.getWidth() + "" + r.getHeight() + "" + n);

public void shrink(Rectangle rec) {

int newWidth = (int) rec.getWidth()/2;
int newHeight = (int) rec.getHeight()/2;
rec .setSize(newWidth, newHeight);

}
public void shrink(int q) {

q = q / 2;

}

Question.2

What is printed by the code fragment below?

Rectangle r = new Rectangle(10, 10);
int n = 4;
shrink(r);
shrink( n );
System.out.print(r.getWidth() + "" + r.getHeight() + "" + n);

public void shrink(Rectangle rec) {

rec = new Rectangle(2,2);
int newWidth = (int) rec.getWidth()/2;
int newHeight = (int) rec.getHeight()/2;
rec.setSize(newWidth, newHeight);

}
public void shrink(int q) {

q = q / 2;

}

Explanation / Answer

I had commented the code with the explanations :

answer 1 : 554 (since there is no space between values)

Rectangle r = new Rectangle(10, 10);
int n = 4;
shrink(r);
shrink( n );
System.out.print(r.getWidth() + "" + r.getHeight() + "" + n); // 5 5 4

public void shrink(Rectangle rec) { //this method will get the reference of Rectangle object as parameter

int newWidth = (int) rec.getWidth()/2; //divide the width & height values by 5
int newHeight = (int) rec.getHeight()/2;
rec .setSize(newWidth, newHeight); // set the value of new height & width to the object

//the value set here is reflected to the object r

}
public void shrink(int q) { //this method will divide the value of lccal variable q by 2 and save it.

q = q / 2; //but this value change will not reflected back as it is method call by value

}

answer 2 : 10104 since there is no space in between values (10 10 4).

there is no difference between the code of question 1 and 2 except :   rec = new Rectangle(2,2);

public void shrink(Rectangle rec) {

rec = new Rectangle(2,2); // the reference variable rec is initialized with new object
int newWidth = (int) rec.getWidth()/2;
int newHeight = (int) rec.getHeight()/2;
rec.setSize(newWidth, newHeight);

}

since the reference varible rec is allocated a new object with height and width 2,2. now whatever be the changes done in the code, it will change the new object. It wont reflect in the Rectangle object referenced by r

feel free to ask if you have any doubts :)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote