0% completed
In Java, type conversion and casting allow us to convert a value of one data type into another. This is useful when you need to work with different types of data in your program.
There are two types of type casting in Java:
Type casting is the process of converting a value from one data type to another. In Java, this can be done in two ways:
Implicit type casting happens automatically when a smaller data type is assigned to a larger data type. This is safe because no data is lost.
byte → short → int → long → float → double
largerType variableName = smallerTypeValue;
Below is an example of widening conversion. Here, the int
value myInt
is automatically converted to a double
value myDouble
.
Explicit type casting is required when a larger data type is converted to a smaller data type. This can result in data loss and requires manual intervention using the casting operator (type)
.
double → float → long → int → short → byte
smallerType variableName = (smallerType) largerTypeValue;
Here, the double
value myDouble
is explicitly cast to an int
. The fractional part (.99
) is lost during this conversion.
In this example, the int
value 130
is explicitly cast to a byte
. Since the byte
range is only -128 to 127
, the value wraps around to -126
.
Sometimes, you may need to combine implicit and explicit casting in a single program.
In the example below, the int
value is implicitly converted to double
, and then the double
value is explicitly cast to float
.
Feature | Implicit Casting (Widening) | Explicit Casting (Narrowing) |
---|---|---|
Process | Automatic | Manual |
Safety | Safe, no data loss | May result in data loss or value wrapping |
Example Conversion | int → double | double → int |
Syntax | largerType variable = smallerValue; | smallerType variable = (smallerType) largerValue; |
Type casting is an essential concept in Java that allows you to handle data flexibly. However, you should be cautious with explicit casting as it may lead to unexpected behavior or data loss. Practice these examples to understand how and when to use type casting effectively.
In the next lesson, we will explore Java Basic Input and Output, where we’ll learn to read and display data in Java programs.
.....
.....
.....