Difference between x++ and x+1

Difference between x++ and x+1

Have you ever wondered what the heck is the difference between x++ and x=x+1?
When x++ is used, the compiler increases the value of x by 1 and In the case of x=x+1, it again increases the value of x by 1. What to wonder?πŸ€·πŸΌβ€β™‚οΈ

Let's see an example now!
What happens when the below code is executed?

    byte b = 10;
    b = b + 1;
    System.out.println(b);

It is a compile-time error!🀯
Surprised?😱😱

Okay, with the same surprised state, guess the output of the below snippet:

    byte b = 10;
    b = b++;
    System.out.println(b);

Yes, this time you are right. it prints 11 to the console.
Confused??😡

No worries, Let's dive into it and check what's wrong🧐 and learn it together.πŸ™‚

We should be aware of the fact that whenever we are trying to apply any arithmetic operator between two variables x and y, the result type is always:

max ( int, type of x, type of y).

Let’s now see what happens in case both of the above cases :

1. Internal Typecasting of data: In the 1st example, we are doing an arithmetic operation i.e. addition on b and 1. Here b is of byte type and 1 is of int type. Therefore, the result should be of type:

max(int,type of b i.e. byte,type of 1 i.e. int).
i.e., int type

We are assigning int type to byte type in the above snippet which turns out to be a compile-time error β€œpossible loss precision”. Here typecasting is required to perform addition.

So modifying the 1st snippet as below works:

    byte b = 10;
    // b = b + 1
    b = (byte) b+1;
    System.out.println(b);

Using x++ :

In the 2nd snippet, we are doing increment. Internally we are doing an operation same as b = b + 1. So as per our 1st theory, the result should be of int type. i.e max(int, type of b i.e. byte, type of 1 i.e. int) but we are getting the result as 11. This is because of implicit typecasting done by the compiler.

byte b = (byte)(b+1)

From the above example we can understand that in the increment/decrement operator, the compiler automatically does type-casting whenever required. It means that in fact x++; is a shortcut for something like:

x = (type of x)(x + 1);

2. The other difference is Different Compiler Instructions

As they are different operators, they use different JVM instructions in bytecode.

x + 1 uses 'iadd' instruction, whereas
x++ uses 'iinc' instruction internally

Although this is compiler dependent. A compiler is free to use a different set of instructions for a particular operation.

That's all the whole difference is.
Hope you have learned something new. If yes, share it with your friends and colleagues.

Let's meet at the other tech article next time. Until then stay connected with me on LinkedIn

-- Pasumarthi Sai Phani Krishna (aka PSPK)😊