Skip to main content

GroTechMinds

GroTechMinds logo

Primitive Type Casting in Java: Widening and Narrowing

Introduction:

Primitive type casting is an important concept in Java, that allows us to convert one primitive data type into another. This process can be broadly classified into two types, namely widening and narrowing. Understanding these concepts is very much essential for writing efficient Java programs. With this blog, let us have a detailed overview of primitive type casting with examples to further our understanding.

Range of data type:

To understand typecasting, we must understand the range of the data types we are going to upcast. The range can be calculated using the formula “-2^(n-1) to (-2^(n-1))-1”, where n is the bits value corresponding to each data type. The range of various data types and how to calculate them are given as follows.

Code Snippet:
Output Screenshot:
java 1
What is Type Casting?

Type casting is the process of converting a variable from one data type to another. In Java, there are two main types of type casting for primitive data types.

java 2
1. Widening (can be done implicitly and explicitly)

Widening is the conversion of a smaller data type into a larger one. This type of casting is done automatically by Java and does not require any explicit syntax.

Code Snippet:
Output Screenshot:
java 3
2. Narrowing (can be done only in explicit way)

Narrowing is the conversion of a larger data type into a smaller one. Unlike widening, this type of casting requires explicit syntax.

Code Snippet:
Output Screenshot:
java 4
Compilation error when we try narrowing implicitly:
java 5
Some Important Considerations when it comes to primitive type casting:
1. Data Loss: Narrowing can result in data loss.

(e.g.,) type casting a double value to a float variable will discard all the fractional parts except the six digits after the decimal place, and when it is converted into int data type, all the decimal places are lost.

Code Snippet:
Output Screenshot:
java 6
2. Range Overflow:

When casting larger integers to smaller integers (e.g., int to byte), if the value exceeds the range of the smaller type, it wraps around. In narrowing data overflow happens as a result of a data type’s smaller value range.

Code Snippet:
Output Screenshot:
java 7
  1. Since widening happens from a smaller data type to a bigger data type, there is space for accommodation, and data loss or data overflow is not a concern when it comes to widening.
Conclusion:

In Java, primitive type casting is a very fundamental concept that allows us to convert a value to a value that represents our desired data type in correspondence with its range. Remember to practice, stay updated with the latest trends in Automation Software Testing Course, and maintain a positive attitude throughout your interview process.Understanding the differences between widening and narrowing is crucial for writing robust and reliable programs.

Also read: