Casting in Java

What is Casting in Java?
Assigning one data type to another or one object to another is known as casting. 
Java supports two types of casting – data type casting and object casting.

What is syntax of casting?
dataType variableName = (dataType) variableToConvert;

What is downcasting and Upcasting?
DownCasting:
In following example, the type Object is a very broad type for a variable, we are “downcasting” the variable to be a String type.

Object obj = "Hello world";
String str = (String)obj;

UpCasting:
Let’s look at the reverse scenario, an “upcast”. We are taking a variable with type String and casting it to a variable type Object.

String str = "Hello world";
Object obj = (Object)str;

When an object can not be casted to another type, ClassCastException occurs on run time. 



<-- Previous || Next -->

No comments:

Post a Comment