Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Require help in type casting concept

 
Deepakk Verma
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello to all Ranchers,
I have been working on this small practice program where i got stuck. This is a simple program on the type casting concept..here i am getting a error as

try12.java:17:possible loss of precision
found :int
required:short

the code is as follows:



But then i type casted it and compiled it i got the result as

=============================================================
-1000
32767000
In 1000 days light will travel about -186000000 miles.
=============================================================

Now i dont understand from where did this -1000 came from





please tell me how this seconds = -1000 is evaluated
Thanking you
Deepak Verma
 
Greg Stevens
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this to see the difference:

"seconds" is assigned the result of casting (days * time) to a short. Since (days * time) is larger than the maximum allowed value for a
short (32,767), the value does not fit properly in the short variable and doesn't make any sense (-1000).

The int variable "second" is assigned the result of integer arithmetic (days * time) and so the value is 32767 * 1000 = 32,767,000.
 
Henry Wong
author
Marshal
Pie
Posts: 21506
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try12.java:17:possible loss of precision
found :int
required:short


This means that you have an assignment that the compiler can't determined to be safe -- meaning that the value being assigned may exceed the range of the target.

To avoid this, you casted it... however, in this example, the value did exceed the range of a short. A casting operation from an int to a short, merely truncates the int -- meaning only the lower bytes will be used.

And the reason the value is negative is because this "overflow" happened to overflow into the sign bit.

Henry
 
Ruben Guillen
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please also give a look to the following reference from

Java Language Specification Third Edition

4.2.1 Integral Types and Values
The values of the integral types are integers in the following ranges:

For byte, from -128 to 127, inclusive
For short, from -32768 to 32767, inclusive
For int, from -2147483648 to 2147483647, inclusive
For long, from -9223372036854775808 to 9223372036854775807, inclusive
For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic