Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java casting implementation

Tags:

java

casting

jvm

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.

like image 254
StKiller Avatar asked May 04 '11 16:05

StKiller


People also ask

What is casting in Java with example?

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

How does Java support type casting explain with an example?

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.


3 Answers

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();
like image 88
OscarRyz Avatar answered Sep 28 '22 02:09

OscarRyz


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

like image 22
jefflunt Avatar answered Sep 28 '22 01:09

jefflunt


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.
like image 32
Peter Lawrey Avatar answered Sep 28 '22 02:09

Peter Lawrey