aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Literal conversion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Literal conversion" Watch "Literal conversion" New topic
Author

Literal conversion

Charlie Swanson
Ranch Hand

Joined: Jan 29, 2001
Posts: 213
Could you explain the below lines of code:
1. int n2 = 4096L; // would require a specific (int) cast
2. short s1 = 32000; // ok
3. short s2 = 33000; // out of range for short primitive
In line 2, what I understand is that the number 32000 is actually assumed to be 32000 which is an integer. So infact it is:
2. short s1 = 32000 (where 32000 is an integer)

However a conversion from integer to short would that be the
the same case as line 1 which required a specific cast. In
the case from (short);
The book says since the number 32000 is the range of short,
and therefore it is accepted. Could someone please explain?
In regards to line 3 the compiler would object to line 3, due to the range of primitives. However, isn't the number 33000 an interger by default which would again need to be converted to a short since to it a narrowing type of conversion. The explaination of how it works is appreciated.
frank davis
Ranch Hand

Joined: Feb 12, 2001
Posts: 1479
The Rules as I understand them are this:
There is an implict narrowing for integer, char & short types only when performing a narrowing conversion if these conditions are met:
1. its an integer literal within range, or
2. its integer, char, short variable defined with final within range.
Charlie Swanson
Ranch Hand

Joined: Jan 29, 2001
Posts: 213
Thank you for the help.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Literal conversion
 
Similar Threads
Doubts with parameter assignment
implicit conversion
char to short and vice versa
JAVA casting bug ? Maybe!
Where to find ans for mock test by Valentinn Cretazz