• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Strange behaviour in Returning method's value !

 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi , can anyone please explain me this !
the first one compile fine the second won"t.

/************************************/
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is because in the first case, the return value is a compile-time constant, and in the second case it is not.

When a value is a compile-time constant, it means the compiler knows at compile time exactly what the value is, so it can check if the value fits in a short and if it does, then it is allowed to write code like this.

But looking at the second case, you'd say that the compiler should also be able to know that the value is always 500, so this should also be allowed. But it isn't, because there are rules that say when something is a compile-time constant and when it is not, and in the second case the compiler will not regard it as a compile-time constant.

Paragraph 15.28 Constant Expressions of the Java Language Specification lists what kinds of expressions are regarded as constant expressions. Note that according to these rules, the expression s in the line return s; is not a constant expression.

Also relevant is Paragraph 5.2 Assignment Contexts that explains when a narrowing conversion (such as a conversion from int to short) is allowed without a cast.
 
Adam Satyres
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the reply ! it's clear now
 
So you made a portal in time and started grabbing people. This tiny ad thinks that's rude:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic