I know how to use casting in Java but have a more specific question; could you please explain to me how the casting works (in memory)?
How is the variable type changed upon upcasting and downcasting?
How does the JVM know that it's safe to send this method to this object?
Thank you in advance.
Example: Converting double into an int int data = (int)num; Here, the int keyword inside the parenthesis indicates that that the num variable is converted into the int type. In the case of Narrowing Type Casting, the higher data types (having larger size) are converted into lower data types (having smaller size).
In Java, type casting is a method or process that converts a data type into another data type in both ways manually and automatically. The automatic conversion is done by the compiler and manual conversion performed by the programmer. In this section, we will discuss type casting and its types with proper examples.
Could you please explain me how the casting works ( in memory )?
It works at byte code level not really in memory
How the variable type is changed on upcasting and downcasting?
If it is a primitive with an special bytecode instruction, for instance from long to integer as in:
long l = ...
int i = ( int ) l;
The bytecode is: l2i
if is a reference with the instruction checkcast
How the JVM knows that from this time it's safe to send this method to this object?
It doesn't, it tries to do it at runtime and if it fails throws an exception.
It is legal to write:
String s = ( String ) new Date();
Possible duplicate of the accepted answer to this question: How does the Java cast operator work?
There's also quite an extensive explanation here, that covers all data types, etc.: http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.5
All casting of primitives is done in registers (like most operations) For primitives, in many cases, when down casting the lower bits are taken and for up casting, the sign is extended. There are edge cases but you usually don't need to know what these are.
upcasting/downcasting a reference works the same in that it checks the actual object is an instance of the type you cast to. You can cast which is neither upcast nor down cast.
e.g.
Number n = 1;
Comparable c = (Comparable) n; // Number and Comparable are unrelated.
Serializable s = (Serializable) c; // Serializable and Comparable are unrelated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With