Codectionary / Developer documentation / Java

Type Casting

Type casting converts a value from one data type to another. Widening (implicit) casting happens automatically when converting a smaller type to a larger one, like int to double, since no data can be lost. Narrowing (explicit) casting requires you to manually write the target type in parentheses, since converting a larger type to a smaller one - like double to int - can lose data or precision.

Syntax

(targetType) value

Examples

Widening (Implicit) Casting

Automatic conversion from a smaller type to a larger one - safe, no data loss.

int num = 100;
double converted = num;  // int -> double, happens automatically

System.out.println(converted);  // 100.0

long bigNumber = num;    // int -> long, also automatic
System.out.println(bigNumber);

Narrowing (Explicit) Casting

Manually converting a larger type to a smaller one - potential data loss, so it must be explicit.

double price = 19.99;
int wholePrice = (int) price;  // explicit cast required

System.out.println(wholePrice);  // 19 (decimal part is truncated, not rounded)

long bigValue = 1234567890123L;
int truncated = (int) bigValue;  // may overflow/produce unexpected results
System.out.println(truncated);

Casting Between String and Numeric Types

Strings require conversion methods rather than a simple cast, since String and numeric types are unrelated.

String numberText = "42";
int parsed = Integer.parseInt(numberText);
double parsedDouble = Double.parseDouble("3.14");

System.out.println(parsed + 8);         // 50
System.out.println(parsedDouble * 2);   // 6.28

int value = 100;
String asText = String.valueOf(value);
System.out.println(asText + " units");  // "100 units"

Best practices

  • Use explicit casting only when you understand and accept the potential loss of precision or data
  • Use Integer.parseInt() / Double.parseDouble() to convert String to a number - a direct cast does not work between them
  • Wrap Integer.parseInt() in a try/catch for NumberFormatException when parsing text that might not be a valid number
  • Prefer widening conversions (letting Java do it automatically) over narrowing ones whenever the larger type is acceptable for your use case

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading