java – What happens to the variable after return value++?

Question:

Example:

int foo() {
    int value = 0;
    return value++;
}

The method will return 0 , but what happens to the value variable? Will the compiler generate code for ++ ? Or optimize? And how to check it?

Answer:

The method will return 0, but what happens to the value variable? Will the compiler generate code for ++? Or optimize? And how to check it?

Here's what I found when I opened the compiled file (with .class extension) in Intellij IDEA. After decompilation, the code will look like this (in Java 8):

int foo() {
    int value = 0;
    byte var10000 = value;
    int var2 = value + 1;
    return var10000;
}

The compiler will create a new variable var10000 as you can see in the form of byte since the value variable is zero and byte will be enough and save us memory. Then for some reason it creates a new variable var2 of type int and adds one and returns the result.

If you want to check in other compilers, then in the IDE select the version of JDK you need, or you can even use the jd decompiler without an IDE.

Scroll to Top