Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java expression compilation error [duplicate]

I'm wondering why this code doesn't compile:

 int x=-3;
    System.out.println(x-----x);

Whereas this code does:

 int x=-3;
    System.out.println(x--- --x);

I think the priority is for pre and then post decrements then the subtraction should be applied.

like image 829
Aladdin Avatar asked Nov 10 '15 08:11

Aladdin


People also ask

What is compilation error in Java?

Compilation Error in java code: Compilation Error in java code: Logical Error: A logic error is when your program compiles and executes, but does the wrong thing or returns an incorrect result or no output when it should be returning an output. These errors are detected neither by compiler nor by JVM.

How to fix illegal start of expression Java error?

Following are some most common scenarios where you would face an illegal start of expression Java error along with the method to fix them, 1. Use of Access Modifiers with local variables Variables that are declared inside a method are called local variables.

How to handle errors during compilation and run time?

During compilation, the compiler has no technique to detect these kinds of errors. It is the JVM (Java Virtual Machine) which detects it while the program is running. To handle the error during the run time we can put our error code inside the try block and catch the error inside the catch block.

What is compile time error in Java?

Compile Time Error: Compile Time Errors are those errors which prevent the code from running because of an incorrect syntax such as a missing semicolon at the end of a statement or a missing bracket, class not found, etc. These errors are detected by the java compiler and an error message is displayed onto the screen while compiling.


1 Answers

x-----x is evaluated from left to right :

((x--)--)-x

The first x-- returns -3, and you can't apply the -- operator on a value (-3), only on a variable (such as x).

That's why you get Invalid argument to operation ++/-- error.

When you add a space - x--- --x

It's evaluated as (x--)- (--x)

                -3 -   -5    = 2
like image 197
Eran Avatar answered Sep 29 '22 20:09

Eran