Search code examples
javacastingprimitive

Parse different data type Java


Since int is less precise than double I thought I needed to cast it when parsing it into a method. Yet the following code runs fine. Why?

public class MyClass {

    public static void main(String[] args) {
        System.out.println(met(3/2));
    }

    static String met(int i){
        return "This is what I get " + i;
    }

}

Solution

  • When you do 3/2 that won't give you a double result. Integer division happens and result gets truncated to an integer. Hence there is no need of cast. In order to get double result, either needs to be cast to double so that get a compiler error to get it casted to double.

    Try doing met(3d / 2), then you run into the compiler error which you are expecting.