I know type casting is done automatically in Java for lower precision primitive type to higher precision. For example in this code :
int i = 20;
int j = 40;
float k = i + j; //explicit casting not required
My question is, what actually happens internally? In the third statement, do the values of i and j individually get casted to float and then added together?
Or the addition is done first in int type and then the result of addition is casted into float?
Let's take a look!
$ cat > temp.java
class temp {
public void f() {
int i = 20;
int j = 40;
float k = i + j; //explicit casting not required
}
}
$ javac temp.java
$ javap -c temp
Compiled from "temp.java"
class temp {
temp();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public void f();
Code:
0: bipush 20
2: istore_1
3: bipush 40
5: istore_2
6: iload_1
7: iload_2
8: iadd
9: i2f
10: fstore_3
11: return
}
As you can see, first they are added as integers (instruction 8), then casted to a float (instruction 9).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With