Skip to content

Latest commit

 

History

History
109 lines (88 loc) · 3.81 KB

File metadata and controls

109 lines (88 loc) · 3.81 KB

Conversion

1. Primitive Type Conversion

Widening Conversion (Automatic / Implicit)

  • Safe, no data loss. Smaller typelarger 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;

Narrowing Conversion (Manual / Explicit)

  • May cause data loss. Larger typesmaller type.
From To Example
double float, long, int, short, byte int i = (int) d;
int short, byte, char byte b = (byte) i;

2. Reference Type Conversion (Objects)

a. Upcasting (Automatic)

SubclassSuperclass (safe)

Dog dog = new Dog();
Animal a = dog;  // Upcasting

b. DownCasting (Manual)

SuperclassSubclass (needs cast)

Animal a = new Dog();
Dog d = (Dog) a;  // DownCasting

Note: Unsafe if actual object is not the subclass (throws ClassCastException)


3. String Conversion

a) Primitive → String

int i = 123;
String s = String.valueOf(i);  // or "" + i;

b) String → Primitive

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


4. Wrapper Class Conversion

  • Java auto-converts between primitives and wrapper classes: Autoboxing / Unboxing
Integer iObj = 10;       // Autoboxing: int → Integer
int i = iObj;            // Unboxing: Integer → int

5.Summary

Summary 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 typesmaller type May cause data loss. Example: int a = 130; byte b = (int) a; result: -126;
SuperclassSubclass May throws ClassCastException
StringPrimitive May Throws NumberFormatException