:::: MENU ::::

Thursday, October 27, 2022

Any programming language has data types that can store data in memory e.g. primitive: integer, floating, string, reference variable: object variable, and more. Sometimes we want to convert one data type into another. So in a simple sentence, type casting is the way of assigning one data type value to another data type.
In java language, it's very important to understand primitive type casting and reference or object variable type casting. Though most programmers know about typecasting in brief and use casting more often in their coding, they face some expected hassle in casting. e.g converting parent object to child object, String to int, or vice-versa, etc. So Clear knowledge about casting could help anyone to avoid unexpected bugs.


So let's Know In Forms this article's content; Moreover first Know and then Informs others about this content.
We believe knowledge sharing is the power of the next generation.
















Primitive Variable Casting in Java 

More specifically integer, double, short, byte, character, etc are primitive data types. There are two ways of casting: 1. Widening and 2. Narrowing casting. The widening (automatically) name says that converting a smaller type to a larger type size.

byte(8bits signed integer) -> short(16bits signed integer) -> char(16bits support unicode character) -> int(32bits) -> long(64bits) -> float(32bits) -> double(64bits)


The narrowing casting (manually) is converting a larger type to a smaller type size.

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



Reference Variable Casting in java

There is a major difference between primitive and reference variable casting. Primitive type casting is irreversible, but reference variable casting is reversible. 
It means you can't recover the value of the double data type from the long data type if you are already done casting. But it's possible in reference data type casting and converting Parent class object to child class and vice-versa are possible here, and upcasting and downcasting come with this topic.




Let's find answers to some questions:

Is it possible to casting parent class to child class??

Yes, the parent class can be converted into a child class if the parent holds the child object's instance. It's called upcasting.



Is it possible to cast the child class to the parent class??

Yes, a child object can be converted into a parent class easily, as the child class inherits the parent class. It's called downcasting.




There are many system design patterns in which upcasting and downcasting lead a vital role. So to be knowledgeable in design patterns, you have to understand upcasting and downcasting.



Is polymorphism related to casting?

Yes, related to a run-time polymorphism that is comparatively more complex than compile-time polymorphism.



4. What is ClassCastException

0 comments:

Post a Comment