Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Require help in type casting concept

Deepakk Verma
Ranch Hand
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 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
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
Posts: 21754
85
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
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