File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Will class casting creats new object on the heap? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Will class casting creats new object on the heap?" Watch "Will class casting creats new object on the heap?" New topic

Will class casting creats new object on the heap?

zhong chen

Joined: Oct 12, 2009
Posts: 24
If B extends A and you do:
A a = new B();
B b = (B)a;

will it creates two objects?
Guillaume Jeudy

Joined: Jul 27, 2009
Posts: 24
The answer is no, an object is only really created when you use the new keyword. In your example 1 object is created and placed on the heap.

SCJP 1.4 and 6.0, SCJD
Atwal Usha
Ranch Hand

Joined: Sep 10, 2009
Posts: 137
Well, Jeudy has already explained it. Class casting never creates objects on heap it's the new keyword which is responsible for that. You could check that by executing the following code.

When Line 1 is executed the constructor of the Child class executes and displays the output child object however the same is not true for Line 2 which means the casting has not created another object on heap. Hope it helps.

Java Certification Exam Mock Tests: SCJA  SCJP 5  SCJP 6  SCJP 6 (Online Training)  SCJP 6 (Instructor Led Training)   SCWCD 5   SCBCD 5  SCEA 5
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15092

When you cast something, what it means is that you say to the compiler: "Compiler, I have a variable of type A here, but I want you to treat it as if it is of type B. (Because I know that the variable really refers to an object of type B)."

Casting does not create any objects or do any smart conversions.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Prithvi Sehgal
Ranch Hand

Joined: Oct 13, 2009
Posts: 774
Yes, only object will be created basically and i believe there will be now two reference variables on the stack
referring to the same object.


My Blog, Follow me on Twitter,Scjp Tips, When you score low in mocks, Generics,Scjp Notes, JavaStudyGroup
Nitish Bangera
Ranch Hand

Joined: Jul 15, 2009
Posts: 537

The main thing to remember for this is for what reason the casting is done and for whoom is it for the compiler or is it used during running the program.

[ SCJP 6.0 - 90% ] , JSP, Servlets and Learning EJB.
Try out the programs using a TextEditor. Textpad - Java 6 api
I agree. Here's the link:
subject: Will class casting creats new object on the heap?
It's not a secret anymore!