• Post Reply Bookmark Topic Watch Topic
  • New Topic

implicit and explicit conversion  RSS feed

 
sangeeta sabharwal
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Line 1 works fine
why does Line 2 needs an explicit cast like in line 3

 
Jon Avadis
Ranch Hand
Posts: 49
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Heres my take: Actually you tell the compiler in both cases to explicitly treat the number as Short.




this is explicit too, cause you tell the compiler you are going to assign a value to a Short.



Here, withouth the cast, the compiler would assume your giving an integer as parameter to the method,
so again, you have to tell him its a Short.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Its allowed. because s assigned to a value which is compile time constant , so compiler will perform narrowing conversion.
for instance, try this int i = 10;short s = i;
and regarding method invocation conversion read below paragraph from JLS:

Method invocation conversions specifically do not include the implicit narrowing of integer constants which is part of assignment conversion (§5.2). The designers of the Java programming language felt that including these implicit narrowing conversions would add additional complexity to the overloaded method matching resolution process (§15.12.2).

 
sangeeta sabharwal
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. That makes sense as it is a conscious decision of the compiler !!
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are welcome
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!