-3

Can someone help break this down?

double i = 5.5;
i = ++i+i++*(int)i+++i;

System.out.println(i);

The answer is 60.5.

Explain step by step please.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
nnn
  • 183
  • 1
  • 1
  • 9

4 Answers4

1
i = ++i + i++ *(int)i + ++i;
  • ++i = 6.5 +
  • (i++ *(int)i) = 45.5 +
  • ++i = 8.5 == 60.5
RadijatoR
  • 113
  • 9
0

Here are the things involved here to calculate.

1)post-increment have highest precedence.

2)casting 7.5 to int become 7

3) i++ increases in value by 1 and stores it back to i

double i = 5.5;

i = ++i +(i++) *(int)(i++) +i; // i incremented by 1 and added that to i back (6.5)

i= ++i + 6.5*int(7.5) +8.5; //// i incremented by 1 and added that to i back (7.5)

i= ++i + 6.5*7 +8.5; // casting 7.5 to int is 7 and added the i value 8.5

i= 6.5 +6.5*7 +8.5; 

i= 60.5
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

The evaluation should be from left to right

6.5+6.5*7+8.5 =60.5

preincr+postincr*removespoint+post incr+ result of incr

mProME
  • 1
  • 1
0

It would be a lot easier if you was to put it in to the format RadijatoR has stated in the comments.

       i = ++i + i++ * (int)i++ + i; 

This question is testing you on precedence.

increment operators have the highest precedence. So let's deal with them first (We shall do so in a left to right order).

i = ++i + i++ * (int)i++ + i;

As you can see the first is a pre-increment operator which means i = 5.5+1, prior to the evaluation. The second is a post increment operator, meaning the value of 6.5 will be used, but the next time i is used it will be incremented, hence the third is 7.5 and then is thus post incremented causing the last i to be 8.5.

Now that is out the way we have the following expression:

i = (6.5) + (6.5) * (int) (7.5) + (8.5)

The cast will come second, so 7.5 will be casted to a primitive int of value 7 not 8, java simply chops off the decimal.

We now have:

i = (6.5) + (6.5)*(7) + (8.5)

Multiplication occurs next so we have 6.5*7 which yields 45.5

 i = 6.5 + 45.5 + 8.5

This finally yields the result of 60.5, which is what you expected.

So to conclude the order of precedence in this question:

1)Increment operators 2)Casts 3)Multiplication 4)Addition

RamanSB
  • 1,162
  • 9
  • 26