aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes return types    scjp1.4 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "return types    scjp1.4" Watch "return types    scjp1.4" New topic
Author

return types scjp1.4

vandu matcha
Ranch Hand

Joined: Dec 28, 2005
Posts: 57
this question is from K&B Self Tests....
i could not understand the solution..any help is appreciated

1. class Test {
2. public static Foo f = new Foo();
3. public static Foo f2;
4. public static Bar b = new Bar();
5.
6. public static void main(String [] args) {
7. for (int x=0; x<6; x++) {
8. f2 = getFoo(x);
9. f2.react();
10. }
11. }
12. static Foo getFoo(int y) {
13. if ( 0 == y % 2 ) {
14. return f;
15. } else {
16. return b;
17. }
18. }
19. }
20.
21. class Bar extends Foo {
22. void react() { System.out.print("Bar "); }
23. }
24.
25. class Foo {
26. void react() { System.out.print("Foo "); }
27. }
what is the result?

ans is Foo Bar Foo Bar Foo Bar
my guess is that it should be Bar Bar Foo Bar Foo Bar
as overridden methods are called based on runtime type of the object ....
vandu matcha
Ranch Hand

Joined: Dec 28, 2005
Posts: 57
got it ....when i executed the program..Y%2 is giving 0..so if condition is true...hence the output is Foo Bar Foo Bar Foo Bar....
Michael Carlson
Ranch Hand

Joined: Sep 11, 2005
Posts: 78
I think the problem your having is with the expression:
(0 == y % 2) for example
if((0 == 0 % 2)) is true.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
I read "if (0 == y%2)" to mean "if y is even". This is a very common idiom. Since 0 is even, then this expression will evaluate to true.

Does that help?

Layne


Java API Documentation
The Java Tutorial
vandu matcha
Ranch Hand

Joined: Dec 28, 2005
Posts: 57
yes exactly ...i was confused ..i thought 0%2 is 2....but later i recognised that arithmetic operation of / and % with 0 as divident is always 0.....thanks for the responses...
Anju sethi
Ranch Hand

Joined: Dec 26, 2005
Posts: 91
got explanations. Even i was confused.


thanks,<br />Anju Sethi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: return types scjp1.4