Question

double x = 4.0;
long y = 10;
byte z = 8;
char c = 'd';

System.out.println (y*++z / (z-- -6.0) + 'd'*0.5);

The result is 80.0, but I don't know why?

d is ASCII-Code Number 100.
First term is 80 second term is 2 third term is 50 ?

Was it helpful?

Solution

First term is 30, second is 50. Totals to 80.

'd' = 100

100 * 0.5 = 50

++z = 9

y * ++z = 10 * 9 = 90

z-- = 8, but after the operation. In the operation it is still 9

z-- - 6.0 = 9 - 6 = 3

90 / 3 = 30

30 + 50 = 80

OTHER TIPS

Just break it into smaller pieces and it becomes clear why the result is 80.0.

    public static void main(String[] args) {

        double x = 4.0;
        long y = 10;
        byte z = 8;
        char c = 'd';

        System.out.println (y*++z); // this is 10 * 9 = 90
        System.out.println ((z-- -6.0)); // this is 9 - 6 = 3
        System.out.println ('d'*0.5); // this is 100 * 0.5 = 50.0

        // System.out.println (y*++z / (z-- -6.0) + 'd'*0.5);

    }

If you need a more rigorous treatment check this part of the JLS.

I think this question is about operator precedence
but also about widening conversions of the operands.

19 specific conversions on primitive types
are called the widening primitive conversions:
- byte to short, int, long, float, or double
- short to int, long, float, or double
- char to int, long, float, or double
- int to long, float, or double
- long to float or double
- float to double

(y ) * (++z) /   ( (z--) - (6.0) ) + 'd' * 0.5
(10) * (++8) /   ( (8--) - (6.0) ) + 'd' * 0.5 // z = 9
(10) * (9)   /   ( (9--) - (6.0) ) + 100 * 0.5 // z-- comes to 9--
(10) * (9)   /   ( (9)   - (6.0) ) + 100 * 0.5 
90           /   ( 3.0           ) + 50
30.0                               + 50
80.0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top