DEV Community

Ligouri S Tittus
Ligouri S Tittus

Posted on

Typecasting and (Notes)

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?

  1. When working with variables in Java, sometimes we need to convert one data type into another.
  2. This process is called typecasting.
  3. 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

  1. Widening (Implicit) Typecasting.
  2. Narrowing (Explicit) Typecasting.
  3. Typecasting with Characters.

1)Widening (Implicit) Typecasting:

  1. Happens automatically when converting a smaller data type to a larger one.
  2. 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:

  1. Conversion from a larger type to a smaller type.
  2. Must be done manually using (datatype).
  3. May cause data loss or overflow.

Example:


** Output**: Double: 99.99
Integer (after narrowing): 99

3)Typecasting with Characters:

  1. Characters (char) in Java are stored as Unicode values.
  2. This means you can typecast between char and int.
  3. Example:

Output:Character: A
ASCII Value: 65
Integer: 66
Character: B

Top comments (0)