0

I want to access a static variable set in one Java class in another class. I am using the syntax properly I guess but I am getting null everytime.

Could someone help with this?

Class 1:

public class Test { 

    public static List<String> dbobj;

    public static void main(String args[]) {
        List<String> accnos= new ArrayList<String>();

        accnos.add("1");
        accnos.add("2");
        accnos.add("3");
        dbobj=accnos;
        System.out.println("dbobj"+dbobj);
    }
}

Class 2 :

public class Test2 {

    public void main(String args[]) {

    List<String> list1= Test.dbobj;
    System.out.println("List value"+list1);  **//COMING AS NULL**
    }   
}
rjdkolb
  • 10,377
  • 11
  • 69
  • 89
Sourav Mehra
  • 435
  • 2
  • 7
  • 23

5 Answers5

1

You have two entry points (programs) which absolutely independent of each other.

When you are calling a Test.dbobj, the main method from the Test is not executed, therefore its initialisation dbobj=accnos; is not called.

It is a bit awkward, but you could call the Test.main(args); before printing to execute that init process.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
0

When you're within the main method of Test2, the main of Test has not been called.
The static variable dbobj has therefore its initial value, being null.

Robert Kock
  • 5,795
  • 1
  • 12
  • 20
0

First of all you can't have 2 main functions and expect it to run both, so the better way to do this would be using a static code block in Class1 like this

static {
    List<String> accnos= new ArrayList<String>();

    accnos.add("1");
    accnos.add("2");
    accnos.add("3");
    dbobj=accnos;
    System.out.println("dbobj"+dbobj);
}
Jockie
  • 47
  • 2
  • 7
0

Try this changes in your class Test2:

Test.main(args); // added
List<String> list1= Test.dbobj;

Problem is you are using static variable dbobj from class Test without initializing that given variable. As of now, dbobj is assigned value inside Test.main(), so likewise you need to invoke that method.

0

There is no code executed that initialized the dbobj list, when your invoke main method in Test2 class. Therefore it points to NULL.

The easiest fix is to initialize it right when it is declared :

public static List<String> dbobj list = new ArrayList<>() {
  { add("str1"); add("str2"); }
};

The other solution is to fix Test1 class as below:

public class Test {
  public static List<String> dbobj;

  public static void init() {
    List<String> accnos = new ArrayList<>();
    accnos.add("1");
    accnos.add("2");
    accnos.add("3");
    dbobj=accnos;
    System.out.println("dbobj"+dbobj);
  }
}

public class Test2 {

    public void main(String args[]) {
      Test.init();
      List<String> list1 = Test.dbobj;
      System.out.println("List first value" + list1[0]);  // should be OK
    }   
}
MaxZoom
  • 7,619
  • 5
  • 28
  • 44