Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

return types scjp1.4

 
vandu matcha
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
vandu matcha
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
got explanations. Even i was confused.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic