Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes is it possible to create a object on stack Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "is it possible to create a object on stack" Watch "is it possible to create a object on stack" New topic
Author

is it possible to create a object on stack

siddhu Math
Ranch Hand

Joined: Aug 10, 2006
Posts: 46
is it possible for me to create an object on stack as i know that objects are created on heap.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19670
    
  18

No it isn't. All method-local primitive types and and references are put on the stack, all objects are put in the heap. No ifs and buts about it.

One reason I can think why they did is that it removes one commonly made error: you pass the stack-based object to a method that stores a reference to that object. Then the object goes out of scope, is removed from the stack, and the reference points to something undefined. Next when you want to access the "object" through the reference, you're in a world of hurt since the object is no longer there - and nobody knows what is.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
siddhu Math
Ranch Hand

Joined: Aug 10, 2006
Posts: 46
ok if objects are created on heap then why not those on stack since you know static objects are created on stack.
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12769
    
    5
since you know static objects are created on stack.


Where in the world did you get that idea? What do you think a "static object" is?



(Why do I ask? As an occasional author I want to find out where bad information comes from.)

Bill
siddhu Math
Ranch Hand

Joined: Aug 10, 2006
Posts: 46
got it i was really in a wrong concept
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18717
    
  40

Hate to complicate matters, but believe it or not, Java objects can exist on the stack !! Java 6 added "escape analysis" as an optimization tool.

If an object (referenced by a local variable) can be determined to not escape the method (which is really not that easy to determine), the object will be created on the stack. It will be finalized right before the method exits -- which reclaims the memory.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Henry Wong:
... Java 6 added "escape analysis" as an optimization tool...

Wow! I didn't realize that.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
wood burning stoves
 
subject: is it possible to create a object on stack