Java Type Casting

Type casting in Java is a process of assigning a value of one primitive data type to another. It is an essential concept in Java programming, enabling flexibility and precision in handling different data types. There are two main types of casting in Java: Widening Casting (automatic) and Narrowing Casting (manual).

Tutorials dojo strip



Widening Casting

Widening casting happens automatically when converting a smaller data type to a larger one. This process is seamless and does not require explicit conversion by the programmer. The order of data types from smaller to larger is as follows:

JAVA


Example of Widening Casting

In this example, the integer smallNum is automatically cast to a double largeNum without any explicit conversion.

JAVA




Narrowing Casting

Narrowing casting must be performed manually, as it involves converting a larger data type to a smaller one. This process requires the programmer to use explicit conversion by placing the target type in parentheses before the value.

JAVA


Example of Narrowing Casting

In this example, the double bigNum is manually cast to an integer smallNum using explicit conversion.

JAVA




Real-Life Application of Type Casting

Type casting can be useful in various real-world scenarios. Consider a program that calculates the percentage of a user’s score in relation to the maximum score in a game. Type casting ensures the result is a floating-point number rather than an integer.

Example

In this example, the integer userPoints is cast to a float before performing the division, ensuring an accurate floating-point result.

JAVA
Tutorials dojo strip