+ 5
What is casting?
3 Answers
+ 4
Casting is changing type of variable.
There are 2 types of casting
1. Downcasting - cast from parent to child
e.g.
Object o = new String("a string");
String s = (String)o;
2. Upcasting - child to parent
e.g.
String s = new String("abc");
Object o = (Object)s;
Note that Object is parent of String.
+ 3
When you use casting with number types, you are able to use two integer types in division and receive a double type as a result.
Ex.
int x = 5;
int y = 2;
int integerDivision = x / y; //the result here is 2
int castedDivision = (double)x / y; //result is 2.5
Here casting works by changing the type of x to double for the duration of the statement. After the statement ends, x remains as an integer type. This also applies with other types, not just int and double.
- 2
casting is converting one type of data into other type and we can also use casting to convert one type of class object into other bt we can't use casting to convert a primitive data type into a class and vice versa