Theorical question about declaration/definition in java

Hi, we know the difference between declaration and definition:
-declaration: no memory is allocated.
-definition: memory is allocated.
In C/C++ if we want to define a variable we can make
int x;or
int x = 5; (we assign a value too)
while, if we just want to declare we can make
extern int x;Is there a way in java to simply declare a variable? According to me just arrays can be declared with
String[] arrayString;while istructions like
String myString;are definition as they allocate at least a String reference on the stack...am I wrong?

Squall867 wrote:
Hi, we know the difference between declaration and definition:
-declaration: no memory is allocated.
-definition: memory is allocated.That's not the definition I learned, back when dinosaurs roamed the earth, men lived in caves and used pterodactyls for airplanes, and computers were made of rocks.
Is there a way in java to simply declare a variable? According to me just arrays can be declared withThis is a pretty meaningless question.
In Java, whenever you declare/define a variable (there is no distinction), space is allocated for that variable. It's at least 1 byte for a byte or boolean, at least 2 bytes for a char or a short, at least 4 bytes for an int, float, or reference, and at least 8 bytes for a double or long. A given JVM implementation may actually use more bytes for any given type for word-alignment performance optimization.
Is there a way in java to simply declare a variable? According to me just arrays can be declared with
String[] arrayString;
This declares a reference variable of type reference to array of String. It will occupy at least 4 bytes.
while istructions like
String myString;are definition as they allocate at least a String reference on the stack...am I wrong?This declares a reference variable of type reference to String. It will occupy at least 4 bytes.
Note that an array reference variable is no different than any other reference variable.
Also note that for any variable, whether it lives on the stack or on the heap depends only on whether it's a member variable or a local variable. If objects are allowed to be created on the stack in future versions of Java, that distinction will get slightly more complex.

