Module 2: Variables, Data Types, and Operators
Lesson focusType Conversion and Casting
Understand how Java handles data type conversions, including implicit (widening) and explicit (narrowing) casting, and the potential for data loss.
Why Convert Types? Sometimes you need to operate on values of different data types. Java handles this through type conversion.
Widening Conversion (Implicit): This happens automatically when you move a value from a smaller data type to a larger one. It is safe because there is no risk of data loss.
byte -> short -> int -> long -> float -> double
- For example, you can assign an
intto adoublevariable without any special syntax:int myInt = 100; double myDouble = myInt; // This is fine
Narrowing Conversion (Explicit Casting): This is when you move a value from a larger data type to a smaller one. This is potentially unsafe as you might lose information. You must tell the compiler you are aware of the risk by performing an explicit cast.
- To cast, you place the target data type in parentheses before the value:
(targetType) value
- Example (Data Loss):
double price = 99.99; int intPrice = (int) price; // intPrice is now 99. The .99 is truncated.
- Example (Out of Range):
int largeInt = 300; byte smallByte = (byte) largeInt; // smallByte will have a strange value because 300 is outside the byte range (-128 to 127).
Rules for Expressions: When an arithmetic expression involves different data types, Java promotes the smaller types to the larger type before performing the operation. For example, if you add an int and a double, the int is first converted to a double, and the result is a double.
// Widening (implicit) conversion
int myInt = 5;
double myDouble = myInt; // Automatically converted
System.out.println(myDouble); // 5.0
// Narrowing (explicit) conversion
double pi = 3.14159;
int approxPi = (int) pi; // Must be explicitly cast
System.out.println(approxPi); // 3 (data loss!)
// Be careful with byte range
int x = 257;
byte y = (byte) x;
System.out.println(y); // 1 (wraps around!)Lesson quiz