Lesson 9: Type Casting and Type Conversion
Type conversion, or casting, is the process of changing a value from one data type to another.
1. Implicit Conversion (Widening Conversion)
This happens automatically when converting a smaller type to a larger type (e.g., int to double). Java performs this automatically because there is no risk of losing data.
java int myInt = 100; double myDouble = myInt; // Implicit conversion: 100 becomes 100.0
// Order of widening (safe): byte -> short -> int -> long -> float -> double
long largeNum = 500000; float approxNum = largeNum; // Valid, but precision might be lost if the long is huge
2. Explicit Conversion (Narrowing Conversion)
This requires manually instructing the compiler using parentheses (). It is necessary when converting a larger type to a smaller type (e.g., double to int). Data loss is possible.
java double salary = 50000.75;
// Explicitly cast the double to an int int wholeSalary = (int) salary; // wholeSalary will be 50000 (the .75 is lost)
byte b; int i = 257; // We force the conversion, but data is lost/wrapped around b = (byte) i; // b will be 1 (since 257 > 127)
System.out.println(b); // Output: 1
3. Conversion involving Strings (Non-Primitives)
Converting primitives to Strings and vice-versa requires helper methods, typically from wrapper classes (like Integer or Double).
-
Primitive to String: java int num = 45; String s1 = String.valueOf(num); String s2 = num + ""; // Common shortcut
-
String to Primitive: java String s = "123"; // Use the parse method on the wrapper class int i = Integer.parseInt(s); // i is now 123
String priceStr = "99.50"; double price = Double.parseDouble(priceStr);