1
public class ForTest {
    public static void main(String[] args){
        int y = 0; 
        int x = y++ + y*5; 

        
        System.out.println(x);
    }
    
}

Why is the output of this expression equal to fiveL I understand that the y++ takes precedence so y*5 equals 5, but in that case shouldn't x equal 6? My conundrum is that if y*5 equals 5 than doesn't that imply that y has already incremented and thus meaning that x should equal 6?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • 2
    0 + 1 × 5 = 5 . – Dren Feb 28 '21 at 21:35
  • 3
    `y++` increments the variable but returns the _old_ value. So `y++ + y*5` evaluates to `0 + 1*5` in your example. That said, `++y` increments the variable and returns the _new_ value. So if you had `++y + y*5` then that would evaluate to `1 + 1*5`. – Slaw Feb 28 '21 at 21:37
  • It is about the order evaluation of operands in one expression. These are evaluated one after one. Not after the whole expression. That means, in your expression `y++ + y*5` (1) operand `y++` is evaluated to `0` and then y is incremented to `1`, afterwars (2) the operand y (in `y*5`) is evaluated to `1`, which will turn to `1*5`. For more informations, have a look at section 2.5.1.6 of http://www.cs.ait.ac.th/~on/O/oreilly/java-ent/jnut/ch02_05.htm – g.momo Feb 28 '21 at 21:47

0 Answers0