In Java, typecasting is the process of converting one data type to another data type using the casting operator. When you assign a value from one primitive data type to another type, this is known as type casting. To enable the use of a variable in a specific manner, this method requires explicitly instructing the Java compiler to treat a variable of one data type as a variable of another data type.
Syntax:
<datatype> variableName = (<datatype>) value;
Types of Type Casting
There are two types of Type Casting in Java:
- Widening Type Casting
- Narrow Type Casting
1. Widening Type CastingĀ (Implicit Casting)
A lower data type is transformed into a higher one by a process known as widening type casting. Implicit type casting and casting down are some names for it. It occurs naturally. Since there is no chance of data loss, it is secure. Widening Type casting occurs when:
- The target type must be larger than the source type.
- Both data types must be compatible with each other.
Note: Widening type casting is also sometimes called upcasting for primitives, but it is not correct to call it casting down.
Syntax:
larger_data_type variable_name = smaller_data_type_variable;
Example:
Java
// Java program to demonstrate Widening TypeCasting
import java.io.*;
class Geeks {
public static void main(String[] args)
{
int i = 10;
// Wideing TypeCasting (Automatic Casting)
// from int to long
long l = i;
// Wideing TypeCasting (Automatic Casting)
// from int to double
double d = i;
System.out.println("Integer: " + i);
System.out.println("Long: " + l);
System.out.println("Double: " + d);
}
}
OutputInteger: 10
Long: 10
Double: 10.0
2. Narrow Type Casting (Explicit Casting)
The process of downsizing a bigger data type into a smaller one is known as narrowing type casting. Casting up or explicit type casting are other names for it. It doesn't just happen by itself. If we don't explicitly do that, a compile-time error will occur. Narrowing type casting is unsafe because data loss might happen due to the lower data type's smaller range of permitted values. A cast operator assists in the process of explicit casting.
Syntax:
smaller_data_type variable_name = (smaller_data_type) larger_data_type_variable;
Example:
Java
// Java Program to demonstrate Narrow type casting
import java.io.*;
class Geeks {
public static void main(String[] args)
{
double i = 100.245;
// Narrowing Type Casting
short j = (short)i;
int k = (int)i;
System.out.println("Original Value before Casting"
+ i);
System.out.println("After Type Casting to short "
+ j);
System.out.println("After Type Casting to int "
+ k);
}
}
OutputOriginal Value before Casting100.245
After Type Casting to short 100
After Type Casting to int 100
Types of Explicit Casting
Mainly there are two types of Explicit Casting:
- Explicit Upcasting
- Explicit Downcasting
1. Explicit UpcastingĀ
Upcasting is the process of casting a subtype to a supertype in the inheritance tree's upward direction. When a sub-class object is referenced by a superclass reference variable, an automatic process is triggered without any further effort.Ā
Example:
Java
// Java Program to demonstrate Explicit Upcasting
import java.io.*;
class Animal {
public void makeSound()
{
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
public void makeSound()
{
System.out.println("The dog barks");
}
public void fetch()
{
System.out.println("The dog fetches a ball");
}
}
class Geeks {
public static void main(String[] args)
{ // Upcasting
Animal animal = new Dog();
// Calls the overridden method in Dog class
animal.makeSound();
// This would give a compile error as fetch() is not
// a method in Animal class
// animal.fetch();
}
}
2. Explicit Downcasting
When a subclass type refers to an object of the parent class, the process is referred to as downcasting. If it is done manually, the compiler issues a runtime ClassCastException error. It can only be done by using the instanceof operator. Only the downcast of an object that has already been upcast is possible.
Example:
Java
// Java Program to demonstrate Explicit downcasting
import java.io.*;
class Animal {
public void eat()
{
System.out.println("The animal is eating.");
}
}
class Cat extends Animal {
public void meow()
{
System.out.println("The cat is meowing.");
}
}
class Geeks {
public static void main(String[] args)
{
Animal animal = new Cat();
animal.eat();
// Explicit downcasting
Cat cat = (Cat)animal;
cat.meow();
}
}
OutputThe animal is eating.
The cat is meowing.
Typecasting is also applicable to reference types, but must be done carefully. Casting an object to an incompatible type will result in a ClassCastException at runtime.
Object obj = "hello"; // A String stored in an Object
String s = (String) obj; // Valid cast, no error
Integer i = (Integer) obj; // Runtime error: ClassCastException
To avoid such issues, it's good practice to use the instanceof operator before downcasting:
if (obj instanceof String) {
String s = (String) obj;
System.out.println("String value: " + s);
}
Similar Reads
Integer toString() in Java
The java.lang.Integer.toString() is an inbuilt method in Java which is used to return the String object representing this Integer's value. Syntax : public static String toString() Parameters: The method does not accept any parameters. Return Value:The method returns the string object of the particul
5 min read
String to int in Java
Converting a String to an int in Java can be done using methods provided in the Integer class, such as Integer.parseInt() or Integer.valueOf() methods. Example:The most common method to convert a string to a primitive int is Integer.parseInt(). It throws a NumberFormatException if the string contain
2 min read
Overriding in Java
Overriding in Java occurs when a subclass or child class implements a method that is already defined in the superclass or base class. When a subclass provides its own version of a method that is already defined in its superclass, we call it method overriding. The subclass method must match the paren
15 min read
Upcasting in Java with Examples
Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features (fields and methods) of another class. There are two ways in which the objects can be initialized while inheriting the properties of the parent an
4 min read
Variance in Java
Variance refers to how subtyping between more complex types relates to subtyping between their components. âMore complex types" here refers to higher-level structures like containers and functions. So, variance is about the assignment compatibility between containers and functions composed of parame
6 min read
Upcasting Vs Downcasting in Java
Typecasting is one of the most important concepts which basically deals with the conversion of one data type to another datatype implicitly or explicitly. In this article, the concept of typecasting for objects is discussed. Just like the data types, the objects can also be typecasted. However, in o
3 min read
Shift Operator in Java
Operators in Java are used to performing operations on variables and values. Examples of operators: +, -, *, /, >>, <<. Types of operators: Arithmetic Operator,Shift Operator,Relational Operator,Bitwise Operator,Logical Operator,Ternary Operator andAssignment Operator. In this article, w
4 min read
Type Erasure in Java
In Java, Generic provides tighter type checks at compile time and also enable generic programming. The way to implement generics, the Java compiler applies type erasure to: Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced byt
3 min read
Method Overloading in Java
In Java, Method Overloading allows us to define multiple methods with the same name but different parameters within a class. This difference may include:The number of parametersThe types of parametersThe order of parametersMethod overloading in Java is also known as Compile-time Polymorphism, Static
10 min read
new operator in Java
When you are declaring a class in java, you are just creating a new data type. A class provides the blueprint for objects. You can create an object from a class. However obtaining objects of a class is a two-step process : Declaration : First, you must declare a variable of the class type. This vari
5 min read