Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit type casting in Java

Tags:

java

casting

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?

like image 265
Ayush Seth Avatar asked May 14 '26 08:05

Ayush Seth


1 Answers

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).

like image 182
Andrea Bergia Avatar answered May 15 '26 22:05

Andrea Bergia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!