1

I have been given some practice questions to do for an upcoming test and there is one that has confused me:

"What is print out by the following segment of code:

int var1 = 2;

int var2 = 6;

int var3 = var1;

var3 = var2++ * var3 + var2 / var3;

System.out.println(var3);"

It looks simple enough, but I cannot understand how the answer is 15, and not 17.5 as I put (and that answer is a float so it isn't valid anyway.)

The only way I see of getting 15 is if, when you do var2++, it does not actually increment var2 to 7. Also, I am not sure if var2++ updates the var2 variable or just increments temporarily for that one instance.

The way I have been doing it is by following the order of presedence...

var3 = ((var2++) * var3) + (var2/var3)

But this gives me...

var3 = (7 * 2) + (7/2)

var3 = 14 + 3.5

var 3 = 17.5

I have run the code in a Java compiler and I am in fact getting 15.

Anyone know why?

Gayan Mettananda
  • 1,498
  • 14
  • 21
Link
  • 317
  • 1
  • 5
  • 17

0 Answers0