Tutorial Playlist
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.
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.
Here are the types of type casting in Java:
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 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);Â
  }
}
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 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();Â
  }
}
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();  Â
}
}
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:
int num1 = 10;
double num2 = 3.14;
int result = (int) (num1 + num2);
String userInput = "50";
int num = Integer.parseInt(userInput);
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 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:
int num1 = 10;
double num2 = num1;
int num1 = 10;
int num2 = 3;
double result = num1 / num2;
public void myMethod(int num) { Â Â
}
public void myMethod(double num) {
}
int num1 = 10;
double num2 = 3.14;
myMethod(num1);
myMethod(num2);
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.
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.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...