Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Result of self test question on K & B studyguide chapter 3 pg 285, question 12.

 
Harold Ndou
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 Bo(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 the result?
A. 4 4
B. 5 4
C. 6 4
D. 4 5
E. 5 5
F. Compalition fails
The anwer is A
Am having hard time trying to understand the results of this code, can anyone explain the results to me. I will apprecite your assistance.
 
Himai Minh
Ranch Hand
Posts: 1296
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


How it works:
1. b1 refers to object in line a
2. go is invoked. The object in line a has a new size=4. The result is an array with the object in line b (size = 6) and the object in line a (size = 4).
3. Now, the result's 0th element is refering to the object in line a(size = 4)
4. The array is refering to the object in line a (size = 4) and the object in line a (size =4).
5. That is why it prints out 4 and 4.

The objective of this question is to test object reference in an array.

 
Harold Ndou
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks so much, i got some light, but still dont understand this line: for (Box b : ba) System.out.print(b.size + " ");

Why it print double 4 4?
 
Jeff Levine
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're looking for an explanation on the enhanced for loop, this should help: https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with

Good luck,
Jeff
 
Harold Ndou
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jeff, i can now understand.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic