File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

primitive casting+boxing

 
Mahesh Murugaiyan
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello. im preparing for SCJP 1.6 and came across these two questions which confuses me a bit. i tried these out and they work as mentioned in the book, still i need some clarifications:

Question 1:

2. Question 2:

- I read that all numerical literals are int by default. so in the first example, the int 200 is narrowed down to short and then boxed into Short. (is it also because 200 can fit in short easily?)

- then, why cant the 7 which can fit in the short is being accepted as a parameter? while short story = 200; works, why cant an int be passed as a parameter?

Thanks
Mahesh
 
Henry Wong
author
Marshal
Pie
Posts: 20826
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mahesh Murugaiyan wrote:
- I read that all numerical literals are int by default. so in the first example, the int 200 is narrowed down to short and then boxed into Short. (is it also because 200 can fit in short easily?)


Correct. This is defined in section 5.2 of the Java Language Specification....

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

And in this section, is a discussion regarding compile time constants, and boxing to Short.


Mahesh Murugaiyan wrote:
- then, why cant the 7 which can fit in the short is being accepted as a parameter? while short story = 200; works, why cant an int be passed as a parameter?


Method parameter conversions is defined in section 5.3 of the Java Language Specification....

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

And interestingly, there isn't a provision for compile time constants.

Henry
 
Mahesh Murugaiyan
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the pointer!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic