0

What will be the value of x in following code:

int x=15; 
x %= x++ + +x - 3

Please explain why.

Why doesn't it give syntax error for +x or the extra + before it?

talex
  • 17,973
  • 3
  • 29
  • 66
sahanir
  • 63
  • 4
  • if you look at https://docs.oracle.com/javase/specs/jls/se8/html/jls-19.html the Syntax of Java was designed this way. While disputable (especially more irritating examples) - this is simple the way the language was created. – kai Feb 15 '19 at 06:53

2 Answers2

1
x %= (x++) + (+x) - 3;  

The x++ is called postincrement. You can check this post.
The +x is just a sign operator.

So your statement will evaluate to:

x %= (15) + (+16) - 3;
Mark Melgo
  • 1,477
  • 1
  • 13
  • 30
1

You can split your code into parts like this to see how does it works:

    int x = 15; 
    int y = x++ + +x;
    System.out.println(y);  //result: 31 (x = 15, then incremation so it is 15 + 16)
    System.out.println(x);  //result: 16 because of previous incrementation
    y = y - 3;
    System.out.println(y);  //result: 31 - 3 = 28
    x %= y;
    System.out.println(x);  //result: 16 % 28 = 16
Rafał Sokalski
  • 1,817
  • 2
  • 17
  • 29
  • No matter how many + or - you use between this 2 numbers if the number of '-' are even then sum will be performed otherwise subtraction – Rafał Sokalski Feb 15 '19 at 06:37
  • Because addition and subtraction has the same priority so it goes from left to right. So + + + gives you + then is minut and + - 3 gives you negative number. It means that '-' negative number gives you positive. x=15 + + + - (+ (- 3)); – Rafał Sokalski Feb 15 '19 at 06:52
  • one may argue(I don't but for the sake of the challenge) an infix operator needs two operands and an operand has at most one sign operator. And well other languages do work differently(and also correct). – kai Feb 15 '19 at 06:58