Reputation: 1753
this is my first post here and i like to thank all the people that can help me with this simple question: how the casting works in java?
I made this very simple class:
public class test {
public static void main ( String[] args )
{
System.out.println((short)(1/3));
System.out.println((int)(1/3));
System.out.println((float)(1/3));
System.out.println((double)(1/3));
}
}
and this piece of software gives me this output when executed ( official JDK 6 u26 on a 32 bit machine under linux )
0
0
0.0
0.0
the problem, or the thing that i don't understand if you would, is that the last 2 results are 0.0, i was expecting something like 0.3333333, but apparently the cast works in another way: how?
thanks
PS I'm not so familiar with the english language, if i made some errors i apologize for this
Upvotes: 4
Views: 437
Reputation: 20235
Because you have the 1/3 in parentheses, it uses integer division then casts to the type specified. It would evaluate to .3333333 if you used 1.0/3.0 or (float)1/3. 1 and 3 are integer literals, so results from division will be truncated. To use float and double literals put an f or d at the end of the number (1.0f, 1.0d). Casting affects the value after it, so if your value is in parentheses, it will evaluate that, then make the cast.
Upvotes: 1
Reputation: 299218
You need to cast the operands, not the result. This will yield the output you expected:
System.out.println(((short) 1 / (short) 3));
System.out.println((1 / 3));
System.out.println(((float) 1 / (float) 3));
System.out.println(((double) 1 / (double) 3));
Upvotes: 1
Reputation: 13686
int is coverted into double.
(1/3) is of type int so answer will be 0.
Now 0 is casted to double or float so it has become 0.0
Upvotes: 1
Reputation: 692181
First, the expression 1/3
is executed. This expression means "integer division of 1 by 3". And its result is the integer 0
. Then this result (0
) is cast to a double (or float). And of course it leads to 0.0
.
You must cast one of the operands of the division to a double (or float) to transform it into a double division:
double d = ((double) 1) / 3;
or simply write
1.0 / 3
Upvotes: 9
Reputation: 365
In the last 2 cases you first compute 1/3, which is 0. Then you cast it to a float/double. Use:
((float)1)/3
Upvotes: 4
Reputation: 16796
If you use the operator /
on integer values, the result will be typed as an integer.
You will have to force either 1 or 3 to a floating point value - try writing 1.0/3
instead of 1/3
.
Upvotes: 5