Blog Java Understanding the Casting in Java

Understanding the Casting in Java

Casting is the process of making a variable behaves as a variable of another type. In this article, we will discuss on casting in Java with example in detail.

Software and application developers know the fast pace at which industry requirements evolve. However, some instruments continue to stay relevant even in the times of constantly fluctuating trends. Java is undoubtedly the best choice of software developers and programmers in the present times for many promising reasons.

The popularity of Java since its foundation has been responsible for the rise in demand for Java tutorials. Among the many topics you can find, casting in Java continues to be one of the most confusing concepts in Java despite being one of the easiest to understand.

The advantages of Java features such as portability, scalability, and platform independence largely arise from the basic functionalities of Java. The following discussion would aim at exploring the different types of casting, such as upcasting and downcasting in Java. Furthermore, the discussion would also focus on exploring the necessity, benefits, and rules of casting.

Java Se 11

Basic Rules for Casting in Java

The start of a good tutorial on casting in Java should always start with a definition of the term. Casting involves taking one object of a specific type and transforming it into another object type. This is one of the prominent reasons for which you can find casting and conversion as analogous processes in Java. You should note that casting is not specific only for Java because many other programming languages also support the casting of variable types.

However, Java has certain restrictions for casting variables so that you cannot cast any variable to a random type. Therefore, you need to focus on java casting rules for understanding the best ways for casting. One of the foremost rules is evident in the casting of classes and interfaces in the same type hierarchy into each other.

The casting of two objects without a similar type of hierarchy could result in a compile-time error. Another important consequence of Java casting rules is evident in typecasting objects in a similar type hierarchy, albeit with the difference in the type of the object that you are casting and the object on which you are casting. The outcome of this deviation would be the ClassCastException in Java.

The release of Java SE 11 has come up with a number of new features. Let’s find out and ubderstand the new Java SE 11 feataures!

Casting Primitives

One of the foremost concerns related to casting in Java refers directly to the two type groups in Java. The two types of groups are primitive and reference. The first attention of this discourse would go to the casting of primitives to ensure type conversion. The primitives refer to int, double, float, long, and other data types.

On the other hand, references include type classes, arrays, or interfaces. However, one of the important points related to casting in Java refers to implicit and explicit changes. In certain cases, the system could itself change the type of expression based on certain requirements. Take the following example into consideration,

int num1 = 5;

double num2;

double a = num1 / num2; 

In the case of the last line of the code, you can witness the automatic typecasting of num1 into ‘double.’

The next important point of concern arises with explicit casting, which is also known as type casting in Java. The programmer has to specify the type in which an object should be cast if certain changes do not happen automatically. The basic syntax for type casting is as follows,

Identifier2 = (type) identifier1;

For example, num1 = (int) num2;

Widening and narrowing primitives

Continuing ahead with the narrowing and widening of primitives, it becomes easier to develop an overall understanding of casting in Java. Widening of primitive types or upscaling involves conversion from a smaller primitive to a larger destination primitive. In the course of widening primitives, smaller primitive value assumes the larger container leaving lots of extra space. As a result, the space on the left is filled with zeros, and you could then proceed towards the floating-point from the integer group. Take the following example to understand the widening of primitives in Java typecasting.

int myInt = 12;

long myLong = myInt;

float myFloat = myLong;

double myDouble = myLong;

The above example is feasible because the movement to a wider primitive does not result in loss of information. Simply, the widening of primitives explains the basics of upcasting in Java. Narrowing primitives is also another form of casting in which you fit a large value than the type specified in variable declaration. As a result, information loss is imperative due to discarding some bytes. Narrowing primitives also demands explicit expression about the use of a cast, and it provides a basic idea about downcasting in Java. Take a look at the following example to understand it better.

int myInt = (int) myDouble;

byte myByte = (byte) myInt;        

Upcasting and Downcasting:

Now, let us focus on the two types of casting, i.e., upcasting and downcasting in Java, for supporting this discussion further. Upcasting involves casting to a supertype, while downcasting refers to casting to a subtype. Both of these types of casting in Java options help in providing advantages such as polymorphism or facility for grouping of various objects. Upcasting refers to generalization or widening through casting to a parent type.

