Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prefix and postfix operators java

I was trying unary postfix and prefix operators in java

Here's the code

int a=10;

This line of code does not give compile time error

System.out.println(a+++ a +++a);   

But this line does

System.out.println(a++ +++a);

whereas this line even doesn't

System.out.println(a+++ ++a);

I can't understand the pattern of how compiler interprets these queries.

like image 461
user2653926 Avatar asked Oct 21 '22 04:10

user2653926


2 Answers

  1. System.out.println(a+++ a +++a);

    is interpreted the same as

    System.out.println(a++ + a++ + a);

    It's compiled and executed as follows:

    • load a as the first operand; the first operand is now 10
    • increment a (first a++), its value is now 11
    • load a as the second operand; the second operand is now 11 (as it was incremented in the previous step)
    • increment a (second a++), its value is now 12
    • add the two operands 10 + 11 to get 21 which is now the result of a++ + a++, let's call this intermediate result i, which will act as the first operand of the next sum
    • load a as the second operand; the second operand is now 12
    • add i (21) to a (12) to get 33
  2. System.out.println(a+++ ++a);

    is interpreted the same as

    System.out.println(a++ + ++a);

    • load a as the first operand; the first operand is now 10
    • post-increment a, its value is now 11
    • pre-increment a, its value is now 12
    • load a as the second operand; the second operand is now 12
    • add the two to obtain 22
  3. The problematic System.out.println(a++ +++a);

    is interpreted as

    System.out.println((a++)++ +a);

    which would give the same error when you call post-increment on an integer literal.

like image 166
M A Avatar answered Oct 22 '22 18:10

M A


In the case of

System.out.println(a++ +++a);

The compiler appears to be interpreting this as

System.out.println((a++)++ +a);

This doesn't work because the result of a pre/post increment/decrement expression is a value, not a variable. (It might also be seeing it as a+ ++(++a) but the outcome is the same).

Indeed, if you compile this with the Oracle compiler from command line, you get the following error:

UnaryOperatorTests.java:10: error: unexpected type
        System.out.println(a++ +++a);
                        ^
  required: variable
  found:    value
1 error

Which is much more indicative of what's going on when compared to the Eclipse compiler's message:

Invalid argument to operation ++/--

That said, you can get that same error from Eclipse by trying to do:

System.out.println(1++);

Adding a space thusly:

System.out.println(a++ + ++a);

seems to remove the ambiguity that confuses the compiler, and compiles as you might expect.

like image 20
JonK Avatar answered Oct 22 '22 18:10

JonK