Typecasting is changing a variable from one data type to another, transferring the value of one type to another. It is necessary in Java due to the need for many operations and can be done in two different ways:
Implicit
Explicit
Implicit type casting occurs when a value of one data type gets assigned to another compatible data type. On the other hand, explicit type casting is the process of forcefully converting a data type into another data type by specifying the target type in parentheses before the value is converted.
What is Type Casting?
Type casting or type conversion is the fundamental concept in programming that converts one type into another. This process is crucial for ensuring compatibility and flexibility within a program.
Primitive Type Casting
Reference Type Casting
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Primitive Data Types
Primitive data types are Java’s simplest form of data type. They store single values and do not require additional memory for object overhead. The Java language predefined these types, representing the most basic kind of data that can be used in Java.
byte
short
int
long
float
double
char
boolean
Types of Casting in Java
There are two types of casting in Java.
Widening Type Casting (Automatic Type Conversion)
Narrow Type Casting (Explicit Type Conversion)
Widening Type Casting in Java( Automatic Type Conversion)
It is the automatic type conversion in Java. It converts a smaller data type to a larger data type. This process does not require explicit casting by the programmer because it is done automatically by the Java compiler. Widening conversions are always safe because they do not lose information.
The following program demonstrates the widening type casting:
Program
public class Main {
public static void main(String[] args) {
int intValue = 100;
long longValue = intValue;
float floatValue = longValue;
double doubleValue = floatValue;
System.out.println("int value: " + intValue);
System.out.println("long value: " + longValue);
System.out.println("float value: " + floatValue);
System.out.println("double value: " + doubleValue);
}
}
Output
int value: 100
long value: 100
float value: 100.0
double value: 100.0
Narrowing Casting (Explicit Type Conversion)
This type of conversion refers to converting a larger data type into a lower one. It is also known as explicit type casting or casting up. It does not happen on its own. Narrow-type casting is not secure, as data loss can occur due to a shortage of supported values in the lower data type.
Syntax
// var is of lowerDataType
var = (lowerDataType) expr;
The following program demonstrates the narrowing casting:
double value: 100.04
float value: 100.04
long value: 100
int value: 100
Type Conversion in Java
As mentioned before, there are two types of conversions in the Java language:
Implicit Type Conversion
Explicit Type Conversion
Implicit Type Conversion (Narrowing Conversion)
Implicit type conversion occurs automatically by the Java compiler when a smaller data type is assigned to a larger one. This type of conversion is also known as widening conversion, which involves converting a type.
The following program demonstrates the implicit type conversion in Java:
Program
public class ImplicitTypeConversion {
public static void main(String[] args) {
int num1 = 100;
double num2;
num2 = num1;
System.out.println("Integer value: " + num1);
System.out.println("Converted double value: " + num2);
}
}
Output
Integer value: 100
Converted double value: 100.0
Explicit Type Conversion
Explicit Type conversion, or narrowing conversion, is required to convert a larger data type to a smaller one. This conversion can lead to data loss, so the programmer must explicitly do it using the typecasting.
The following program demonstrates the explicit type conversion in Java:
Program
public class ExplicitTypeConversionExample {
public static void main(String[] args) {
double doubleValue = 9.78;
int intValue = (int) doubleValue;
System.out.println("Double value: " + doubleValue);
System.out.println("Converted to int: " + intValue);
long longValue = 10000L;
short shortValue = (short) longValue;
System.out.println("Long value: " + longValue);
System.out.println("Converted to short: " + shortValue);
float floatValue = 15.99F;
byte byteValue = (byte) floatValue;
System.out.println("Float value: " + floatValue);
System.out.println("Converted to byte: " + byteValue);
int anotherIntValue = 65;
char charValue = (char) anotherIntValue;
System.out.println("Int value: " + anotherIntValue);
System.out.println("Converted to char: " + charValue);
}
}
Output
Double value: 9.78
Converted to int: 9
Long value: 10000
Converted to short: 10000
Float value: 15.99
Converted to byte: 15
Int value: 65
Converted to char: A
Advantages and Disadvantages of Explicit Type Casting in Java
The tabular representation of the advantages and disadvantages of explicit type casting in Java language:
Aspect
Advantages
Disadvantages
Precision Control
This allows precise control over the data
It may result in the loss of precision especially when converting from floating-point to integers types.
Compatibility
This enables the conversion of incompatible data types(eg, ‘double’ to ‘int’).
This increases the complexity of the source code. It makes it harder to read and maintain
Memory Management
This optimizes memory usage by casting larger types into smaller ones.
It can lead to data loss when converting larger data types to smaller ones
Risk Data Loss
This is not applicable
Loss of data, such as truncation of decimal points when casting ‘double’ to ‘int’
Potential for Bugs
It is not applicable (related disadvantages)
These bugs may be subtle and hard to detect when explicit casting is used incorrectly.
Conclusion
Type casting is the process that allows data of one particular type to be changed into another. It may be either automatic or explicit, depending on the type involved and requirements in the operations being applied. Typecasting knowledge is quite essential in programming.
It helps developers handle different kinds of data more effectively, optimize memory usage, and ensure correct source functioning across various scenarios. By understanding it, developers can implicitly and explicitly cast effectively.
FAQs
What is type casting in Java?
Type casting in Java converts a variable from one data type to another. It can be either implicit (automatic) or explicit (manual).
What is the difference between implicit and explicit type casting?
Implicit type casting occurs automatically when converting a smaller data type to a larger one (eg ‘int’ to ‘long’). Explicit type casting requires manual conversion, typically from a larger data type to a smaller one (eg ‘double ‘ to ‘int’).
When is implicit type casting used in Java?
Implicit type casting is used when the source data type is smaller than the target data type, and the conversion is safe and does not result in data loss. This commonly occurs in assignments and arithmetic operations.
What are the risks associated with explicit type casting?
The main risks include data loss (e.g. losing the fractional part when casting from ‘double’ to ‘int’) and potential runtime errors like ‘ ClassCastException’ when casting incompatible types.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.