The description of upcasting in simple words suggests the casting of an individual type to a general type. On the other hand, downcasting is the exact opposite and involves casting to a child type or casting a common type to individual type. The need of upcasting in Java is not exactly mandatory. Upcasting is evident in scenarios where you have to write code dealing only with the parent class. On the other hand, the need for downcasting in Java arises when you have to access the behavior of subtypes.

Object Casting

Another important aspect of this discussion refers to object casting in Java. The basic notion of object casting aligns with typecasting, albeit with references to objects. Objects of other classes could be cast on objects of other classes with the condition that source and destination classes have interrelations by inheritance. Inheritance implies that one class is a subclass of the other. Certain objects would need explicit casting because of specific reasons.

The reason is that a subclass contains all information which the superclass contains, thereby allowing the use of an object of subclass anywhere with the application of superclass. The example for such a case, suppose a method is taking two arguments among which one is of the type “Object,” and the other is of the type “Component” in ‘java.awt.’ A package containing classes for the graphical user interface.

Here, you can pass an instance of any class for the “Object” argument because of including all Java classes in the subclasses of “Object.” In the case of “Component” argument, you could pass it in subclasses like Button, Label, and Container in ‘java.awt.’ Not only for method calls, but object casting in Java is also applicable anywhere in a program.

Variables with the definition of class “Component” allow assigning objects of that class or its subclasses to the variable without casting. The reverse is also applicable as you could use a superclass in places where a subclass is expected. Since subclasses contain more behavior than superclasses, considerable loss in precision is evident with the casting process.

Java 13 is the recently launched version of Java. If you are a Java enthuasitic, check out these Java 13 new features and expand your knowledge.

The reason is that the superclass objects may not have the necessary behavior for acting instead of a subclass object. For example, if you have an operation for classing methods in objects in the “Integer” class, then using an object of superclass “Number” would not include various methods in “Integer.”

Errors can pop up if you attempt to call methods that do not exist in the destination object. Another important concern of casting in Java for objects is that you can also cast objects to interfaces, only of the object’s class or superclasses follows the interface. The casting of an object to an interface suggests the facility of calling one of the interface’s methods. This is possible even if the concerned object’s class does not implement the interface.

Reference Casting

Conversion and casting of reference types is also a prominent topic for evaluation of casting in Java. References involve type class, array or interface. You cannot find arithmetic promotion in the case of reference type casting or conversion because object references could not be arithmetic operands. Here, you can find two distinct methods for reference casting, such as assignment conversion and method invocation.

Assignment conversion involves the assignment of a reference type to a value of different types. The object reference conversion process follows specific rules applicable to casting in Java. Interface type conversion is possible only to an interface type or to an Object. In the case of casting to a new interface type, the new interface type should be superior to the old type.

Class type conversion is possible only to a class type or an interface type. Similarly, an array type conversion should be on to the class Object to the Cloneable or Serializable interface or to an array. Method invocation casting of reference types is possible by passing a reference type to a method accepting the argument of a different type.

Also Read : Top Reasons to Get a Java Certification


On a final note, we can note that casting in Java for primitives and reference types follow a similar route. The uniformity of rules for the casting of primitives and reference types offer a distinct semblance of the general approach to casting. Casting allows accessing specific functionalities of different objects without the concerns of implicit downcasting or loss of information.

This provides better flexibility of using different variables without treating them as generic objects. The casting of different types is a common task that you can find in general programming activities. However, a clear awareness of the set of rules governing ways in which statically typed languages could operate castings is mandatory. Awareness of the rules for casting can help in identifying reasons for code not compiling and saving considerable time.

Looking for Java Certification Training Courses? Checkout Whizlabs Java Training Courses and start your preparation.

About Neeru Jain

Technology Scientist by Mind and Passionate Writer by Heart!! With an enthusiasm for technological research and learning, Neeru turned out to be a technology expert. Her Belief: “Words are powerful enough to change Mind, Life, and the World; only the writer should have a real passion for Writing!!”
Spread the love


Please enter your comment!
Please enter your name here