Consider the follwing code:
class Box {
int size;
Box(int s) {
size = s;
}
}
public class Laser {
public static void main(String[] args) {
Box b1 = new Box(5);
Box[] ba = go(b1, new Box(6));
ba[0] = b1;
for (Box b : ba) {
System.out.print(b.size + " ");
}
}
static Box[] go(Box b1, Box b2) {
b1.size = 4;
Box[] ma = {b2, b1};
return ma;
}
}
What is the result?
i solved it to be 5 4 but it’s not the right one, the right answer is 4 4, how that come?
The
gomethod changes the size of yourb1box to 4, and places it at index 1 in the array. Then the main method also sets it at index 0. So the array contains two references tob1, whose size is 4.