- Primitive Type Conversion
- Reference Type Conversion (Objects)
- String Conversion
- Wrapper Class Conversion
- Summary
- Safe, no data loss.
Smaller type→larger type.
| From | To | Example |
|---|---|---|
| byte | short, int, long, float, double | int i = b; |
| short | int, long, float, double | long l = s; |
| char | int, long, float, double | double d = c; |
| int | long, float, double | float f = i; |
| long | float, double | double d = l; |
| float | double | double d = f; |
- May cause data loss.
Larger type→smaller type.
| From | To | Example |
|---|---|---|
| double | float, long, int, short, byte | int i = (int) d; |
| int | short, byte, char | byte b = (byte) i; |
Subclass → Superclass (safe)
Dog dog = new Dog();
Animal a = dog; // UpcastingSuperclass → Subclass (needs cast)
Animal a = new Dog();
Dog d = (Dog) a; // DownCastingNote:
Unsafe if actual object is not the subclass (throws ClassCastException)
int i = 123;
String s = String.valueOf(i); // or "" + i;Use parse methods:
String s = "123";
int i = Integer.parseInt(s);
double d = Double.parseDouble("3.14");
boolean flag = Boolean.parseBoolean("true");Note: Throws NumberFormatException if string is not valid
- Java auto-converts between primitives and wrapper classes:
Autoboxing/Unboxing
Integer iObj = 10; // Autoboxing: int → Integer
int i = iObj; // Unboxing: Integer → intSummary Casting:
| Type | Auto | Needs Cast | Notes |
|---|---|---|---|
| Widening | ✅ | ❌ | Safe |
| Narrowing | ❌ | ✅ | May lose data |
| Upcasting | ✅ | ❌ | Safe, object → parent |
| Downcasting | ❌ | ✅ | Risky, use instanceof |
| String <-> Primitive | ❌ | ✅ | Use parse and valueOf |
Summary Exception:
| Cast | Exception |
|---|---|
Larger type → smaller type |
May cause data loss. Example: int a = 130; byte b = (int) a; result: -126; |
Superclass → Subclass |
May throws ClassCastException |
String → Primitive |
May Throws NumberFormatException |