Win a copy of Event Streams in Action this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

static variable: can I always get its value ??

Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
package dir2;
import dir3.*;
public class Class2 {
public void doIt() {
Class3 class3 = new Class3();
package dir3;
public class Class3 {
public void doIt() {
Class4 class4 = new Class4();
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 ?
Posts: 13553
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Crusading Chameleon likes the size of this ad:
Java Code Review and Psychology
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!