Y in java objects are created on heap only n not on stack ?

Hi ,
I need a answer to the question " why all the objects are created on heap only in java and not on stack " ?
In java a object is created when we specify new i.e. for example,
consider the following cases.
1.
Vector v = new Vector();
here object is created and the reference to this object is assigned to variable v. okie.
2.
when i write something like
Vector vec ;
Here i am creating reference variable for Vector. No object is created and no seperate memory is allocated for it. Here this reference is placed on the java stack along with other primitive data types.
My question is, in C++ by writing case 2 i can create an object and it is creating this object on stack. So why in java object is not created on stack while i do like this ? Why in java objects are created on heap only ?
If my question is out of interest of this forum i apologize for it. But if somebody can throw some light on it, it would be of great help.
Cheers !!
Dipesh

Cross post!
http://forum.java.sun.com/thread.jsp?forum=32&thread=260589

Similar Messages

  • Y in java objects are created on heap only and not on stack ??

    Hi ,
    I need a answer to the question " why all the objects are created on heap only in java and not on stack " ?
    In java a object is created when we specify new i.e. for example,
    consider the following cases.
    1.
    Vector v = new Vector();
    here object is created and the reference to this object is assigned to variable v. okie.
    2.
    when i write something like
    Vector vec ;
    Here i am creating reference variable for Vector. No object is created and no seperate memory is allocated for it. Reference variablesa are stored along with other primitive variables on the java stack.
    My question is, in C++ by writing case 2 i can create an object and it is creating this object on stack. So why in java object is not created on stack while i do like this ? Why in java objects are created on heap only ?
    If my question is out of interest of this forum i apologize for it. But if somebody can throw some light on it, it would be of great help.
    Cheers !!
    Dipesh

    Hi
    I asked this question just to understand how compiler and jvm cud have been designed......i.e. to know the philosophy behind designing language.......
    now what i cud surmise is that if objects were to be stored in stack then on calling garbage colllector , it may delete some unused obj and unreferenced object(unreachable object) and this in turn may give rise to non-contagious areas in stack, thus nullifying the garbage collector's objective of freeing the the memory. Again deallocating that intersperse spaces into one free block of space will be bit troublesome task.....
    So considering above factor the designer of jvm and java compiler have opted for storing objects on heap rather than stack.....
    If u have something to say bout this.......pls go ahead.......
    Cheers !!
    Dipesh

  • How many java String objects are created in string literal pool by executin

    How many java String objects are created in string literal pool by executing following five lines of code.
    String str = "Java";
    str = str.concat(" Beans ");
    str = str.trim();
    String str1 = "abc";
    String str2 = new String("abc").intern();
    Kindly explain thanks in advance
    Senthil

    virtuoso. wrote:
    jverd wrote:
    In Java all instances are kept on the heap. The "String literal pool" is no exception. It doesn't hold instances. It holds references to String objects on the heap.Um, no.
    The literal pool is part of the heap, and it holds String instances.
    [http://java.sun.com/docs/books/jvms/second_edition/html/Overview.doc.html#22972]
    [http://java.sun.com/docs/books/jvms/second_edition/html/ConstantPool.doc.html#67960]
    You're referring to the JVM. That's not Java.It's part of Java.
    There is nowhere in Java where it is correct to say "The string literal pool holds references, not String objects."

  • How many Objects are created in this?

    Hi,
    How many objects are created in the flwg code:
    String str = new String("Hello");
    String str2 = "Hey there";
    str = str + str2;

    Depends if you're counting objects created at compile time.
    "Hello" is created at compile time. That's 1.
    new String("Hello") creates a new String object at runtime, pointing its backing array at the "Hello" in the constant pool. That's 2.
    "Hey there" is created at compile time. 3.
    str + str2 I might do everything at compile time, or it might do some at runtime. I don't know if str is considered a compile time literal here. I think not, but I'm not sure. You can check by using javap. If I'm correct, then at runtime you'll create a StringBuffer (4) and another String (5).
    So I'd say 5 objects. But if the compiler treats str as a literal and therefore can do the str+str2 at compile time, then it might do so without creating the StringBuffer. Or it might still create it at compile time, use it, and throw it out.

  • How many objects are created?

    I have this question which some one posted to me.
    He asked me how many objects are created when an object of a simple class is created for example
    class A{
    public static void main(String args[])
    A a1 = new A();
    Now how many objects are created? I think only one. Can anyone tell me if any other objects are also created.
    Plz tell me .

    No, the answer is indeed 1. All the other objects
    (including the String[] in the main method
    parameters) are created outside of the A
    class, either by the JVM itself or by some other
    class that calls the A.main() method. You can try
    this out for yourself by adding a constructor such as
    A()
    System.out.println("Creating class A");
    } and see what prints out.Take a closer look at the question:
    how many objects are created when an object of a
    simple class is created for exampleIt doesn't say "how many objects of type A are created".
    I.e. The VM has to load class A before you can create an object from it, and thus an object of type Class is created. There are also a bunch of other objects which needs to be created before you can instantiate A.
    Kaj

  • Newbie Help: Java Object to create an image

    Hi there.
    I'm trying to create a Java class that I can call from Coldfusion that will build a GIF file based on parameters.
    The idea is, the Java object opens a "background" gif file and then writes some text onto it and saves the whole thing out as a GIF.
    Bearing in mind this class will be used directly by Coldfusion, and so isn't an applet or an application...can anyone tell me what is wrong with this code as I get a null pointer exception on the getGraphics() line:
    // Methods available to Coldfusion
    public String CreateOverlay( String imageFile, String outPath, String overlayText, int x, int y, String fontFace, int PointSize)
    try{
    Toolkit tk = Toolkit.getDefaultToolkit();
    Image im = tk.getImage(imageFile);
    Gif89Encoder enc = new Gif89Encoder();
    OutputStream out = new BufferedOutputStream(
    new FileOutputStream(outPath)
    Image newimg = createImage(100,50);
    ***** Graphics g = newimg.getGraphics();
    g.drawImage(im, 0, 0, 100, 50, this);
    g.drawLine(0,0,50,50);
    enc.addFrame( newimg );
    enc.encode(out);
    out.close();
    catch (Exception e) {
    System.out.println("Error...");
    e.printStackTrace();
    return "Dont care at the moment";
    Any help to this troubled newbie would be appreciated.

    Hi Kurt,
    You must call "setVisible(true)" on your Frame before
    creating the image.But, the thing is, this object doesnt have (or need) a GUI. Its just an object that sits on the server and its methods are called to generate an image on disk. Basically what happens is Coldfusion receives information from a user and it loads the java object, calls a method which then generates a new GIF file that is made up of a simple button background and some text (entered by the user)....it then returns the name of this file to Coldfusion and Coldfusion stores it in a database for later retrieval.
    In simple terms:
    COLDFUSION===========
    1. Creates an instance of the JAVA Object
    2. Call the generateGif method passing an image filename and some text eg:
    newFile=c.GenerateGif( "simplebutton.gif", "Some text for button");
    JAVA OBJECT========= (GenerateGif method)
    1. Load the GIF simplebutton.gif
    2. Create a new blank image
    3. Draw the loaded GIF onto the blank one
    4. Write the Text ("some text for button") onto the image
    5. Take the image and encode it to GIF format
    6. Write this GIF to disk
    7. Return the filename of the new GIF image just created
    8. Finish
    As you can see, I dont want or need a GUI.....
    Is this possible ?
    Thanks in Advance,
    Tony Johnson

  • Garbage Collection: how many objects are created after for loop?

    Please see the fallowing java code
    1 public class Test1 {
    2     
    3     public static void main(String[] args) {
    4          
    5          MyObj obj = null;
    6          for(int i=0;i<5;i++){
    7               obj = new MyObj();
    8          }
    9 // do something
    10
    11     }
    12 }
    so my question is How may objects are eligible for garbage collection at line no: 9 (// do something)?

    so my question is How may objects are eligible for
    garbage collection at line no: 9 (// do something)?It's impossible to answer that question since we don't know how MyObj is implemented.
    Kaj

  • Why java objects on heap

    Hi,
    Why the java architecture is such that all the java objects are created on heap. If in certain cases they are allowed to be created on stack then i think the load on garbage collector can be reduced.
    Just for curiosity I want to know this.
    Thanking you.
    - Jaydipsinh Narolia.

    A wild stab in the dark...
    1) They just didn't think about it.
    2) A stack object would imply that there was at least an implicit destructor. But that couldn't be used in heap objects so stack objects couldn't be used.

  • Create java objects from xml

    I want to create a tree structure for java object. These java objects are populated after the parsing the xml. But what could be the logic for adding child to parent when there are
    many sub nodes? I wanted to use one recursive function which iterate through all the elements of the xml file. But I have not got the idea how to add one child object to parent object.
    following are my classes. Any help on this highly appreciated.
    public class TreeObject {
              private String name;
              private TreeParent parent;
              public TreeObject(String name) {
                   this.name = name;
              public String getName() {
                   return name;
              public void setParent(TreeParent parent) {
                   this.parent = parent;
              public TreeParent getParent() {
                   return parent;
              public String toString() {
                   return getName();
    import java.util.ArrayList;
    public class TreeParent extends TreeObject {
         private TreeObject treeObject ;
              private ArrayList children;
              public TreeParent(String name) {
                   super(name);
                   children = new ArrayList();
              public void addChild(TreeObject child) {
                   children.add(child);
                   child.setParent(this);
                   treeObject = child ;
              public void removeChild(TreeObject child) {
                   children.remove(child);
                   child.setParent(null);
              public TreeObject [] getChildren() {
                   return (TreeObject [])children.toArray(new TreeObject[children.size()]);
              public boolean hasChildren() {
                   return children.size()>0;
              public TreeObject getChild(){
                   return treeObject;
    private TreeParent getChilderen(Element rootNode){
         List list = rootNode.getChildren();
         String rootNodeName = rootNode.getName();
         TreeParent root = new TreeParent(rootNodeName);
         for (int i=0; i< list.size(); i++)
    Element node = (Element) list.get(i);
    if(node.getChildren().size() > 0){
         // TreeParent treeParent = new TreeParent(node.getText());
         TreeParent treesub = new TreeParent(node.getText());
         treesub.addChild(treesub);
         //TreeParent p = treeParent.getParent();
         // rootParent.addChild(treeParent);
    }else{
         TreeObject object = new TreeObject(node.getText());
         root.addChild(object);
    getChilderen(node);
         return root ;
    public TreeParent buildTree(String filePath) {
    SAXBuilder builder = new SAXBuilder();
    File xmlFile = new File(filePath);
    try{
    Document document = (Document) builder.build(xmlFile);
    Element rootNode = document.getRootElement();
    // List list = rootNode.getChildren("staff");
    TreeParent rootParent = getChilderen(rootNode);
    return rootParent ;
    }catch(IOException io){
    System.out.println(io.getMessage());
    }catch(JDOMException jdomex){
    System.out.println(jdomex.getMessage());
    return null;
    Edited by: 870611 on Jul 6, 2011 6:27 AM

    Hi
    I recommend you use the API JAXB. Is much simpler.
    here a link: http://www.oracle.com/technetwork/articles/javase/index-140168.html
    here a example: http://download.oracle.com/javaee/5/tutorial/doc/bnbay.html#bnbbc

  • Are java byte[] stored on the heap?

    are java byte[] stored on the heap?
    If not, How can I clear a byte[]?
    For example in C, I could simply put the '\0' at
    the zeroth index.
    Please help.
    hm

    Yes, byte[] objects are stored on the heap. In Java, all objects are stored on the heap, all arrays are objects, and byte[] is an array.
    You seem to be equating byte[] with a C-style string. That kind of thinking will get you into all kinds of trouble in Java. Strings in Java are sequences of Unicode characters. Byte arrays can be converted to and from Strings using encodings such as UTF-8.

  • Visibility of methods of generated xmlbean java Objects

    Hi,
    I created a simple xml schema containing a small complex type and an element using that complex type. I am able to successfully create the xmltypes.jar using scomp tool.
    At the place of usage, i put this jar file into my class path and wrote the java code using the java objects created by xmlbean. The problem is, the methods in the java objects are not public methods, it is having the default visibility (no access modifier). so my java code is not getting compiled.
    How to solve this issue? what changes do I need to do in my .xsd file, so that xmlbean will create public methods in the components created for complex type objects. the package of the java objects created by xmlbean is noNamespace.*;
    Regards,
    Jeyakumar C.K

    Hi Jeyakumar,
    The methods defined in XML beans should be public.
    Have you tried it with weblogic workshop?
    The reason that the package name is noNamespce is because the targetNamespace is not defined in your schema.
    Hope this helps.
    Kind Regards,
    Jennifer

  • Problem when adding java objects in a vector and passing thru web service

    Hi! I'm getting this error when I try to add a java object I created into a vector and passing it through a web service: java.lang.IllegalArgumentException: No Serializer found to serialize a 'testObj' using encoding style 'http://schemas.xmlsoap.org/soap/encoding/'
    This does not happen when I simply add strings or Integer objects into the vector. What am I missing?
    Thanks.

    just chek this
    http://forum.java.sun.com/thread.jspa?threadID=501189&messageID=2370914
    Edited by: garava on Jul 16, 2008 1:13 PM.
    It would be great if you could paste the wsdl part for that vector and just have a look for the complex typr cntent
    like for HashMap we have the following mapping
    <complexType name="HashMap">
      <sequence>
        <element name="item" minOccurs="0" maxOccurs="unbounded">
          <complexType>
            <sequence>
              <element name="key" type="anyType" />
              <element name="value" type="anyType" />
            </sequence>
          </complexType>
        </element>
      </sequence>
    </complexType>Since in Value it should again contain a mapping for the Object which you are trying to pass then only an appropriate serializer and deserilaizer would get generated. Hope this answers your query. For refernece
    http://www.theserverside.com/tt/articles/article.tss?l=Systinet-web-services-part-2
    [http://www.theserverside.com/tt/articles/article.tss?l=Systinet-web-services-part-2|For refernce tutorial]
    Thanks,
    Avadhoot Sawant.
    Edited by: garava on Jul 16, 2008 1:16 PM

  • Dereferenced objects are hold by Finalizer and stay in memory forever

    One of my application is running out of memory constantly. I profiled it with jmap/jhat and found that a large growing number of dereferenced com.sun.net.ssl.internal.ssl.SSLSessionImpl objects stay in memory, only referenced by same number of Finalizer objects. These objects are created indirectly by part of the code that frequently calls Apache common-httpclient for another HTTPS service. Full garbage collection can't release them from tenured space, they grows as requests come in and stay in tenured space forever. This issue is very similar to http://forum.java.sun.com/thread.jspa?threadID=346348.
    I tried following things but none of them helped:
    1. Call System.runFinalization();
    2. Increase priority of Finalizer thread;
    3. Try several types of garbage collector: the default serial collector, ParallelOldGC and ConcMarkSweep
    4. Take system out of network and hope finalizer slowly keep up the pace
    5. Increase ParallelGCThread
    6. Increase Eden space and Survivor space and make sure they are rarely full
    If it's not a bug of SSLSessionImpl, is there any way to force to clean up a type of dereferenced objects explicitly and synchronously? Any suggestions for this issue?
    Thanks
    -Jiaqi

    One of my application is running out of memory constantly. I profiled it with jmap/jhat and found that a large growing number of dereferenced com.sun.net.ssl.internal.ssl.SSLSessionImpl objects stay in memory, only referenced by same number of Finalizer objects. These objects are created indirectly by part of the code that frequently calls Apache common-httpclient for another HTTPS service. Full garbage collection can't release them from tenured space, they grows as requests come in and stay in tenured space forever. This issue is very similar to http://forum.java.sun.com/thread.jspa?threadID=346348.
    I tried following things but none of them helped:
    1. Call System.runFinalization();
    2. Increase priority of Finalizer thread;
    3. Try several types of garbage collector: the default serial collector, ParallelOldGC and ConcMarkSweep
    4. Take system out of network and hope finalizer slowly keep up the pace
    5. Increase ParallelGCThread
    6. Increase Eden space and Survivor space and make sure they are rarely full
    If it's not a bug of SSLSessionImpl, is there any way to force to clean up a type of dereferenced objects explicitly and synchronously? Any suggestions for this issue?
    Thanks
    -Jiaqi

  • How to use Java objects in business rules 11g

    I have made one business rule with two XML facts and then follow one doc to create the java facts.But I am unable to use the facts.

    No Java Facts are created,but as I have mentioned XML input and output facts at the time of creation of business rules,so I am not able to use java fact in business rule.
    Edited by: 856272 on Jan 4, 2012 6:22 AM

  • How can I change a var in class C from class B if C and B are created in A?

    Hi!
    I have a little problem. It´s not really a Swing problem as you may believe by reading below, it´s about object creation.
    I have a JFrame class called TransactionDialog. The TransactionDialog contains a JPanel with a CardLayout.
    The CardLayout contains two components:
    1) JPanelStep1 (an own class that extends JPanel)
    2) JPanelStep2 (an own class that extends JPanel)
    I want a variable in JPanelStep2 to depend on what the user does in JPanelStep1.
    The question:
    Both the JPanelStep1 and JPanelStep2 objects are created in the TransactionDialog class. How can I call the JPanelStep2 object (which is created in TransactionDialog ) from JPanelStep1 if JPanelStep1 has to be created before JPanelStep2 in the TransactionDialog class?

    Jacobs has the right idea.
    If this variable is part of the SWING display, you can do it the quick and easy way by passing that display object to JPanelStep1 and allowing that panel to mutate the value.
    For instance:
    JPanelStep1 step1 = new JPanelStep1();
    JPanelStep2 step2 = new JPanelStep2();
    step1.setDependent(step2.getDependent());
    And the methods would be for example:
    void setDependent(JTextField field) {
    this.field = field;
    JTextField getDependent() {
    return field;
    And whenever the user interacts with JPanelStep1 and you want to alter the text as it displays in JPanelStep2 you just make a call in JPanelStep1 to:
    field.setText(updatedText);
    Do not forget though that if you do not have your MDT squared away, the update might not occur immediately, without calling to your JFrame or throwing a thread on the MDT with invokeAndWait()

Maybe you are looking for

  • How can I get an ImageIcon back from a JToggleButton...

    When I create a JToggleButton I have to create an ImageIcon and pass it to the constructor. e.g. JToggleButton toggleButtonA = new JToggleButton( new ImageIcon( "images/A.gif" ) ); But when I want to get that ImageIcon back, all I can find in the doc

  • Using Webkit inside of AIR to load in PHP

    Hello, We have a game that we are developing for tablets that we are porting over from a browser based Flash game. In that game, there is a link to a PHP script that loads in player information and displays it on a web page. We would like to be able

  • Metadata/Custom Columns + SkyDrive Pro

    Hi I am trying to Synchronise documents across devices from SharePoint Online using SkyDrive Pro. Is it possible to Sync libraries that have Custom Columns?  In particular lookup columns?  I have tried doing it on a Document library with one lookup c

  • HT1178 wifi to set up time capsule

    if i don't have the cable can i set up time capsule using wifi?

  • Cisco CUEAC 9.1 configurations

    I have installed Cisco CUEAC 9.1. In User Configuration mode then in Queue MGMT option, i am unable to find Queue DDI option like as in previous version 8.6. We have following options. 1. Name  2. Queue DDI 3. Priority 4. Saluation But in 9.1 version