top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Type Casting in Java

Introduction

Various industries widely use Java, which is a popular programming language. The language was designed to be written once and be able to run the program without any modifications across multiple platforms. Java has a safe environment with sound security, delivering high flexibility and user-friendliness. This is why it is a widely used programming language.

Type casting in Java is a vital method programmers use to change the data type from one form to another. There are two distinguished kinds of type casting in Java: implicit and explicit type casting. 

Overview

This tutorial primarily deals with the meaning of type casting in Java and its types and explains the processes with the help of code examples for gaining a clearer understanding. 

Types of type casting

Here are the types of type casting in Java:

Widening type casting

Type casting Java is a process of converting a value of one data type to another data type. Widening type casting is also known as implicit type casting. It is a type of type casting where the data type of a variable is automatically converted to a larger data type. This is done without the need for any explicit conversion.

For instance, if we have a variable "a" of type "int" (that can be used only with integer values) with a value of “10”. Then we assign the value of "a" to a variable "b" of type "double" (that can be used with decimal values). Then this is an example of widening type casting. This is because "double" is a larger data type than "int." Also, the value of "a" can be represented without any loss of precision in a "double" variable.

Here's a widening type casting example:

public class WideningTypeCastingExample {
    public static void main(String[] args) {
        int myInt = 10;
        double myDouble = myInt; 
        System.out.println("myInt: " + myInt);
        System.out.println("myDouble: " + myDouble);
    }
}

In this example, we declare an integer variable myInt, with a value of “10”. We then assign this value to a double variable, “myDouble,” using widening type casting. This is done since double is a larger data type than int.

Narrowing type casting

Narrowing type casting is also known as explicit type casting. It is a type of type casting where the data type of a variable is explicitly converted to a smaller data type. This can hold less data without losing precision.

For instance, if we have a variable "a" of type "double" with a value of 10.5. If we assign the value of "a" to a variable "b" of type "int," Then this is an example of narrowing type casting. This is because "int" is a smaller data type than "double." It is to be noted that some of the information in "a" may be lost when it is converted to an "int" variable.

Here's an example code that demonstrates narrowing type casting:

public class NarrowingTypeCastingExample {
    public static void main(String[] args) {
        double a = 10.5;
        int b = (int) a;
        int c = b + 5; 
        System.out.println("a: " + a);
        System.out.println("b: " + b); 
        System.out.println("c: " + c);
    }
}

In this code, we first perform narrowing type casting to convert the value of "a" to an "int" value of “10”. We then use the result of the narrowing type casting in an arithmetic operation. In essence, we add “5” to it. Then, we store the result in a variable "c." Then we print the values of "a," "b," and "c." We can see that "a" retains its original value of “10.5”. "b" is the truncated value of "a" after narrowing type casting. "c" is the result of adding “5” to "b."

Two ways we can change the type from one to another: 

Type casting

In Java, type casting is the process of converting a variable of one data type to another data type. This can be done explicitly using a cast operator. This can also be done implicitly in some cases where the conversion is safe and automatic. There are two types of type casting: widening and narrowing. These are already explained in detail above.

Type conversion

Type conversion and casting in Java are two related concepts. Type conversion is a more general term that refers to converting a value from one data type to another. This can either be done implicitly or explicitly. This may include type casting as well as other forms of conversion, such as converting a string to a numeric data type. 

For example:

public class TypeConversionExample {
    public static void main(String[] args) {
        String myString = "10";
        int myInt = Integer.parseInt(myString);
        System.out.println("myString: " + myString);
        System.out.println("myInt: " + myInt); 
    }
}

Explicit type casting on user-defined datatypes

In Java, explicit type casting can also be applied to user-defined data types, such as classes and interfaces. However, the rules for type casting user-defined types differ slightly from those for primitive types.

To perform an explicit type cast on a user-defined data type, the type being cast must either be a subclass of the target type or implement the target interface. This is because the target type must be able to "accept" the type being cast. This is only possible if the type being cast has all of the properties and methods required by the target type.

For instance, suppose we have two classes, “Animal” and “Dog,” where “Dog” is a subclass of “Animal”:

public class Animal {
    public void eat() {
        System.out.println("Eating...");
    }
}
public class Dog extends Animal {
    public void bark() {
        System.out.println("Barking...");
    }
}
To cast a “Dog” object to an “Animal” object, we can use the cast operator as follows:
Dog myDog = new Dog();
Animal myAnimal = (Animal) myDog;

Since “Dog” is a subclass of “Animal,” we can safely cast a “Dog” object to an “Animal" object. The resulting “Animal” object will have all of the properties and methods of “Animal.” However, any properties or methods specific to “Dog” will be "hidden" or inaccessible.

