Data Type Casting in Java

Casting in Java is the process of converting a value of one data type to another data type. There are two types of casting in Java: implicit casting (also known as widening) and explicit casting (also known as narrowing).

Implicit Casting: Implicit casting is an automatic process that happens when a value of a smaller data type is assigned to a variable of a larger data type. For example:

sql
int num = 10; double decimalNum = num; // implicit casting from int to double

In this example, the value of num is automatically casted to a double and assigned to the variable decimalNum.

Explicit Casting: Explicit casting is a manual process that happens when a value of a larger data type is assigned to a variable of a smaller data type. For example:

sql
double decimalNum = 10.5; int num = (int) decimalNum; // explicit casting from double to int

In this example, the value of decimalNum is explicitly casted to an int using the (int) syntax.

It's important to note that when casting from a larger data type to a smaller data type, there is a potential loss of information. For example, when casting from a double to an int, the decimal portion of the value is lost. Therefore, it's important to be careful when using explicit casting to avoid losing important data

Comments

Popular posts from this blog

Java Applet Overview

Applet Vs Application

Cryptography API