Similar Messages

  • Question about main difference between Java bean and Java class in JSP

    Hi All,
    I am new to Java Bean and wonder what is the main difference to use a Bean or an Object in the jsp. I have search on the forum and find some post also asking the question but still answer my doubt. Indeed, what is the real advantage of using bean in jsp.
    Let me give an example to illustrate my question:
    <code>
    <%@ page errorPage="errorpage.jsp" %>
    <%@ page import="ShoppingCart" %>
    <!-- Instantiate the Counter bean with an id of "counter" -->
    <jsp:useBean id="cart" scope="session" class="ShoppingCart" />
    <html>
    <head><title>Shopping Cart</title></head>
    <body bgcolor="#FFFFFF">
    Your cart's ID is: <%=cart.getId()%>.
    </body>
    <html>
    </code>
    In the above code, I can also create a object of ShoppingCart by new operator then get the id at the following way.
    <code>
    <%
    ShoppingCart cart = new ShoppingCart();
    out.println(cart.getId());
    %>
    </code>
    Now my question is what is the difference between the two method? As in my mind, a normal class can also have it setter and getter methods for its properties. But someone may say that, there is a scope="session", which can be declared in an normal object. It may be a point but it can be easily solved but putting the object in session by "session.setAttribute("cart", cart)".
    I have been searching on this issue on the internet for a long time and most of them just say someting like "persistance of state", "bean follow some conventions of naming", "bean must implement ser" and so on. All of above can be solved by other means, for example, a normal class can also follow the convention. I am really get confused with it, and really want to know what is the main point(s) of using the java bean.
    Any help will be highly apprecaited. Thanks!!!
    Best Regards,
    Alex

    Hi All,
    I am new to Java Bean and wonder what is the main
    difference to use a Bean or an Object in the jsp. The first thing to realize is that JavaBeans are just Plain Old Java Objects (POJOs) that follow a specific set of semantics (get/set methods, etc...). So what is the difference between a Bean and an Object? Nothing.
    <jsp:useBean id="cart" scope="session" class="ShoppingCart" />
    In the above code, I can also create a object of
    ShoppingCart by new operator then get the id at the
    following way.
    ShoppingCart cart = new ShoppingCart();
    out.println(cart.getId());
    ...Sure you could. And if the Cart was in a package (it has to be) you also need to put an import statement in. Oh, and to make sure the object is accessable in the same scope, you have to put it into the PageContext scope. And to totally equal, you first check to see if that object already exists in scope. So to get the equivalant of this:
    <jsp:useBean id="cart" class="my.pack.ShoppingCart"/>Then your scriptlet looks like this:
    <%@ page import="my.pack.ShoppingCart %>
    <%
      ShoppingCart cart = pageContext.getAttribute("cart");
      if (cart == null) {
        cart = new ShoppingCart();
        pageContext.setAttribute("cart", cart);
    %>So it is a lot more work.
    As in my mind, a normal class can also
    have it setter and getter methods for its properties.True ... See below.
    But someone may say that, there is a scope="session",
    which can be declared in an normal object.As long as the object is serializeable, yes.
    It may be
    a point but it can be easily solved but putting the
    object in session by "session.setAttribute("cart",
    cart)".Possible, but if the object isn't serializable it can be unsafe. As the point I mentioned above, the useBean tag allows you to check if the bean exists already, and use that, or make a new one if it does not yet exist in one line. A lot easier than the code you need to use otherwise.
    I have been searching on this issue on the internet
    for a long time and most of them just say someting
    like "persistance of state", "bean follow some
    conventions of naming", "bean must implement ser" and
    so on. Right, that would go along the lines of the definition of what a JavaBean is.
    All of above can be solved by other means, for
    example, a normal class can also follow the
    convention. And if it does - then it is a JavaBean! A JavaBean is any Object whose class definition would include all of the following:
    1) A public, no-argument constructor
    2) Implements Serializeable
    3) Properties are revealed through public mutator methods (void return type, start with 'set' have a single Object parameter list) and public accessor methods (Object return type, void parameter list, begin with 'get').
    4) Contain any necessary event handling methods. Depending on the purpose of the bean, you may include event handlers for when the properties change.
    I am really get confused with it, and
    really want to know what is the main point(s) of
    using the java bean.JavaBeans are normal objects that follow these conventions. Because they do, then you can access them through simplified means. For example, One way of having an object in session that contains data I want to print our might be:
    <%@ page import="my.pack.ShoppingCart %>
    <%
      ShoppingCart cart = session.getAttribute("cart");
      if (cart == null) {
        cart = new ShoppingCart();
        session.setAttribute("cart", cart);
    %>Then later where I want to print a total:
    <% out.print(cart.getTotal() %>Or, if the cart is a JavaBean I could do this:
    <jsp:useBean id="cart" class="my.pack.ShoppingCart" scope="session"/>
    Then later on:
    <jsp:getProperty name="cart" property="total"/>
    Or perhaps I want to set some properties on the object that I get off of the URL's parameter group. I could do this:
    <%
      ShoppingCart cart = session.getAttribute("cart");
      if (cart == null) {
        cart = new ShoppingCart();
        cart.setCreditCard(request.getParameter("creditCard"));
        cart.setFirstName(request.getParameter("firstName"));
        cart.setLastName(request.getParameter("lastName"));
        cart.setBillingAddress1(request.getParameter("billingAddress1"));
        cart.setBillingAddress2(request.getParameter("billingAddress2"));
        cart.setZipCode(request.getParameter("zipCode"));
        cart.setRegion(request.getParameter("region"));
        cart.setCountry(request.getParameter("country"));
        pageContext.setAttribute("cart", cart);
        session.setAttribute("cart", cart);
      }Or you could use:
    <jsp:useBean id="cart" class="my.pack.ShoppingCart" scope="session">
      <jsp:setProperty name="cart" property="*"/>
    </jsp:useBean>The second seems easier to me.
    It also allows you to use your objects in more varied cases - for example, JSTL (the standard tag libraries) and EL (expression language) only work with JavaBeans (objects that follow the JavaBeans conventions) because they expect objects to have the no-arg constuctor, and properties accessed/changed via getXXX and setXXX methods.
    >
    Any help will be highly apprecaited. Thanks!!!
    Best Regards,
    Alex

  • Where is the best place to ask questions about NetBeans 6 for Java?

    When it comes to Java discussions, all I can think is this forum, but what about Java Desktop Applications using NetBeans IDE 6?
    Question/Query 1:
    I just like to ask how I can make the Database Application Template under the Java> Java Desktop Application> Database Application:
    Well, the the nice Frame with prebuilt components are good, but how can we customize the Window Icon? Has anybody in this forum and particularly Netbeans 6 users encountered the same scenario?
    Question/Query 2:
    How can I make a splash page with such a Database Application template too?

    Hello Andy,
    we talk about Photoshop, or? In this case you should use Photoshop General Discussion
    You will find all the (other) communities by clicking "Adobe Communities" on the top of the window. Please have a look at
    https://forums.adobe.com/welcome (see screenshot) and/or open "All communities"
    Hans-Günter

  • Question about creating Forms in Java.

    Hello , im new to Java , i find kinda weird how Java creates Forms , its pretty simple in Oracle Forms ,
    why did Java designers make it this difficult ? do people say this is something bad about Java ?
    when i learned about the Layout Managers that Java provides i found out how much code one have to write just to create a simple form ,my question to the experienced java developers : what do you do to create a form , do you hard code it ? , or do you use something like GUI Builder in an IDE like NetBeans for example? and is the code generated by this builder easy to deal with and modify ?
    Thanks ....

    HeavenBoy wrote:
    Hello , im new to Java , i find kinda weird how Java creates Forms , its pretty simple in Oracle Forms ,
    why did Java designers make it this difficult ? do people say this is something bad about Java ?Some Oracle Forms fans certainly do. But the truth is that Oracle Forms application tie down all the components in fixed pixels. The typical Swing form can be resized and can function at different screen resolutions. So, when designing a Java form, we don't tend to work on a fixed grid but define the sizes and positions relative to other components. What's more the interface between the form elements and the data is completely flexible, and flexibility means extra effort.
    >
    when i learned about the Layout Managers that Java provides i found out how much code one have to write just to create a simple form ,my question to the experienced java developers : what do you do to create a form , do you hard code it ? , or do you use something like GUI Builder in an IDE like NetBeans for example? and is the code generated by this builder easy to deal with and modify ?
    Most I've tried have been a bit of a straitjacket, but I've recently been using the latest Netbeans offering and it's pretty good. I think the breakthrough was the introduction of the GroupLayout layout manager. This is a layout manager really designed for WYSIWYG form designers (pretty challenging to use hand coded).
    The way these things work is that the class generated contains some methods which cannot be edited by hand, but you can add any amount of your own code without interfering with the generated code. You hook your own code snippets into the generated code, for example you can select a property of an object, say the model of a JTree, and select "user code", then type in an expression returning the TreeModel you want to use.
    With listeners the designer will generate the method signature etc. but you can edit the body of the listener method.
    However I would always recommend that you hand code a form or two before resorting to on of these editors because it's important you understand the code, even where a designer writes it.

  • Question About Xerces Parser and Java  JAXP

    Hi,
    I have confusion about both of these API Xerces Parser and Java JAXP ,
    Please tell me both are used for same purpose like parsing xml document and one is by Apache and one is by sun ?
    And both can parse in SAX, or DOM model ?
    Is there any difference in performane if i use xerces in my program rather then JAXP, or is ther any other glance at all.
    Please suggest some thing i have and xml document and i want to parse it.
    Thanks

    Hi
    Xerces is Apaches implementation of W3C Dom specifiacation.
    JAXP is a API for XML parsing its not implementation.
    Sun ships a default implementation for JAXP.
    you have factory methods for selecting a parser at run time or you can set in some config file about what is the implementaion class for the SAXParser is to be chosen (typically you give give the class file of xerces sax parser or dom parser etc..)
    go to IBM Developerworks site and serch for Xerces parser config. which have a good explination of how to do it.
    and browse through j2ee api .may find how to do it.

  • Question about declaring type as interface

    Hi
    I am trying to get my head around declaring an object as the interface type (I think this is right correct me if I am wrong). Ok so I understand if I declare my object reference as the interface I will only get the methods of the interface defined in the objects class..? ie
    List myList = new ArrayList();I think any method particular to ArrayList will not be there. But I dont actually understand wha is happening here, I have a ref to a List but the object is actually an ArrayList?
    So if I passed ths list to a session object and got it out I could cast it back to the interface. I dont understand why or what is happening here.
    I hope someone understands my question enough that they can help me out, this has been nugging me for a while.
    Thanks

    I am trying to get my head around declaring an object
    as the interface type (I think this is right correct
    me if I am wrong). Ok so I understand if I declare my
    object reference as the interface I will only get the
    methods of the interface defined in the objects
    class..? ie
    List myList = new ArrayList();I think any method particular to ArrayList will not
    be there. If you use myList without casting, then, yes, only List's methods will be available, because all the compiler knows is that it's a reference to a List. It doesn't know that at runtime it will point to an ArrayList object.
    You could cast myList to ArrayList to get ArrayList-specific things (if there are any), but a) if you're not careful, you can end up with a ClassCastException at runtime (you won't here, but in general you can) and b) if you're going to do that, you have to question why you declared it as a List in the first place. There are cases where casting is appropriate, but you have to be careful.
    But I dont actually understand wha is
    happening here, I have a ref to a List but the object
    is actually an ArrayList?Yes.
    So if I passed ths list to a session object and got
    it out I could cast it back to the interface. I dont
    understand why or what is happening here.You could cast it to anything that the object actually is, that is, any of its superclasses and superinterfaces. If it's an ArrayList, you could cast it to any of the following: ArrayList, AbstractList, AbstractCollection, Object, Serializable, Cloneable, Iterable, Collection, List, RandomAccess.

  • Question about an entry level java programmer

    i was curious that if i do find a job in java as an entry level what kind of programming can i expect? i am sure some of the members over here were hired as an entry level. can you share your ideas with me? like any projects etc...

    What is your background in education? I don't know how much you know of Java, but that won't be the only thing they base their choice on. You barely ever have a project that uses exclusively java. Make sure you know basics of working with databases, different operating systems...
    The most important thing is that you can sell whatever you know as usefull for the job they have for you! Prepare yourself well for an interview. If you have the time, picture the type of work you expect from a vacancy. Ask yourself what technologies will be needed for that particular job and make sure you do at least know a little about them. Make sure you adapt your responses to the type of interviewer, type of company. In addition to that, don't tell people you know more than you do!
    Get some understanding on OO concepts.This would be a very important thing for some, but totally unnecessary to others. For me this is quite important! If your interviewer is a manager type, he won't be able to follow what you're talking about if you start talking about design principles! If your interviewer is a techie, then this is a good thing to show.
    JCP certification would be handy..From my experience this isn't a minimum requirement to get in. If the company values certificates, you can always use it afterwards to prove your dedication and get a raise once you're in. ;-)
    Further knowledge in Web components and Enterprice components (eg EJB) will be pluses.Again viewed from the 'make it sellable' side. If you come bragging that you're a Spring expert and your company is against open source frameworks, that won't be a point in your advantage.

  • Lame question about Enterprise vs. regular java

    ok,
    up until now my company has had no need for the Enterprise features, but now we are starting to look to the future and it seems we are going to need a bit of its functionality.
    My question is: does Enterprise require a licensing fee for commercial use? Is there any licensing fee at all? what kind of situations is it required in? i googled it and couldn't get a straight answer. thanks.

    pnandrus wrote:
    buzzword fever. i figured someone would suggest that.
    actually, its not buzzword fever. its just that my company uses a client-server model with a heavy
    application that resides on the actual ws, but communicates with an app server and a scheduler.
    We have some monthly processes that need to be distributed to different app servers from a single server
    . I have been writing POJO for 4 years, so i'm just learning about this stuff. However, i felt that i could use EJB in a container to communicate between app servers more easily than trying to implement it using POJO (if that's even possible), or using JNI. I'm new to this, so i was trying to use as little vocab as
    possible for fear of being mocked. Good idea.
    I don't see how EJB helps you out here.
    Anyways, is this an appropriate use of EJB? I'll basically want to be able to start this app up on an app
    server, then call methods remotely on other servers that will start the given processes on those machines.
    I will add more functionality later. Isn't that an EJB-worthy task? maybe i'm way off....I believe you can do it without EJB.
    Curious again - what is your understanding of EJBs, and how do they help you?
    SLSB, SFSB, MDB, and entity EBJs - which of the four is appropriate here, in your opinion?
    %

  • Question about the performence of Java Card

    Could anyone here tell me how slow running algorithms, like rc4�Ades3 or rsa, on an 8k EEPROM JavaCard?
    thanx in advance
    rong

    Hi:
    The performance of javacard is no direct relation with chips. At present most chips is still 8 bit processor. 16 bit processor has more higher price. The reason of running algorithm slow is same as the java applet running on PC platform. Any java and javacard applet must be interpreted by java VM or javacard VM. This way is different from common application windows-based running. This kind application is machine code which can be understanded by hardware directly. But bytecode of java applet is not. It must be translated into machine code by VM. So running speed must slow down. As I konw, some mainstream chip maker is developing javachip. It can run java applet several times faster than software implementation.
    Chen Song
    Beijing

  • A question about share interface in java card

    I meet a big problem in java card recently.
    I try to develop a loyalty and a purse in the JCOP 20 . I use the share interface to share data between two applets.At first I write two small applets to test the share interface.Then I manully dowon the two applets into the card but it doesn't work. The error always happen to the "getAppletShareableInterfaceObject" method.
    Following is part of the code.
    buffer[0]=(byte)0x06; buffer[1]=(byte)0x05; buffer[2]=(byte)0x04; buffer[3]=(byte)0x03; buffer[4]=(byte)0x02; buffer[5]=(byte)0x01; buffer[6]=(byte)0x01;
    //server applet ID
    AID loyaltyAID2 = JCSystem.lookupAID(buffer, (short) 0,(byte)7);
    if(loyaltyAID2==null) ISOException.throwIt((short)0x0902);
    loyaltySIO = (JavaLoyaltyInterface) JCSystem.getAppletShareableInterfaceObject(loyaltyAID2,(byte)0);
    //...........................................error happen in this line
    I try to find the error I find the error, so I trace to the server applet,I add a "ISOException.throwIt " method in the getShareableInterfaceObject in the server applet.
    I find if I add it,the "getAppletShareableInterfaceObject" will return but get the null object.
    It's correct.But when I remark the "ISOException.throwIt" and just return "this" ,the card will get "6F00".
    Following is my code.
    public Shareable getShareableInterfaceObject(AID clientAID,byte parameter)
    //ISOException.throwIt((short)0x9999);
    return this; } error happen in this line
    TKS...

    Yes I did do it,I modify the sample code of the SUN micro's loality and purse .Following is my source code.
    Client code(purseeasy).......
    //=========================
    package purseeasy;
    import com.sun.javacard.samples.JavaLoyalty.JavaLoyaltyInterface;
    import javacard.framework.*;
    public class purseeasy extends javacard.framework.Applet
    private byte[] echoBytes;
    private static final short LENGTH_ECHO_BYTES = 256;
         public purseeasy()
         echoBytes = new byte[LENGTH_ECHO_BYTES];
    register();
    public static void install(byte[] bArray, short bOffset, byte bLength)
    new purseeasy();
    public void process(APDU apdu)
    byte buffer[] = apdu.getBuffer();
    short bytesRead = apdu.setIncomingAndReceive();
    short echoOffset = (short)0;
    switch(buffer[2])
    case 0x31:
    AID loyaltyAID1 =JCSystem.getAID();
    short i=loyaltyAID1.getBytes(buffer,(short)0);
    if(loyaltyAID1==null)
              ISOException.throwIt((short)0x0901);
    buffer[0]=(byte)0xd1;buffer[1]=(byte)0x58;
         buffer[2]=(byte)0x00;buffer[3]=(byte)0x00;
         buffer[4]=(byte)0x01;buffer[5]=(byte)0x00;
         buffer[6]=(byte)0x00;buffer[7]=(byte)0x00;
         buffer[8]=(byte)0x00;buffer[9]=(byte)0x00;
         buffer[10]=(byte)0x00;buffer[11]=(byte)0x00;
         buffer[12]=(byte)0x00;buffer[13]=(byte)0x00;
         buffer[14]=(byte)0x31;buffer[15]=(byte)0x00;
         AID loyaltyAID2 = JCSystem.lookupAID(buffer,
    (short)0,(byte)16);
    if(loyaltyAID2==null)
         ISOException.throwIt((short)0x0902);
         JavaLoyaltyInterface loyaltySIO =
    (JavaLoyaltyInterface)
         JCSystem.getAppletShareableInterfaceObject(loyaltyAID2,(byte)1);
    if(loyaltySIO ==null)
         ISOException.throwIt((short)0x0903);
    loyaltySIO.grantPoints (buffer);
    break;
    apdu.setOutgoingAndSend((short)0, (short)18);
    //=====================================
    //Server program....share interface
    package com.sun.javacard.samples.JavaLoyalty;
    import javacard.framework.Shareable;
    public interface JavaLoyaltyInterface extends Shareable
    public abstract void grantPoints (byte[] buffer);
    //=============================================
    //Server program....loyalty
    package com.sun.javacard.samples.JavaLoyalty;
    import javacard.framework.*;
    public class JavaLoyalty extends javacard.framework.Applet     implements JavaLoyaltyInterface
    public static void install(byte[] bArray, short bOffset,
    byte bLength)
    {new JavaLoyalty(bArray, bOffset, bLength);
    public JavaLoyalty(byte[] bArray, short bOffset, byte
    bLength)
    register();
    public Shareable getShareableInterfaceObject(AID
    clientAID,byte parameter)
    return (this);
    public void process(APDU apdu)
    byte buffer[] = apdu.getBuffer();
    short bytesRead = apdu.setIncomingAndReceive();
    apdu.setOutgoingAndSend((short)0, (short)18);
    public void grantPoints (byte[] buffer)
         buffer[0]=0x08;
         buffer[1]=0x08;
         buffer[2]=0x08;
         buffer[3]=0x08;
         buffer[4]=0x08;
         buffer[5]=0x08;
         buffer[6]=0x08;
         buffer[7]=0x08;
    Could you tell me what wrong with my code???
    Thanks....

  • Very simple question about declaring variables

    if a create a new ' int ' as in the code below :
    static int counter;
    does the value of counter automatically default to ' 0 ' ?
    Does this also apply if i declare the var to be public, protected etc ( but not final )
    thanks

    Most languages will initialise an int to 0 if no value is specified but it is dangerous to rely on this as it is not always the case. It is therefore recommended as good practice that you always initialise your own variables to ensure they start with the value you wish and not something unexpected.
    Mark.

  • Real easy question about defining objects in java

    hey guys here is my problem. I am trying to implement an insert() method for my binary tree. i have my node class defined to contain
    public T element() {
              return _data;
    and then my actual tree class has an instance of this declared to be called runner.
    BTreeNode runner;
    runner = _root;
    The problem occurs when i try to compare what i am inserting (obj) with what i have (runner.element) The actual line of code is
    ( obj.compareTo(runner.element) < 0 )
    i get an error that says "runner.element cannot be resolved or is not a field".
    I believe the error comes because i didnt adequately define runner but im not sure how to take care of that. Any suggestions would be most appreciated.
    -peter

    this is all of the code that has a relation to the error I am getting. The error is found in the BasicBTree class and says
    "The method compareTo(T) in the type Comparable<T> is not applicable for the arguments
    (Comparable)"
    Basic Binary Tree Node class
    public class BTreeNode<T extends Comparable<T>> implements Position<T> {
         private BTreeNode<T> _left;
         private BTreeNode<T> _right;
         private BTreeNode<T> _parent;
         private T            _data;
         public T element() {
              return _data;
         }Basic Binary Tree class
    public class BasicBTree<T extends Comparable<T>> implements BinaryTree<T> {
    public void insert(T obj) {
              BTreeNode runner;
              runner = _root;
              if (obj.compareTo (runner.element()) = null) { // ERROR OCCURS HERE
                   _root = new BTreeNode(obj);
              return;   
    }the interface posistion
    public interface Position<T> {
         public T element();
    }

  • Beginer, I have a question about win Xp and java

    I dont know where to start, please help. I can give you a list of the tools I have, and would like to know what else I need to start programing and animation. Thanks

    It probably would be better to start with some language basics before you get over to animation. But that's up to you, of course.
    Anyway, here's what you need:
    Tools
    * The Java Development Kit (http://java.sun.com/j2se/1.4.1/download.html)
    Things to read
    * The Java Tutorial (http://java.sun.com/docs/books/tutorial/)
    * The API documentation (http://java.sun.com/j2se/1.4.1/docs/api/index.html)
    * These forums (http://forum.java.sun.com/)
    Kind regards,
    Levi

  • Question about SAP Gui for java

    I've just installed SAP GUI for java on my local compoter , when I chooe new and the system list is empty , Can any one tell me how to do with it ?
    It will be very helpful if you can provide me with an template of the config file .
    Best regards ?

    Hi,
         Check this link
    /people/manfred.lutz/blog/2007/03/16/new-blog-series-abap-trial-version-for-newbies
    Reward points if useful,
    Regards,
    Niyaz

  • Question about the GC in Java

    Given
    Given:
    3. class Beta { }
    4. class Alpha {
    5. static Beta b1;
    6. Beta b2;
    7. }
    8. public class Tester {
    9. public static void main(String[] args) {
    10. Beta b1 = new Beta(); Beta b2 = new Beta();
    11. Alpha a1 = new Alpha(); Alpha a2 = new Alpha();
    12. a1.b1 = b1;
    13. a1.b2 = b1;
    14. a2.b2 = b2;
    15. a1 = null; b1 = null; b2 = null;
    16. // do stuff
    17. }
    18. }Why there is only 1 object will be eligible for GC. I need a clear explanation pls

    newbie wrote:
    jverd wrote:
    newbie wrote:
    Pinto wrote:
    Since this looks like a homework assignment, how about you post what you think the answer is. Rather than just spoonfeeding you the answer which you will just hand in as your own work.It is not a homework assignment. It is practice test from SCJP. Nevertheless, since you're trying to learn, you'll learn better if you think it through as much as possible yourself, post what you think and why and solicit feedback on that, rather than just asking for the answer.
    How many objects do you think are eligible, and why?Thanks for your cheer.First of all I rename the instance variable of object Alpha. now i have
    Given:
    3. class Beta { }
    4. class Alpha {
    5. static Beta x;
    6. Beta y;
    7. }
    8. public class Tester {
    9. public static void main(String[] args) {
    10. Beta b1 = new Beta(); Beta b2 = new Beta();
    11. Alpha a1 = new Alpha(); Alpha a2 = new Alpha();
    12. a1.x = b1;
    13. a1.y = b1;
    14. a2.y= b2;
    15. a1 = null; b1 = null; b2 = null;
    16. // do stuff
    17. }
    18. I have a stack containing a1, a2, b1, b2 and heap is containing 2 objects of type Alpha, 2 objects of type Beta, x, y *(AM I RITE AT HERE)*Yes. Note that x and y are part of the two Alpha objects.
    At line 12 and 13, the instance variable y and class variable x of class Alpha point to an object of class Beta b1.Close. The instance variable y of one of the Alpha objects (not of the Alpha class) and the class variable x of class Alpha point to a Beta object--the same Beta that's pointed to by b1.
    At line 14,*instance variable y* points to an object of class Beta b2.Instance variable y of the other Alpha object points to the second Beta object--the same one that's pointed to by b2.
    Note that there are two y variables (one for each Alpha object) and one x variable (one for the Alpha class overall). That's the difference between an instance (non-static member) variable and a class (static member) variable.
    Finally, at line 15, a1, b1, b2 are set to null. Yup.
    Therefore, i think there are 2 objects which are eligible for GC ( 1 object of type Alpha and 1 object of type Beta)Well, let's see.
    a1 is null, so nothing is pointing to the first Alpha, so it's GC-able. Additionally, that first Alpha's y is no longer pointing to the first Beta, so you might think that makes that Beta unreachable. However, the class variable x (which is not specific to any Alpha instance) is still pointing to the first Beta. So far, one GC-able object.
    b1 is null, so it no longer points to the first Beta, but Alpha.x still points to the first Beta. Still one GC-able object.
    b2 is null, so it no longer points to the second Beta, but the second Alpha's y still does, so the second Beta is still reachable. Still one GC-able object.
    Remember, there are two y variables--one for each Alpha instance--and one x variable--one for the Alpha class as a whole.
    Part of what makes this example confusing is they followed a syntactically legal but bad practice approach of using a reference variable to refer to a static class member, rather than the class name.
    a1.x // legal, but confusing
    Alpha.x // preferred
    a1.y // the only legal way
    Alpha.y // error, won't compile -- how would the compiler know WHICH Alpha instance's y variable we mean?

Maybe you are looking for

  • Non-english caracters in file names

    Hi, I use archlinux, KDE, Dolphin. I have a problem with file names with the norwegian caracters ø æ å in some file names. I get the message that "the file does not exist". I can change the file name in the terminal, but it's a lot of work. In Dolphi

  • Oracle Streams PIT on Source DB

    I'm testing backup/recovery in my streams environment, simulating a PITR on the source. The objective is to get both the source and destination to the same point in time, driven by the source. That being said, if recover to a time 5 hours prior, on b

  • Index size 3 times more then table

    table cnmas record 134 only but there is lot of dml operation on this table SQL> SELECT COUNT(*) FROM CNMAS; COUNT(*) 134 1* SELECT SUM(BYTES)/1024/1024 FROM USER_SEGMENTS WHERE SEGMENT_NAME='CNMAS' SQL> / SUM(BYTES)/1024/1024 4 1* SELECT SUM(BYTES)/

  • [Faces] Criterias for multiple faces-config.xml files...

    Hi, I'm working in a big development proyect migrating an ERP. We know the mechanics of having multiple "faces-config" files, but is there some recommendation about the number of pages supported, or the total file size, or any other? We have found th

  • Error 1406. could not write to value Adobe ARM to key \Software\Microsoft\Windows\CurrentVersion\Run

    Had reinstalled Windows 7. Trying out Acrobat and keep getting this error: Error 1406. could not write to value Adobe ARM to key \Software\Microsoft\Windows\CurrentVersion\Run tried a few of the discussions and haven't been able to fix it