Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question regarding method invocation's parameter widening/narrowing

 
kay lin
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi:
Here is one practice quesiton I came upon

What is the result of attempting to compile and run the program?
a. Prints: float,float
b. Prints: float,double
c. Prints: double,float
d. Prints: double,double
e. Compile-time error
f. Run-time error
g. None of the above

The answer key is a. Prints: float,float

now, is it because on method invocation, the parameter of the invocating method can only be widened to match the parameters of the actual method?

please let me know.

Thanks
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason is that when you have more that one method that could match an invocation, the most specific method is chosen.
 
kay lin
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what exactly do you mean by "more specific" sorry I am sitll not clear on that..
 
James Quinton
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by kay lin:
what exactly do you mean by "more specific" sorry I am sitll not clear on that..


you can understand "more specific" as "narrower", or "closer".
In you code example, float is narrower than double. Hence, float is closer to int and long.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by kay lin:
what exactly do you mean by "more specific" sorry I am sitll not clear on that..


Basically the idea is that you have two methods, A and B, that could both match the method call, and if any call to B could be made to A without a compile-time error, then B is more specific than A.
 
priyanka jolly
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
can you tell me that in this question while saying long l=2 why we didnt specify L after 2 because by virtue all numbers will be taken as Integer and so to assign to long we have to say long l=2L .Am i Wrong?
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by priyanka jolly:
Hi
can you tell me that in this question while saying long l=2 why we didnt specify L after 2 because by virtue all numbers will be taken as Integer and so to assign to long we have to say long l=2L .Am i Wrong?


Yes, you are wrong. The 2 (as you said) is an int literal. But by assigning it to a long it gets converted to a long. But on the other hand using 2L is also correct, it just avoids the conversion.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic