When compiling the code, both numero1 and numero2 display the same value even having an increment

Asked

Viewed 88 times

4

public class IncrementoDecremento{

    public static void main(String[] args) {

        Integer numero1 = 10;
        Integer numero2 = ++numero1;

        System.out.println("numero: " + numero1 + ", numero2: " + numero2);


    }

}

How this Increment works?

2 answers

8

It is called preincrement so it takes the value of the variable in which it operates and changes its value by adding 1 to what already existed. And since the operator results in an expression the result of this can be used anywhere that expects an expression, then in this example this new value is assigned to the new variable.

The compiler will end up doing the same as this code:

public class Main {
    public static void main(String[] args) {
        Integer numero1 = 10;
        numero1++;
        Integer numero2 = numero1;
        System.out.println("numero: " + numero1 + ", numero2: " + numero2);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

This is different from the post-increment where the variable value is used in the expression before applying the operation, then the value of numero1 would have ended up being the same, but numero2 would give a different result. That would look like this:

public class Main {
    public static void main(String[] args) {
        Integer numero1 = 10;
        Integer numero2 = numero1;
        numero1++;
        System.out.println("numero: " + numero1 + ", numero2: " + numero2);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

The recommendation is not to use operations that cause side effect (changes the state) in a place that expects an expression, so every time the operator makes an assignment on the variable itself do so on a separate line. Another way is to use parentheses to contain the expression, but in practice this would transform even the post-increment in preincrement, which may not be what you want, so just avoid putting everything in the same line two operators that make assignment.

Also not very interesting the use of the type Integer (is a shame until it exists), prefer the int whenever possible.

7


It’s simply a question of where the ++

Integer numero2 = ++numero1;

It turns into that:

numero1 = numero1 + 1;
Integer numero2 = numero1;

Now if you put:

Integer numero2 = numero1++;

Turn that around:

Interger numero2 = numero1;
numero1 = numero1 + 1;
  • 1

    The simplest explanation was what made me understand. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.