Home » Java » java – How to create a Variable with scope global and but should not be a STATIC-Exceptionshub

java – How to create a Variable with scope global and but should not be a STATIC-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment


Need a variable to hold a value which will be assigned once and will be used by every method of a class

if I specify it as non static variable it is not holding the value

Class Test{

private String test;

public void method1(){
     test = "String1";

public void method2(){


Getting Null Pointer exception. the value of the test will be used in every method.

Could anyone help me, how to fix the issue.

How to&Answers:

The NullPointerException will be thrown whenever the test variable is null and you try to invoke methods on that variable. In your case, when you invoke method2() before method1(). That has nothing to do with global, local or whatever, as Long Vu already mentioned.

So first you should make sure, you don’t access an uninitialized variable. Then, if you need a class with a single instance, which should be accessible application wide, you can implement this using the singleton pattern. For more about it, have a look at this Wikipedia page: https://en.wikipedia.org/wiki/Singleton_pattern


Maybe your problem is that you are creating multiple objects of class Test.
For example this should work:

Test test1=new Test();
test1.method1(); //call this first then other methods

You should use this object “test1” as a parameter wherever you need it.

If you want to access the variable globally then create a Singletone class:

    class Test{ 

    private static Test single_instance = null; 
    private String test; 

    // private constructor restricted to this class itself 
    private Test(){ 

    // static method to create instance of Singleton class 
    public static Test getInstance(){ 
        if (single_instance == null) 
            single_instance = new Test(); 

        return single_instance; 

    public void setTest(String value){ 
        test = value; 

    public String getTest(){ 
        return test; 

  public static void main(String args[]){ 
        Test test = Test.getInstance();