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;
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;
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
It effectively changes both.
Your expression, (double) length / width
, is equivalent to ((double) length) / width
. However the Java language does not define dividing a double
by a value of a different type than double
. Therefore width
is implicitly promoted to a double before the division is performed.
Personally I sometimes write such an expression as (double) length / (double) width
to make it clearer what happens. It’s a practice I haven’t seen elsewhere, and I am sure that a lot of programmers will just find my code needlessly long.
What really happens behind the scenes, I don’t know, and we should not care. If some JVM has a way of performing a division of a double
by, say, an int
, it may use it as long as it guarantees to give the same result as if width
had been converted to double
. The language specifies the result of our code, not the implementation.
Nishadi Wickramanayaka is correct in the other answer: the variables themselves are unchanged. Neither the variable length
nor width
change their types. Only values taken from the variables are converted to double
for use in the calculation.