Java Type Conversion
Type conversion in Java refers to the process of changing a value from one data type to another. Java supports two kinds of type conversion for primitive t...
Implicit and Explicit Casting Between Java Types
Type conversion in Java refers to the process of changing a value from one data type to another. Java supports two kinds of type conversion for primitive types: widening conversion (also called implicit casting or automatic type promotion) and narrowing conversion (also called explicit casting). Understanding which conversions happen automatically and which require programmer action helps prevent subtle bugs and data loss.
Widening conversion occurs when a value is assigned to a variable of a larger type. Java performs this automatically because no data can be lost. The widening order for numeric types is: byte to short to int to long to float to double. For example, int x = 100; double d = x; is perfectly valid — Java automatically converts the int to a double. Widening also happens in expressions: when you add an int and a double, Java promotes the int to double before performing the addition.
Narrowing conversion goes in the opposite direction — from a larger type to a smaller one. Because this may lose information, Java requires an explicit cast. The syntax is: (targetType) value. For example, double pi = 3.14159; int rounded = (int) pi; stores 3 in rounded, discarding the fractional part. There is no rounding; the fractional bits are simply truncated. Narrowing a long to an int may silently discard the high-order bits if the value does not fit, producing a completely different number.
Casting between char and int is also permitted. A char is internally a 16-bit unsigned integer, so you can write int code = 'A'; which stores 65 (the Unicode code point for 'A'). Conversely, char letter = (char) 65; stores 'A'.
String conversion is handled differently. To convert a primitive to a String, use String.valueOf(value) or concatenate with an empty string: "" + 42 produces "42". To convert a String to a numeric primitive, use the parse methods of the wrapper classes: Integer.parseInt("42") returns the int 42. If the string is not a valid number, parseInt throws a NumberFormatException.
The instanceof operator can be combined with pattern matching (introduced in Java 16) to safely cast reference types: if (obj instanceof String s) { System.out.println(s.length()); } avoids a ClassCastException.
Interview tip: A classic trick question is "what is the result of (int)(3.9 + 0.1)?" The answer is 4, not 3, because 3.9 + 0.1 is first computed as a double (giving approximately 4.0), and then cast to int, which yields 4. Contrast this with (int)3.9 + (int)0.1, which gives 3 + 0 = 3.