Return type

exercise No. 205

Q:

We consider a method computing a circle's area:

static public float getArea (int radius) {
  return radius * radius * 3.1415926;
}
  1. Compilation fails due to the following error:

    Required type: float
    Provided: double

    Explain the error message.

    Tip

    Dissect the underlying expression.

  2. You are not allowed to change the method's signature. What is the cleanest way to correct the programming error?

A:

  1. The expression radius * radius * 3.1415926 is being evaluated from left to right. The literal 3.1415926 is of type double. We thus have:

    int * int * double
      \   /      /
       int * double
         \    /
         double
  2. Replacing the double literal by a float literal leaves us with an overall float expression resolving the issue:

    radius * radius * 3.1415926F
    
       int * int * float
         \   /     /
          int * float
            \   /
            float