File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Require help in type casting concept Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Require help in type casting concept" Watch "Require help in type casting concept" New topic

Require help in type casting concept

Deepakk Verma
Ranch Hand

Joined: Sep 09, 2009
Posts: 31
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 i am getting a error as loss of precision
found :int

the code is as follows:

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

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

Joined: Jul 23, 2009
Posts: 41
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

Joined: Sep 28, 2004
Posts: 18977
  40 loss of precision
found :int

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.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ruben Guillen

Joined: Sep 02, 2009
Posts: 28
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

I agree. Here's the link:
subject: Require help in type casting concept