File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Returning long for an integer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Returning long for an integer" Watch "Returning long for an integer" New topic

Returning long for an integer

Aniket Patil
Ranch Hand

Joined: May 02, 2006
Posts: 218
While it is alright to return a constant integer from a method where a short or a byte is expected, why does this not work with returning a constant long in place of an integer?

For eg. the following is fine
However this doesent work out:

A possible loss of precision error is thrown.
Similarly, returning a constant double for a float is also disallowed. Does this have anything to do with the float-value set and double-value set?
[ September 07, 2006: Message edited by: Aniket Patil ]

SCJP 5.0 | SCWCD 1.4 <br /> <br />If you don't know where you are going, any road will take you there!
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023

Does not compile too.
[ September 07, 2006: Message edited by: wise owen ]
Aniket Patil
Ranch Hand

Joined: May 02, 2006
Posts: 218
That is true. Though i didn't state it clearly, i was only referring to constants that could be fit in the data type. However, my doubt is still not clear w.r.t int and constant long.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Check JLS 5.2 and you will find:
In addition, if the expression is a constant expression (�15.28) of type byte, short, char or int :

* A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

So if your constant expression is a long, you are out of luck - you cannot assign it to the narrower return type.

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Aniket Patil
Ranch Hand

Joined: May 02, 2006
Posts: 218
Thanks for that!
I agree. Here's the link:
subject: Returning long for an integer
It's not a secret anymore!