• 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 ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Junilu Lacar
  • Martin Vashko
  • Jeanne Boyarsky
  • Tim Cooke
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Scott Selikoff
  • salvin francis
  • Piet Souris

Loss of Precision in method return-type

Posts: 11
Notepad Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I am currently studying the topic 'Methods and Encapsulation' from Jeanne Boyarsky and Scott Selikoff.
Now, I tried the following snippets of code :

Case 1 :

Case 2:

Now, when I compile these classes, in Case 1, it works fine and I get the output as :
From method m1...returning short to int

In case 2, however, I get a compile -time error :
error: incompatible types : possible lossy  conversion from int to short
          short num = m1();

Am failing to understand, if it is promoting the returned short value in case 1, why is it not working in Case 2.
Can anybody please provide a logical explanation for the same?
Help will be appreciated as always
Thank you in anticipation.
Posts: 66525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In both cases youo are returning an int from line 12. At least it would be line 12 if you used the correct number of empty lines:-Your method might have a short as its local variable, but to other code its return type is int. That is how it is declared. The compiler doesn't go through the code to test whether there is a “narrower” type returned. In the first code block, you are doing nothing with the value returned, which simply disappears into cyber‑limbo never to be seen again. The second code block attempts to assign an int to a short reference, which as you know can only be done with an explicit narrowing conversion (=cast). Please remind yourself of the kinds of conversions allowed and not allowed, from the Java┬« Language Specification (=JLS). If you don't supply a cast, your code won't compile.
I'm full of tinier men! And a tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!