However, if we try to cast an “Animal” object to a “Dog” object, we will get a runtime error. This is simply because not all “Animal” objects can be treated as “Dog” objects:

Animal myAnimal = new Animal();
Dog myDog = (Dog) myAnimal;

In this case, the “Animal” object does not have all of the properties and methods required by “Dog.” As a result, the cast fails, and a “ClassCastException” is thrown at runtime.

In summary, explicit type casting on user-defined data types is only possible if the type being cast is a subclass of the target type or implements the target interface. Otherwise, it will result in a runtime error.

Explicit Downcasting

Explicit downcasting in Java converts an object of a superclass type to an object of its subclass type. This is done explicitly using a cast operator. It is only allowed when the object being cast was initially created as an instance of the subclass.

Here is an example of explicit downcasting in Java:

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");
    }
}
public class Main {
    public static void main(String[] args) {
        Animal myAnimal = new Dog();
        myAnimal.makeSound(); 
        Dog myDog = (Dog) myAnimal;         
myDog.fetch(); 
    }
}

Explicit Upcasting

In Java, explicit upcasting refers to converting a reference to a more specific class type to a reference to a less specific class type. This is because we are widening the scope of the reference variable to a more general type. This is also known as widening conversion.

Here is an example of explicit upcasting in Java:

class Animal {
    public void makeSound() {
        System.out.println("The animal makes a sound");
    }
}
class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("The dog barks");
    }
    public void fetch() {
        System.out.println("The dog fetches a ball");
    }
}
public class UpcastingExample {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        Animal myAnimal = (Animal) myDog;        
        myAnimal.makeSound();    
}
}

Application of type casting

Explicit type casting

Explicit type casting in Java is beneficial when we want to convert a value of one data type to another data type. There can be various applications of explicit type casting. Some of those are as follows:

  • Arithmetic operations: When we perform arithmetic operations on values of different data types, Java automatically promotes one or both values to a higher data type. But, we may want to explicitly cast a value to a specific data type before performing arithmetic operations. For instance:

int num1 = 10;
double num2 = 3.14;
int result = (int) (num1 + num2);
  • Converting strings to other data types: When we read input from the user, the input is usually generated as a string. If we need to work on this input or perform calculations, we may need to convert the string to a different data type. For instance:

String userInput = "50";
int num = Integer.parseInt(userInput);
  • Working with arrays: When working with arrays, we may need to explicitly cast the elements of the array to a different data type. For example:
double[] myArray = { 1.5, 2.7, 3.2 };
int[] newArray = new int[3];
for (int i = 0; i < myArray.length; i++) { 
newArray[i] = (int) myArray[i];
}

Automatic type casting

Automatic type casting in Java is also known as implicit type casting. It is useful when Java automatically converts one data type's values to another. This can occur in various situations. Some of these situations are as follows:

  • Assigning a value of a smaller data type to a variable of a larger data type: When we assign a value of a smaller data type to a variable of a larger data type, Java automatically converts the value to the larger data type. For instance:

int num1 = 10;
double num2 = num1;
  • Performing arithmetic operations on values of the same data type: When we perform arithmetic operations on values of the same data type, Java automatically promotes the values to a higher data type if it deems necessary. For instance:

int num1 = 10;
int num2 = 3;
double result = num1 / num2;
  • Method overloading: When we overload a method with different parameter data types, Java automatically selects the appropriate method based on the argument data types. For instance:

public void myMethod(int num) {   
}
public void myMethod(double num) {
}
int num1 = 10;
double num2 = 3.14;
myMethod(num1);
myMethod(num2);

Conclusion

This tutorial will help aspiring programmers gauge the uses and correct usage of type casting in Java. Learners can also avail of courses offered by reputed online learning platforms like upGrad to master programming languages like Java and much more. This will help them get a career boost if they want to explore the field of computer application and computer science. 

FAQs

1. What are the differences between implicit type casting and explicit type casting in Java?

There are a few differences between implicit and explicit type casting in Java.

Implicit type casting is done automatically by Java. Explicit type casting is done manually by the programmer. Implicit type casting is generally safer because the conversion is done automatically. Explicit type casting can be risky if the programmer is not careful about potential data loss or errors.

2. What is data loss in type casting in Java?

Data loss occurs when a value of one data type is converted to another, and some information is lost in the process. For instance, if a double value is cast to an int, the decimal portion of the value will be truncated. Therefore, this results in a loss of precision.

3. How can you cast a variable in Java?

To cast a variable in Java, you use syntax such as "(int) myDouble" to cast a double to an int. The data type being cast is enclosed in parentheses before the variable name.

Leave a Reply

Your email address will not be published. Required fields are marked *