StKiller
StKiller

Reputation: 7941

Java casting implementation

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)?

Thank you in advance.

Upvotes: 7

Views: 4363

Answers (4)

Peter Lawrey
Peter Lawrey

Reputation: 533492

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.

Upvotes: 1

OscarRyz
OscarRyz

Reputation: 199215

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();

Upvotes: 4

Lefteris Laskaridis
Lefteris Laskaridis

Reputation: 2322

If you are interested in the inner workings of jvn concerning how casts work you may also check the jvm spec http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#25611

Upvotes: 0

jefflunt
jefflunt

Reputation: 33954

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

Upvotes: 3

Related Questions