Win a copy of Classic Computer Science Problems in Swift this week in the iOS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Method calls as parameters  RSS feed

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am taking a practice test for Java certification and got this question:

What will the following code print?



This is the answer:
Beta 44
4 44
Beta 44
44 44


I understand the part about overriding and h being shadowed or not. What I'm confused about is what exactly happens when getH() is passed as a parameter. When it is passed as a parameter, does it get to output its println()? Apparently it does. So then why is "Beta 44" first? Why does getH() get executed before b.h is printed?

Thanks for any help.
 
author & internet detective
Marshal
Posts: 38152
617
Eclipse IDE Java VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Patrick Kasarski wrote: So then why is "Beta 44" first? Why does getH() get executed before b.h is printed?


Because Java needs to know the values to pass to System.out.println(). The value of b.h is already known since it is just a variable. Since getH() is a method, it needs to be executed. Then both (b.h and the result of getH()) get passed to println at the same time. It isn't until that point that it executes.
 
Patrick Kasarski
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Jeanne Boyarsky wrote:It isn't until that point that it executes.



Thank you. So just to clarify, if you call a method as a parameter, the parameter method will execute first, before the method call of which it is a parameter?
 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Patrick Kasarski :
if you call a method as a parameter, the parameter method will execute first, before the method call of which it is a parameter?




Thats absolutely true . In your example also , the same thing happens .
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!