aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Primitive casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Primitive casting" Watch "Primitive casting" New topic
Author

Primitive casting

Priya Jothi
Ranch Hand

Joined: Jul 13, 2004
Posts: 168
Hi all...

when I run the following prg, It is throwing exception at line 6.But it is compiling well with line 5. what make difference here.Why cant we do same with long.

public class Tester {
public static void main(String[] args) {
final int i=10;
final long l= 10;
short s= i; // line 5
short s1=l; // line 6
}
}
Can any one clarify the reason.

Thanks in advance..

Priya
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Exactly what exception is it throwing at line 6 when you run the program?


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Kayalvizhi Umashankar
Greenhorn

Joined: Aug 04, 2005
Posts: 25
Its not throwing an exception but compile time error as "Type mismatch: cannot convert from long to short"

Kayal
Priya Jothi
Ranch Hand

Joined: Jul 13, 2004
Posts: 168
This is the compile time error im getting.


>javac tst.java
tst.java:248: possible loss of precision
found : long
required: short
short s1=l; // line 6
^
1 error
Santana Iyer
Ranch Hand

Joined: Jun 13, 2005
Posts: 335
Priya,

for implicit narrowing conversion on assignment to occur following conditions are reqd.

the source is a constant expression of either byte, short, char, or int type

the destination type is either byte, short, or char type

the value of the source is determined to be in the range of the destination type at compile time

in your case source is long not int
Priya Jothi
Ranch Hand

Joined: Jul 13, 2004
Posts: 168
Ok..Thanks a lot!!

Cheers,
Priya.
Kayalvizhi Umashankar
Greenhorn

Joined: Aug 04, 2005
Posts: 25
Thanks Santana for the awesome reply.


Kayal
 
jQuery in Action, 2nd edition
 
subject: Primitive casting
 
Similar Threads
wrappers
final int/byte
JQuest question
Primitive Value Assignment
for loop working 2 - 4 times