Fundamentals · Medium · Free
What is implicit vs explicit type conversion? Give examples that cause bugs in interviews.
FresherFundamentalsProgramming Fundamentals
Implicit vs explicit conversion
Implicit conversion (widening/coercion) happens when the compiler or runtime promotes a value automatically—e.g., int to double in arithmetic. Explicit conversion (casting/parsing) is intentional: (int) 3.9 or Integer.parseInt("42").
| Bug pattern | Why it bites | Interview fix |
|---|---|---|
| String "10" vs number 10 (JS) | Sort/compare gives wrong order | Normalize types before compare |
total / count with ints | Integer division truncates | Cast numerator to double first |
| Silent float → int cast | Loses cents in billing | Use BigDecimal or integer cents |
java
double avg = (double) total / count;
int port = Integer.parseInt(System.getenv("PORT"));
// Java: widening int→long is implicit; narrowing needs castInterview tip: Give one real bug—"I once fixed a leaderboard that compared string ranks to numbers."