Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jan 2014
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    lifetimeof primitives..??

    i started learing java
    reading thinking in java
    i cam across this
    java objects do not have same lifetime as primitives
    an object retains in memory even after its scope until garbage collector detects and releases the memory

    well whats the lifetime of primitives..??
    their memory will be released after the scope..??

  • #2
    New Coder
    Join Date
    Jul 2012
    Posts
    10
    Thanks
    2
    Thanked 0 Times in 0 Posts
    From what I know, once your variable (primitive or reference) is outside of the scope of which it is created, it is removed by Java's garbage collection system. This may not happen instantaneously, but either way you no longer have access to that variable's value.

    Example:
    Code:
    public static void main(String[]args) {
    //These variables remain until the program/main method is finished executing
    Box myBox = new Box(10,40,50);
    int myNum = 10;
    
    
    //The new box takes on the vale (by reference) of the one create in the function
    Box anotherBox = multiply(myBox, myNum);
    }
    
    //int m is used only locally and will exist only when this function is executing because it is passed by actual value
    public static Box multiply(Box b, int m) {
    //This instance of box would be garbage collected after multiply() is finished, except it is returned
    Box newBox = new Box();
    
    newBox.setLength = b.getLength * m;
    newBox.setWidth = b.getWidth * m;
    newBox.setDepth = b.getDepth * m;
    
    return newBox;
    }
    Primitives follow the basic lifespan of objects you just have to keep in mind when things are being passed by reference of value. Hope this helps


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •