This content has been marked as final. Show 4 replies
There's an explanation about casting at the bottom.
Did u try google....
we promise the compiler that the object we're casting is in fact of the type we're casting to. if we lie, the JVM spanks us with a ClassCastException. all you're really doing is making a reference of one type point to an object of another type. it's up to you to make sure it makes sense
> Please explain what exactly happens when we type cast
an object to a user defined object or a built-in java object
One doesn't cast an object. When applied to a reference value, the cast operator checks that the referred-to object is type-compatible with the reference.
JLS �15.16 Cast Expressions
A cast expression converts, at run time, a value of one numeric type to a similar value of another numeric type; or confirms, at compile time, that the type of an expression is boolean; or checks, at run time, that a reference value refers to an object whose class is compatible with a specified reference type.
CastExpression:See �15.15 for a discussion of the distinction between UnaryExpression and UnaryExpressionNotPlusMinus.
( PrimitiveType Dimsopt ) UnaryExpression
( ReferenceType ) UnaryExpressionNotPlusMinus
The type of a cast expression is the result of applying capture conversion (�5.1.10) to the type whose name appears within the parentheses. (The parentheses and the type they contain are sometimes called the cast operator.) The result of a cast expression is not a variable, but a value, even if the result of the operand expression is a variable.
A cast operator has no effect on the choice of value set (�4.2.3) for a value of type float or type double. Consequently, a cast to type float within an expression that is not FP-strict (�15.4) does not necessarily cause its value to be converted to an element of the float value set, and a cast to type double within an expression that is not FP-strict does not necessarily cause its value to be converted to an element of the double value set.
It is a compile-time error if the compile-time type of the operand may never be cast to the type specified by the cast operator according to the rules of casting conversion (�5.5). Otherwise, at run-time, the operand value is converted (if necessary) by casting conversion to the type specified by the cast operator.
Some casts result in an error at compile time. Some casts can be proven, at compile time, always to be correct at run time. For example, it is always correct to convert a value of a class type to the type of its superclass; such a cast should require no special action at run time. Finally, some casts cannot be proven to be either always correct or always incorrect at compile time. Such casts require a test at run time. See for �5.5 details.
A ClassCastException is thrown if a cast is found at run time to be impermissible.