DEV Community

Rajan S
Rajan S

Posted on

Type casting

Java Type Casting

*java type casting *

Type casting in Java is the process of converting one data type into another. It is essential when you want to perform operations between different data types or when you need to store a value of one type into a variable of another type. Java supports two types of casting: implicit (automatic) casting and explicit (manual) casting.

Type casting is when you assign a value of one primitive data type to another type.

In Java, there are two types of casting:

  1. Widening Casting(implicit) (automatically) - converting a smaller type to a larger type size byte -> short -> char -> int -> long -> float -> double

Here’s an example to illustrate widening type casting in Java

  1. Narrowing Casting(explicit)
    (manually) - converting a larger type to a smaller size type
    double -> float -> long -> int -> char -> short -> byte

    1. Widening or Automatic type converion

Automatic Type casting take place when,

  1. the two types are compatible
  2. the target type is larger than the source type

Example:

2.Narrowing or Explicit type conversion

When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit type casting. If we don't perform casting then compiler reports compile time error.

Example :

Example of Explicit Conversion

Here, we have one more example of explicit casting, double type is stored into long, long is stored into int etc.

Top comments (0)