Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Casting in Java

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

like image 930
user827992 Avatar asked Nov 30 '22 16:11

user827992


1 Answers

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
like image 74
JB Nizet Avatar answered Dec 05 '22 01:12

JB Nizet