• Post Reply Bookmark Topic Watch Topic
  • New Topic

Assigning int literal to e.g. byte works, but not as method parameter  RSS feed

 
Bora Sabrioglu
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

if you write
it works (implicit conversion of implicit int literal 100 to byte.
But if you have a method
and want to invoke it with a literal (which is an int by default): then there is no implicit conversion.

Is the just an exception in Java? And is it the rule that one has to explicitely cast (narrow) integer literals when passing to smaller-than-int types?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bora Sabrioglu wrote:
if you write
it works (implicit conversion of implicit int literal 100 to byte.


For full details, see section 5.2 of the JLS...

http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.2

Look about halfway down in the JLS section regarding compile time constants.

Bora Sabrioglu wrote:
But if you have a method
and want to invoke it with a literal (which is an int by default): then there is no implicit conversion.


For full details, see section 5.3 of the JLS...

http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.3

Notice that there isn't any mention of the case of compile time constants.

Henry
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bora Sabrioglu wrote:
Is the just an exception in Java? And is it the rule that one has to explicitely cast (narrow) integer literals when passing to smaller-than-int types?


It is not just integer literals, it is for compile time constants... which has a very exact meaning in the JLS. See my other topic regarding compile time constants.

http://www.coderanch.com/t/454384/java/java/compile-time-constant

And yes, it only applies to implicit casting between int, short, byte, and char only.

Henry
 
Bora Sabrioglu
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks alot Henry.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!