In this tutorial, we’ll try to understand the difference between b++ and b=b+1 ?
b++ and b=b+1:
If we see at a glance, the b++ and b=b+1 both generates the same output but in terms of evaluation of expression it differs a lot.
- ++ is an increment operator and also it is a unary operator as because we can only apply ++ operator on single operand just like b++. We can not apply ++ on two operands like b++a or b++1 these are invalid.
- Where as + is an arithmetic operator, so that we can apply this operator in between two or more operands. Like b+1 or a+b+c etc.
b=b+1 meaning, we are adding the existing b value with 1 and assigning the resultant value to b itself. So while doing this operation we have to be bit careful because if we apply any arithmetic operator between two operands the resultant type is always maximum of (int, type of a, type of b).
For example if you try to add two bytes the return type would be the int, where as if we add short and long the return type would be long because the maximum of short and long is long.
Here is the list of possible return types:
- byte + byte = int (maximum of (int, byte, byte))
- byte + short = int (maximum of (int, byte, short))
- short + short = int (maximum of (int, short, short))
- short + long = long (maximum of (long, short, long))
- byte + double = double (maximum of (double, byte, double))
- char + char = int (maximum of (int, char, char))
- char + double = double (maximum of (double, char, double))
Let’s understand better by taking an example below.
byte a =10; byte b=20; byte c = a+b; //maximum of (int,type of a, type of b) it will returns the int type System.out.println(c);
The above program generates an exception like possible loss of precision found int require byte.
So the expression b=b+1 is always fail fast. However we can resolve this exception by explicitly casting the type of a value like below.
byte b = (byte) a+b;
But in this we (developer) should aware of outcome of the output, otherwise result might be weird.
++ is an increment operator and also it is a unary operator as because we can only apply ++ operator on single operand just like b++. We can not apply ++ on two operands like b++a or b++1 these are invalid.
Unlike the b+1 expression, this case the implicit conversion will be happen internally of the given types. Meaning if use unary operator the compiler takes care of the conversions internally (taking care of finding maximum of type and increment the value)
byte b = 10; b++; // b= (byte)(b+1); Implicit conversion System.out.println(b); // 11
Here the implicit conversion happening while evolution of the expression.
Happy Learning 🙂