✏️ Explanatory Question

[Primitive Values, Wrapper Classes, Types and Casting]

Complete the code of TeacherA and name the technique used:
TeacherA:
int average = ( ____ )((m1 + m2 + m3) / 3);

TeacherB:
int average = Math.round((m1 + m2 + m3) / 3);

👁 0 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

✅ TeacherA Code:
int average = (int)((m1 + m2 + m3) / 3);
✅ Technique Used: Type Casting (Explicit Type Conversion)

Understanding the Problem:

The variables m1, m2, m3 are of type:

double

So the expression:

(m1 + m2 + m3) / 3

produces a result of type:

double

But we are storing it in:

int average

This causes a:

Compile-time error (incompatible types)

TeacherA Solution:

TeacherA uses type casting:

(int)((m1 + m2 + m3) / 3)

This converts the double result into int.

Important Note:

  • Type casting removes decimal part (truncation)
  • Example: 75.9 → 75

TeacherB Solution:

Math.round((m1 + m2 + m3) / 3)

This performs rounding:

  • 75.4 → 75
  • 75.5 → 76

Comparison:

Teacher Technique Effect
TeacherA Type Casting Removes decimal part
TeacherB Math.round() Rounds to nearest integer

Important Concept:

(double → int) conversion → requires explicit casting

Final Conclusion:

  • TeacherA uses Type Casting
  • TeacherB uses Math.round()
  • Both avoid compile-time error, but behave differently