double average = (double) 22 / 4; // output is 5.5
double average1 = (double) (22 / 4); // output is 5.0
double s2 = (double) 2 3 / 2; // output is 3.0
double s = (double) (2 3) /2; // output is 2.5
I am a little confused about Java type casting. Can someone please explain how casting works and how it is being applied in the above lines?
CodePudding user response:
It's not a matter of 'how casting works', it's 'how does operator precedence work?'.
Casting, being essentially a monadic operator, binds tighter than the binary arithmetic operators.
double average = (double) 22/4; output is 5.5
The cast converts 22 to 22.0, so 4 is converted to 4.0 to make both operands 'double'. 22.0 / 4.0 is 5.5.
double average1 = (double) (22/4); output is 5.0
The parentheses cause 22/4 to be evaluated first. Integer division truncates; 22/4 is 5. That is then converted to 5.0.
double s2 = (double) 2 3 / 2; output is 3.0
The cast gives 2.0, thus 2.0 3 / 2. Division has higher precedence than addition. 3 / 2 uses integer division, giving 1. 1 is then converted to 1.0; 2.0 1.0 is 3.0.
double s = (double) (2 3) /2; output is 2.5
2 3 is 5 by integer addition. That is then converted to 5.0 by the cast. To make the other operand also double, 2.0. 5.0 divided by 2.0 is 2.5.
CodePudding user response:
double average = (double) 22 / 4; //output is 5.5,
Divide integer 22 cast to double as 22.0 by integer 4 cast to double 4.0, which is a double 5.5.
double average1 = (double) (22 / 4); //output is 5.0
Divide integer by integer, get a result integer, then cast to double.
double s2 = (double) 2 3 / 2; //output is 3.0,
Add an integer cast to double to an integer divided by an integer (result of this division is an integer 1), which is 2.0 1, giving double 3.0
double s = (double) (2 3) / 2;
Add an integer to an integer, result is cast to double, and divided by an integer, which is 5.0 / 2, giving us double 2.5.
The tricky part for Java beginners is understanding operator precedence. More info here https://introcs.cs.princeton.edu/java/11precedence/
CodePudding user response:
22 and 4 are integers. 22/4 thus would return an integer (5 in this case).
By casting 22 to a double (as in the first example), you allow for it to be divided into a decimal number.
In the second example, you are casting the result of 22/4 to a double, but since both of them are integers, you are essentially casting 5 to a double, returning 5.0
In the third example you are casting the first 2 to a double, meaning that 3/2 will still return an int (1), meaning that in the end it will return 2.0 1
In the last example you are casting 2 3 to a double, meaning that in the end you return 5.0/2 which returns 2.5