Type Conversion and Casting in Java and Kotlin
Type conversion and casting define how one data type is converted into another. This topic is critical for interviews, JVM understanding, and bug-free coding, especially when working with primitives, wrappers, and mixed-type expressions.
Table of Contents
1. Type Conversion Basics
Type conversion is the process of converting one data type into another. It usually happens when assigning values or performing operations.
There are two main types:
- Implicit (Widening) – automatic
- Explicit (Narrowing) – manual casting
2. Implicit (Widening) Conversion
Implicit conversion happens when a smaller data type is converted to a larger one. There is no data loss.
Java Example
int a = 10;
long b = a; // int → long
double c = b; // long → double
Kotlin Example
val a: Int = 10
val b: Long = a.toLong()
val c: Double = b.toDouble()
📌 Important: Unlike Java, Kotlin does not perform implicit numeric widening automatically.
3. Explicit (Narrowing) Casting
Explicit casting is required when converting from a larger type to a smaller type. This can cause data loss.
Java Example
double d = 10.75;
int i = (int) d; // explicit cast
Kotlin Example
val d: Double = 10.75
val i: Int = d.toInt()
Kotlin uses conversion functions instead of cast operators, making conversions explicit and safer.
4. Kotlin Type Rules (Why Kotlin Is Strict)
Kotlin enforces strict type conversion rules to prevent runtime bugs.
- No implicit numeric conversion
- No unsafe casts by default
- Null safety enforced at compile time
val x: Int = 5
// val y: Long = x // Compilation error
val y: Long = x.toLong() //correct
This design improves code readability and safety.
5. Java and Kotlin – Type Conversion Comparison
| Aspect | Java | Kotlin |
|---|---|---|
| Implicit numeric conversion | Yes | No |
| Explicit casting | (int), (double) | toInt(), toDouble() |
| Null safety | No | Yes |
| Runtime safety | Medium | High |
6. Interview Questions & Answers
Q1. What is type casting?
Answer: Manually converting one data type to another compatible type.
Q2. Why does Kotlin not allow implicit numeric conversion?
Answer: To avoid hidden bugs and make conversions explicit and readable.
Q3. Can type casting cause data loss?
Answer: Yes, narrowing conversions can truncate or overflow values.
Q4. How does Kotlin handle unsafe casts?
Answer: Using as? for safe casting, which returns null instead of crashing.
7. Conclusion
Type conversion is simple in concept but critical in practice. Java prioritizes convenience, while Kotlin prioritizes safety and clarity.
Mastering this topic helps you:
- Write safer JVM code
- Avoid subtle runtime bugs
- Answer interview questions confidently
Comments
Post a Comment