The Artima Developer Community
Sponsored Link

Java Answers Forum
Local variable: null declaration

1 reply on 1 page. Most recent reply: Sep 28, 2005 9:50 PM by Amol Brid

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Gerrit

Posts: 4
Nickname: sifman
Registered: Sep, 2005

Local variable: null declaration Posted: Sep 28, 2005 9:27 PM
Reply to this message Reply
Advertisement
When I declare a local variable (reference type), and instantiate it with the value null (let's say a variable that is assigned its value inside a try block, but is needed outside the try block again), is there a chance that the GC might destroy that initial reference before it is even set inside the try block, because it is initialized with null?

Or does declaring a local var like that in fact mean that there wasn't even any space allocated at all on the heap because its initial value is null, and thus the GC won't even touch it?

Thanks in advance.


Amol Brid

Posts: 43
Nickname: amolbrid
Registered: Feb, 2004

Re: Local variable: null declaration Posted: Sep 28, 2005 9:50 PM
Reply to this message Reply
Setting reference variable to null does not mean that GC will reclaim the memory allocated to that variable. The job of GC is to reclaim the memory which is referred by reference variable(memory allocated to the object). As far as reference variable is considered, it will be destroyed as soon as its scope ends. So if you are doing something like this then it is 100% safe:
StringBuffer str = null;
 
try {
   str = new StringBuffer("Test String");
   // some other code
} catch(Exception e) {
  
}
 
System.out.println(str);
 

Flat View: This topic has 1 reply on 1 page
Topic: chained exception doubt Previous Topic   Next Topic Topic: Query on Facade Pattern

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use