1

I come from C++ and just know some Java, but there is one thing that I don't fully understand about java is the casting. In c++, we have Regular cast vs. static_cast vs. dynamic_cast. In java, we have casting between primitive types and object types (known as boxing and unboxing), casting between primitive types, casting using Class function, and sometimes we perform unchecked casting. Is there a direct mapping from Java's casting system to C++'s casting system? are they equivalent? or is there something that is unique in one side?

Community
  • 1
  • 1
keelar
  • 5,814
  • 7
  • 40
  • 79
  • 1
    What's a "regular cast"?! – Kerrek SB Jun 22 '13 at 23:35
  • 1
    @KerrekSB: The link I provided explains it. – keelar Jun 22 '13 at 23:35
  • 1
    I would not consider boxing as casting, as it creates new instances. It is just a compiler convenience for doing `new Integer(myInt)` and all that. – SJuan76 Jun 22 '13 at 23:37
  • No. In Java you have primitive casts, boxing/unboxing, and reference type coercion. The first two actually alter the data value. The third type of cast simply asserts to the compiler and JVM what the object type is -- there is no change to the data value. This third type is ALWAYS checked. These three concepts are quite distinct and different from each other and have (rather unfortunately) "overloaded" the term/notation of "cast", leading to considerable confusion. – Hot Licks Jun 22 '13 at 23:40

2 Answers2

2

If you know C++, the Java object model can be explained fairly easily. Java variables of class type are references to dynamically created objects of the corresponding type. An initialized Java variable T x = new T(); corresponds closely to a C++ pointer: T * px = new T;

In Java, all class types inherit from the polymorphic type Object, and thus all pointers can be used for RTTI: All casts of Java class-type variables are what dynamic_cast is in C++. So Java's (S) x corresponds to dynamic_cast<S *>(px) in C++, with the same failure mode that a null result indicates that the dynamic types aren't related.

All the other C++ pointer casts are unsafe and have no equivalent in Java. I don't know if Java has scalar conversions like integer-to-floating point; if so, then those would correspond closely to the C++ conversions.

Boxing and primitive types are a rather separate and unrelated issue. If you wanted something like that in C++ you'd have some kind of template <typename T> struct Box with a conversion-to-T opera­tor.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

In short:

Think about casts from built-in types as static_cast's and

think about casts between objects as dynamic_cast's in C++.

sasha.sochka
  • 14,395
  • 10
  • 44
  • 68