Syntax
(targetType) valueExamples
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