🟢 Foundation · Lesson 08
Type Casting in Java
Type Casting in Java
What is Type Casting?
Type casting converts a value from one data type to another. Java has two kinds: widening (automatic) and narrowing (manual).
Widening (Automatic)
Smaller type → larger type happens automatically, no data loss.
int x = 10;
double d = x; // int to double, automatic
System.out.println(d); // 10.0
Narrowing (Manual)
Larger type → smaller type needs an explicit cast and may lose data.
double price = 99.9;
int p = (int) price; // manual cast
System.out.println(p); // 99 (decimal lost)
Summary
- Widening (small→large) is automatic and safe.
- Narrowing (large→small) needs
(type)and may lose data.
Type Casting क्या है?
Type casting value को एक data type से दूसरे में बदलता है। Java में दो तरह: widening (automatic) और narrowing (manual)।
Widening (Automatic)
छोटा type → बड़ा type अपने आप होता है, कोई data loss नहीं।
int x = 10;
double d = x; // int से double, automatic
System.out.println(d); // 10.0
Narrowing (Manual)
बड़ा type → छोटा type के लिए explicit cast चाहिए, data जा सकता है।
double price = 99.9;
int p = (int) price; // manual cast
System.out.println(p); // 99 (decimal गया)
सारांश
- Widening (छोटा→बड़ा) automatic और safe।
- Narrowing (बड़ा→छोटा) को
(type)चाहिए, data जा सकता है।