Apps/Gaming

What is Java Type Casting?

One of the very first things you learn when you start working with Java is how strict it is about typing. Like Little Mikey, the fussy boy in the Quaker Oats commercials of the 1970s, Java will not allow other data types to be assigned to a variable, and that is that! Java will show its displeasure by responding with a compiler error if programmers try to assign a larger data type (ie a float) value to a smaller (ie an internal) variable.

Thankfully, there is a way to appeal Java by employing casting. Casting is a way of temporarily converting data from one data type to another data type. This process of data conversion is also known as type conversion or type coercion.

This tutorial will cover all of the ins and outs of using casting to convert data from one type to another in such a way that does not invoke the wrath of the Java compiler.

Reading: Java Primitive Data Types

What are the Two Main Types of Casting in Java?

There are actually thirteen types of conversion in Java! These include Identity conversions, Boxing and Unboxing conversions, and many more.
In this web development tutorial, we will be exploring the two main types, which are:

  1. Implicit (widening) casting.
  2. Explicit (narrowing) casting.

Implicit/Widening Casting in Java

Implicit/Widening casting is done automatically when passing a smaller size type to a larger size type. Implicit casting follows the order of conversion as shown below:

byte -> short -> char -> int -> long -> float -> double

Implicit casting takes place under two conditions:

  1. The data types are compatible. For example, numeric data types are compatible with other numeric data types, but they are not compatible with boolean, charor string data types. Likewise, a string is not compatible with a boolean data type.
  2. If the targeted value to be converted has a smaller size, eg 4 bytes, to a larger data type, eg 8th bytes.

Here is some example code that demonstrates the implicit casting from internal to double in Java:

public class ImplicitCastingExample { public static void main(String[] args) { int myInt = 5; double myDouble = myInt; // Implicit casting from int to double System.out.println(myInt); // Outputs 5 System.out.println(myDouble); // outputs 5.0 } }

Explicit/Narrowing Casting in Java

Narrowing casting must be done manually by placing the type in parentheses in front of the value. Explicit casting follows the exact same order of conversion as shown above, but in reverse order:

Double -> FLoat -> Long -> Int -> Char -> Short -> Byte

The following example shows the explicit casting of a double to internal in Java:

public class ExplicitCastingExample { public static void main(String[] args) { double myDouble = 5.67d; int myInt = (int) myDouble; // Manual casting: double to int System.out.println(myDouble); // outputs 5.67 System.out.println(myInt); // output 5 } }

Reading: Java Tools to Increase Productivity

Object Type Casting in Java

Casting works a little differently with variables that reference objects because these only refer to an object but do not contain the object itself. Hence, casting a reference variable does not affect the object it refers to, but rather, labels the object in another way, by either expanding or narrowing opportunities to work with it. Upcasting narrows the list of methods and properties available to this object, while downcasting extends it.

As such, a reference acts much like a remote control to an object whereby the remote control will have more or fewer buttons depending on its type. When developers apply casting to a reference variable, we are changing the type of remote control but not the object itself.

Java upcasting

Upcasting occurs when we cast from a subclass to a superclass. Typically, the upcasting is implicitly performed by the compiler.

Upcasting is closely related to inheritance; it is common to use reference variables to refer to a more specific type, and every time we do this, implicit upcasting takes place.

To demonstrate upcasting, let’s define a generic Vehicle class:

class Vehicle { protected String brand = “Infiniti”; public void honk() { System.out.println(“Honk, honk!”); } }

Now let’s extend Vehicle to something more specific:

class Car extends Vehicle { private String modelName = “G35”; public backup() { System.out.println(“Backing up…”); } public static void main(String[] args) { Car myCar = new Car(); myCar.honk(); System.out.println(myCar.brand + ” ” + myCar.modelName); } }

Now we can create an object of the cars class and assign it to the reference variable of type cars:

Car myCar = new Car();

We can also assign it to the reference variable of type Vehicle:

Vehicle vehicle = myCar;

In the above assignment, implicit upcasting takes place.

Java downcasting

If we now wanted to invoke the cars backup() method on the myCar variable (of type Vehicle) we would now need to employ downcasting, which is the casting from a superclass to a subclass. If we try to invoke Car’s backup() method on the myCar Vehicle instance, the compiler will complain that the backup() method does not exist for the type Vehicle.

Therefore, to call backup() programmers should downcast myCar to a cars first:

((Car) myCar).backup();

The inner parentheses and the type they contain are often called the cast operator. Note that external parentheses are also needed so that the casting occurs before the invocation of the backup() method.

Final Thoughts on Java Type Casting

In this tutorial, we learned all about the process of converting the value of one data type to another data type known as typecasting. As we saw, casting can be done implicitly when passing a smaller size type to a larger size type or explicitly, or manually, by placing the type in parentheses in front of the value.

In the case of variables that reference objects, casting doesn’t affect the underlying object itself to but only labels this object, by either expanding or narrowing opportunities to work with it. Upcasting narrows the list of methods and properties available to this object, while downcasting extends it.

Reading: Type Conversion in Java

Related posts

Data conversion in Go

TechLifely

WordPress CMS Review

TechLifely

How MondayOFF increased IPM by 57% with playable ads

TechLifely

Leave a Comment