Java Type Casting

Java Type Casting (Type Conversion)

Type casting in Java is the process of converting a variable from one data type to another. There are two types of type casting:


1. Widening Casting (Automatic / Implicit Conversion)

Converts a smaller type → larger type automatically.
No data loss occurs.

FromTo
byte → short → int → long → float → double

Example:


 


🚀 2. Narrowing Casting (Manual / Explicit Conversion)

Converts a larger type → smaller type manually.
May result in data loss.

Example:


 


🎯 Important Notes

  • Widening Casting is safe since Java handles it automatically.

  • Narrowing Casting may lose precision, especially with decimals.


Additional Example:


 


🎉 Summary Table

TypeType CastingAutomatic?Risk
WideningSmall → LargeYesNo
NarrowingLarge → SmallNoYes (data loss)

You may also like...