aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Result of self test question on K & B studyguide chapter 3 pg 285, question 12. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Result of self test question on K & B studyguide chapter 3 pg 285, question 12." Watch "Result of self test question on K & B studyguide chapter 3 pg 285, question 12." New topic
Author

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

Harold Ndou
Ranch Hand

Joined: May 19, 2013
Posts: 34
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

Joined: Jul 29, 2012
Posts: 812
    
    1


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

Joined: May 19, 2013
Posts: 34
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

Joined: Jun 03, 2013
Posts: 8
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

Joined: May 19, 2013
Posts: 34
Thanks Jeff, i can now understand.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Result of self test question on K & B studyguide chapter 3 pg 285, question 12.