File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes static variable:  can I always get its value ?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "static variable:  can I always get its value ??" Watch "static variable:  can I always get its value ??" New topic
Author

static variable: can I always get its value ??

mike zhang
Ranch Hand

Joined: Feb 26, 2002
Posts: 59
I have the follwoing test code:
***************************
package dir1;
import dir2.*;
import dir3.*;
public class Class1 {
public static void main(String[] args) {
String id = "abc";
Class4.NUMBER = id;
Class2 class2 = new Class2();
class2.doIt();
}
}
**********************************
package dir2;
import dir3.*;
public class Class2 {
public void doIt() {
Class3 class3 = new Class3();
class3.doIt();
}
}
***************************************
package dir3;
public class Class3 {
public void doIt() {
Class4 class4 = new Class4();
class4.getIt();
}
}
********************************************
package dir3;
public class Class4 {
public static String NUMBER;
public void getIt() {
String newNumber = NUMBER + "def";
System.out.println("newNumber = " + newNumber);
}
}
**************************************
The output is "newNumber = abcdef".
Question: When Class4 instance access its method, is that static NUMBER variable still existing ?
If the Class1,2,3,4 are very long code, could the Class4 have been garbage collected when the program reaches the line of
String newNumber = NUMBER + "def";
in Class4 so that NUMBER is no longer "abc" ?
Is the above code guaranteed to be safe in terms of letting Class4 get the value of "abc" for variable NUMBER ?
Thanks,
Mike
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 5288
    
  10

Mike,
Normally folks worry about keeping things around longer than they need to be but you seem to be worried that you'll lose the value assigned to NUMBER before you get a chance to use it.
Don't worry: Class4 will keep anything assigned to NUMBER. The static NUMBER variable will always exist because it is part of the class (due to the static keyword).
The point of having a garbage collection system is to relieve the programmer from the tedious and error-prone task of managing memory. So again, for the most part, you really shouldn't worry about these kind of issues at all.
Junilu


Junilu - [How to Ask Questions] [How to Answer Questions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static variable: can I always get its value ??