问题
Can anyone solve my confusion here is my code :
byte i = 0;
i++;
System.out.println(i);
Result: 1
byte i = 0;
i = i+1;
System.out.println(i);
Generate compile time error: Type mismatch: cannot convert from int to byte
When I convert that to byte like: i = (byte) (i+1);
then happily getting result 1
Performing this example i am understand i = i+1 & i++ perform can't same opearation so now i want to know what is exactally difference between them ...!!!
回答1:
i++
and i+=1
implicitly cast the result back to the type of i
.
So if i
is a byte
, then i++;
is not equivalent to i = i + 1;
- it's actually equivalent to i = (byte)(i + 1);
.
From the Java Language Specification, section 15.14.2, emphasis mine:
... the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored.
There's no fundamental reason to it, other than "because the specification says so". The people who wrote the specification most likely wrote it this way so that ++
would be useful for all numeric types (not just int
and long
).
回答2:
internally for short, char, byte and int datatype if any arithmetic operation is performed compiler will upgrade data type to int and perform the operation. compiler will change the data type of expression result value to int
so for byte i
i = i+1; // will not work
because i+1
will result an integer data type value. so you have to typecast externally as
i = (byte)(i+1); // this is equivalent to i +=1; or you can say i++;
回答3:
Finally i am found my problems(questions) superior understand so here describe it to understands others easily..!!!
1> i = i + 1
In java whenever any arithmetic operation performs between two or more variables then it's return value's type depends upon like this equation :
RETURN VALUE TYPE = (int, MAXIMUM RANGE OF VARIABLE-1, MAXIMUM RANGE OF VARIABLE-N )
here, Return value type : int
For eqution (int, byte, byte) so int have maximum range..
byte -> 1 byte size & int -> 4 byte size
That's why above exe i can't store that return value in byte directly it's require external type casting i = (byte) (i+1)
2> i++
In java whenever increment & decrement operation perform like these then it's return value's type depends upon this equation:
RETURN VALUE TYPE = (VARIABLE TYPE, VALUE + 1)
these equation denote internal type casting perform in this case
MUST REMEMBER:
case 1: External type cast require if needed
case 2: internal type casting perform automatically
来源:https://stackoverflow.com/questions/29490795/difference-between-i-i1-i