• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Primitive casting

 
Priya Jothi
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Exactly what exception is it throwing at line 6 when you run the program?
 
Kayalvizhi Umashankar
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Its not throwing an exception but compile time error as "Type mismatch: cannot convert from long to short"

Kayal
 
Priya Jothi
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 335
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok..Thanks a lot!!

Cheers,
Priya.
 
Kayalvizhi Umashankar
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Santana for the awesome reply.


Kayal
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic