My Perspective:
Todays topic is about typecasting first of all i learnt a new topic which is more required for the basic of programmig and interview questions.
I have reffered some of the interview questions from my brothers they said that this would be a basic questions but many of them don't know how it really works and here is the explanation and few examples that anyone can easily understand.
What is Typecasting?
- When working with variables in Java, sometimes we need to convert one data type into another.
- This process is called typecasting.
- It’s very common when dealing with numbers, characters, or objects.
Example:
Here, the int value is automatically converted into a double.
Types of Typecasting in Java
- Widening (Implicit) Typecasting.
- Narrowing (Explicit) Typecasting.
- Typecasting with Characters.
1)Widening (Implicit) Typecasting:
- Happens automatically when converting a smaller data type to a larger one.
- No data loss.
Order in numeric type:
byte → short → int → long → float → double
Example:
**
** Output****:Integer: 100
Double (after widening): 100.0
2) Narrowing (Explicit) Typecasting:
- Conversion from a larger type to a smaller type.
- Must be done manually using (datatype).
- May cause data loss or overflow.
Example:
** Output**: Double: 99.99
Integer (after narrowing): 99
3)Typecasting with Characters:
- Characters (char) in Java are stored as Unicode values.
- This means you can typecast between char and int.
- Example:
Output:Character: A
ASCII Value: 65
Integer: 66
Character: B
Top comments (0)