Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what's the narrowest valid return type for the method

 
Essam AbdelAziz
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear All ,can you help me to solve this

public class Test{

returnType method(byte x,double b){
return (long)x/y*2

}

}

what's the narrowest valid return type for the method

thanks
 
Vassili Vladimir
Ranch Hand
Posts: 1585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

In the statement:



It must be "b" instead of "y" right ? If so, the the return type can only be double or Double.

If it's "y", please specify its type.

Best of luck ...
 
Essam AbdelAziz
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry it was aritten misatke it supposed to be (b)
but the question now?
why double not any thing else
 
Vassili Vladimir
Ranch Hand
Posts: 1585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because it's returning a double, only a double or a Double (as a narrowest) can be defined as a return type.

A long can't fit, because there will be a lost of precision.

As a matter of fact, you can define a Number or an Object as the return type.

Good luck ...
 
Essam AbdelAziz
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
could you please clarify more

Thank you
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

public class Test{

returnType method(byte x,double b){
return (long)x/y*2

}

}


Hi Balidimir,
Here we did explicit casting from double to long that is ok, so why can't we return long. An we see long is returned after casting double to long, so why can't return type of the method be long.

Please clarify that,

Thanks in advance,

Regards,
cmbhatt
 
Pratik Patel
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Qoute:Here we did explicit casting from double to long that is ok, so why can't we return long.

You didnt cast the value of an expression to long. You just type casted the value of varialbe x. So finally the value of whole expression will be promoted to double since y is of type double.

If you want to cast the value of expression to long you should do it in the following way.

(long)(expression)... (long)(x*y/2).
Then you can return the long type from method.

Pratik
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Pratik for pointing out the real concern.






Thanks and Regards,
cmbhatt
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic