简体   繁体   中英

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;
    }

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM