Basic Syntax
Type Casting and Conversion
Explore widening (implicit) and narrowing (explicit) numeric conversions, character mappings, and runtime casting rules.
Interview: Heavily tested on arithmetic promotion rules, narrowing overflow truncation, and ClassCastException.
Type conversion occurs when a value of one type is converted to another type. Java supports two types of conversions: Implicit Widening Conversion (performed automatically by the compiler) and Explicit Narrowing Conversion (requiring the cast operator).
Core Idea
Widening moves data to larger types safely. Narrowing forces values into smaller types, potentially causing data truncation or loss of precision.
Why It Matters
Java's math rules automatically promote variables to at least 32-bit ints, which can cause compile-time type mismatch errors.
Interview Lens
Tests numeric promotions, downcasting errors in class hierarchies, and using pattern matching instanceof.
Widening vs Narrowing
1. Widening Conversion (Implicit)
Occurs when converting a smaller type to a larger type without risk of data loss. Order:
byte ---> short ---> int ---> long ---> float ---> double
The compiler performs this automatically (e.g. int x = 10; double d = x;).
2. Narrowing Conversion (Explicit)
Occurs when converting a larger type to a smaller type. Because data loss can occur, the compiler requires an explicit cast operator (e.g. (type)).
Narrowing Behavior: Floating-point values are truncated (decimals discarded). Integers that exceed the smaller type's capacity are truncated using modulo arithmetic, which can flip the sign bit.
Arithmetic Promotion Rules
When evaluating expressions, the compiler automatically promotes operands:
- All
byte,short, andcharvalues are promoted tointbefore mathematical operations are performed. - If one operand is
double, the entire expression is promoted todouble. - Otherwise, if one operand is
float, the expression is promoted tofloat. - Otherwise, if one operand is
long, the expression is promoted tolong.
Common Pitfalls
- Integer Overflow Before Casting: Writing code like
long micros = 1000 * 1000 * 1000 * 1000;causes an overflow. The calculation is performed using 32-bit ints first, and the overflowed result is then cast to a long. To fix this, suffix one of the numbers withL(e.g.,1000L * ...). - ClassCastExceptions in Reference Types: Attempting to downcast an object reference to a subclass type without validating the actual object type first throws a runtime
ClassCastException.
Best Practices
- Use Math.toIntExact() for Safe Downcasting: When converting a long to an int, use
Math.toIntExact(longVal). This throws anArithmeticExceptionif the value overflows, preventing silent data truncation. - Use Modern Pattern Matching for Downcasting: Since Java 16, use pattern matching for
instanceof(e.g.,if (obj instanceof String s)) to avoid manual type casting.
Interview-Relevant Information
Q1: Why does byte b1 = 1; byte b2 = 2; byte b3 = b1 + b2; fail to compile?
Answer: In Java, arithmetic operations automatically promote byte variables to int. The result of b1 + b2 is an int, and assigning this result to b3 requires an explicit cast (e.g., b3 = (byte)(b1 + b2);).
Q2: What happens when you cast a float containing 3.99 to an int?
Answer: The value is truncated (fractional part discarded), resulting in the integer value 3 (not rounded to 4).
Quick Checklist
Can you order the widening conversion chain, write code to catch casting exceptions, and explain why byte variables promote to ints during addition? If yes, you understand Java type casting.
Use Cases
Downcasting object instances using pattern matching inside event processor pipelines.
Casting long timestamps to integer values for legacy API payloads safely using Math.toIntExact.
Common Mistakes
Assuming floating-point casts automatically round values (e.g. thinking (int)3.99 rounds to 4).
Failing to cast arithmetic promotions back to short/byte variables.