Type casting in Java is the process of converting a variable from one data type to another. It is used when you need to assign a value of one type to a variable of another type.
Java में Type casting का मतलब है एक variable को एक data type से दूसरे data type में बदलना। यह तब उपयोगी होता है जब एक प्रकार के मान को दूसरे प्रकार के variable में डालना होता है।
We need type casting to:
- Convert between compatible data types.
- Prevent data loss by explicitly controlling conversions.
- Work with different numeric types together.
- Ensure the program runs without type mismatch errors.
हमें Type casting की जरूरत इसलिए पड़ती है ताकि:
- Compatible data types के बीच conversion कर सकें।
- Data loss से बचने के लिए conversions को नियंत्रित कर सकें।
- अलग-अलग numeric types के साथ काम कर सकें।
- प्रोग्राम में type mismatch errors से बचा जा सके।
public class WideningExample {
public static void main(String[] args) {
int i = 100;
long l = i; // int to long
float f = l; // long to float
System.out.println("int: " + i);
System.out.println("long: " + l);
System.out.println("float: " + f);
}
}
Output:
int: 100
long: 100
float: 100.0
Widening casting converts smaller types to larger types automatically.
Widening casting छोटे type को बड़े type में अपने आप convert करता है।
public class NarrowingExample {
public static void main(String[] args) {
double d = 100.04;
long l = (long) d; // double to long
int i = (int) l; // long to int
System.out.println("double: " + d);
System.out.println("long: " + l);
System.out.println("int: " + i);
}
}
Output:
double: 100.04
long: 100
int: 100
Narrowing casting requires explicit casting and may lose data.
Narrowing casting मैन्युअल रूप से करनी पड़ती है और इसमें data loss हो सकता है।
public class CharCastingExample {
public static void main(String[] args) {
char c = 'A';
int ascii = (int) c;
System.out.println("Character: " + c);
System.out.println("ASCII value: " + ascii);
}
}
Output:
Character: A
ASCII value: 65
Casting a char to int gives the ASCII (Unicode) value of the character.
char को int में cast करने से उस character का ASCII (Unicode) value मिलता है।