首页 > 解决方案 > Does forcing a type into a variable make the whole statement into the inserted type?

问题描述

I am at a dilemma as to whether the type double would change the variable of width into a double or only length :

double ratio = (double) length / width;

标签: javavariablestypestype-conversionvar

解决方案


Type of the variables length and width do not change after executing that line. The type you have given to those variables when you declare them, remains as it is. Assuming width and length is type int, I wrote the small program below to check the type.

public class CheckType{

    void printType(int x) {
        System.out.println(x + " is an int");
    }

    void printType(double x) {
        System.out.println(x + " is an double");
    }
    
    public static void main(String []args){
         int length=6; int width=2;
         double ratio = (double) length / width;
         CheckType x = new CheckType();
         
         System.out.println(length);
         System.out.println(width);
         x.printType(ratio);
         x.printType(length);
         x.printType(width);

     }
}

Output from the above program is:

6
2
3.0 is an double
6 is an int
2 is an int

推荐阅读