0

As far as I know Java has automatic casts for transforming compatible data types from smaller to larger since no data is lost, yet in one of the test programs in my JDK 8 beginners guide book, a cast is used this way. The method fuelNeeded is of question. I know it prints the same double result without the cast so why is this needed? Or is it?


class Vehicle {
    int passengers;
    int fuelcap;
    int mpg;

    Vehicle (int p, int f, int m) {
        passengers = p;
        fuelcap = f;
        mpg = m;
    }

    int range() {
        return mpg * fuelcap;
    }

    double fuelNeeded(int miles) {
        return (double) miles / mpg;
    }

}

public class CompFuel {

    public static void main(String[] args) {

        Vehicle minivan = new Vehicle(7, 16, 21);
        Vehicle supra = new Vehicle(2, 14, 12);
        double gallons;
        int dist = 252;

        gallons = minivan.fuelNeeded(dist);
        System.out.println("To go " + dist + " miles, minivan needs " + gallons + " gallons of fuel");

        gallons = supra.fuelNeeded(dist);
        System.out.println("To go " + dist + " miles, supra needs " + gallons + " gallons of fuel");

    }

}
Glamy
  • 1
  • 2

1 Answers1

1

If you try removing the cast, and trying something like 1/2, the return value will be 0.0. with the cast, return value will be 0.5.

There is a difference because of the cast - explicitly casting the variable miles to double makes the overall division a division between a double and int, this gives us a double value. Not casting would result in an int division.

Sidak
  • 1,213
  • 6
  • 11
  • You are right :) – Glamy Apr 30 '20 at 10:59
  • But whats the point of declaring the method with the double type if you have to write a cast anyways, seems weird in this situation. – Glamy Apr 30 '20 at 11:06
  • Declaring the method return value type is different from what you're calculating using the cast. Assume the return type is `int`, the value returned will not have floating point values like `1`. If the return value is `double`, even if there is integer division, there will be a floating point value like `1.0` – Sidak Apr 30 '20 at 12:48