• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

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: 38506
653
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 .
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!