Java Type Casting

Java Type Casting

Java Type Casting

Java Type Casting:

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

  1. Implicit Casting: Implicit casting occurs automatically when a value of a smaller data type is assigned to a variable of a larger data type. For example:
				
					int num = 10;
double dNum = num; // implicit casting from int to double 

				
			

In this example, the integer value 10 is assigned to the double variable dNum. Since double has a larger range than int, the conversion happens automatically.

  1. Explicit Casting: Explicit casting is required when a value of a larger data type is assigned to a variable of a smaller data type. For example:
				
					double dNum = 10.5;
int num = (int) dNum; // explicit casting from double to int 

				
			

In this example, the double value 10.5 is assigned to the integer variable num. Since int has a smaller range than double, the conversion needs to be done explicitly using a cast operator “(int)”.

It is important to note that explicit casting can result in loss of data or precision. For example, when casting a double value to an integer, the fractional part of the value is lost.

 

Join To Get Our Newsletter
Spread the love