• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Possible Loss of Precision error - why?

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why does this cause an error:



Isn't char a 16 bit type? How could assigning a short to a char cause a loss of precision?

I realize that the problem can be eliminated by adding an explicit cast to char, but I want to understand why it's necessary here.

Thanks,
 
Sheriff
Posts: 9707
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
well short can have -ve values but char can't so the compiler generates an error that there might be a loss of precision

eg.

short s1 = -10, s2 = 5;

char ch = (short)(s1+ s2); //-5 cannot be assigned to char
 
Ranch Hand
Posts: 220
Eclipse IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
char is unsigned so you cannot assign it negative values
it starts from ZERO ....

 
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Moreover addition also results in an integer which cant be assigned to a char.


correct me if i am wrong
 
Ankit Garg
Sheriff
Posts: 9707
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by pradeepta chopra:
Moreover addition also results in an integer which cant be assigned to a char.
correct me if i am wrong



You are right. This is why I used the cast in my code

har ch = (short)(s1+ s2);
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic