Type Casting and Conversion

Implicit and explicit type conversion

Interview Relevant: Important for understanding data type compatibility
7 min read

What is Type Casting?

Type casting is converting a variable of one data type to another. There are two types: widening (automatic) and narrowing (explicit).

Widening Conversion (Implicit)

Converting from a smaller data type to a larger one. This happens automatically:

byte → short → int → long → float → double

āœ“ Safe: Widening conversion never loses data.

Narrowing Conversion (Explicit)

Converting from a larger data type to a smaller one. This requires explicit casting and may lose data:

double → float → long → int → short → byte

āš ļø Risky: Narrowing conversion can lose data. Only use when necessary!

String Conversion

Converting between Strings and other types is very common:

  • String to int: Integer.parseInt()
  • int to String: String.valueOf() or concatenation
  • String to double: Double.parseDouble()

Code Examples

Automatic widening conversion from smaller to larger types

java
1// Widening conversion (implicit)
2int intValue = 100;
3long longValue = intValue;  // int to long
4double doubleValue = intValue;  // int to double
5
6System.out.println(longValue);    // 100
7System.out.println(doubleValue);  // 100.0

Narrowing conversion requires explicit casting with (type)

java
1// Narrowing conversion (explicit)
2double doubleValue = 95.5;
3int intValue = (int) doubleValue;  // explicit cast required
4
5System.out.println(intValue);  // 95 (loses decimal part)
6
7long longValue = 50000;
8int intValue2 = (int) longValue;  // explicit cast required

Converting between Strings and numeric types

java
1// String conversion
2// String to int
3String str = "123";
4int number = Integer.parseInt(str);  // "123" → 123
5System.out.println(number + 1);  // 124
6
7// int to String
8int value = 456;
9String strValue = String.valueOf(value);  // 456 → "456"
10String strValue2 = "" + value;  // also works
11
12// String to double
13String decimalStr = "3.14";
14double pi = Double.parseDouble(decimalStr);  // "3.14" → 3.14

Use Cases

  • Converting user input from String to numeric types
  • Storing values in appropriate data types for calculations
  • Preventing data loss by choosing correct types
  • Working with APIs that expect specific data types
  • Mathematical operations requiring consistent types

Common Mistakes to Avoid

  • Losing decimal places when narrowing double to int
  • Forgetting explicit cast for narrowing conversions
  • Not handling NumberFormatException when parsing strings
  • Assuming automatic conversion for incompatible types
  • Mixing int and double without explicit conversion in calculations