Published 27 Oct, 2022

Java - How to access global non static variable from static method

Category Java
Modified : Dec 01, 2022
57

I have main method in my java program, I want to store values in global variable because i want to access that values from different methods of the class, however I am not convinced to use static global variable, as the values in the variable keep on changing, so am afraid values which are declared as static may not change as it is defined on the class level, so I am looking for non static global variable. Can someone give an idea, how to achieve this.

Answers

There are 3 suggested solutions here and each one has been listed below with a detailed description. The following topics have been covered briefly such as Java, Static. These have been categorized in sections for a clear and precise explanation.

8

I suggest you make a separate class with with variables you want to store, with proper getter and setter methods. That way you keep the code more clean and maintainable and you follow the Separation of concerns principle, which tells us that every class should have it's own purpose.

EG:

 public class Person {
   private String name; // private = restricted access

   // Getter
   public String getName() {
   return name;
   }

  // Setter
  public void setName(String newName) {
  this.name = newName;
  }
}

 public class MyClass {
   public static void main(String[] args) {
     Person myObj = new Person();
     myObj.setName("John"); // Set the value of the name variable to "John"
     System.out.println(myObj.getName()); //Prints out name value
   }
 }

38

To start a java class uses the "main" static method present in all normal java programs. HOWEVER, the "constructor" method (really just "constructor") is named after the "main class" name and is where you initialise variables whether you call a declared method in the class or retrieve a static variable from the starter method "main".

The main method does not require any passer method to obtain a static variable from it to either set a global static variable in the class because it is only 1 step in hierarchy "scope" in the class (this is why some frameworks pass variables to global without typing of the method but rather instead using "void" on the method declaration) BUT you cannot put a non static method call in a static section of code such as the main method.

The way you remove static context from a variable is to make another variable with the same name in a non static context and cast the static variable to the non static instance.

e.g. for a global String primitive type variable from main method at construction time globally declare

static String uselessRef1 = ""; //  declared globally initialised

// following is declared inside the static method main
uselessRef1 = args[1]; // static argument 1 from the main method args[] array

// following is declared in global scope code or in the constructor code
    String uselessRef1b = (String)uselessRef1; // (String) cast removes the static context of the String type and copies to non static version of the type

While committed inline in the global declarations not in the constructor they are deemed to be loaded in the class constructor in sequence.

NB: You can put or make a static method in a non-static class but not the make a non static method in a static class.

import.javax.swing.*;
public class ExampleStaticRemoval{
static String uselessRef1 = ""; //  declared globally initialised
String uselessRef1b = ""; 
ExampleStaticRemoval(){

// following is declared in global scope code or in the constructor code
    uselessRef1b = (String)uselessRef1; // (String) cast removes the static context of the String type and copies to non static version of the type 
    printOut();

}// end constructor



    // program start method
    public static void Main(String[] args){
    new ExampleStaticRemoval();
        // static global class variable uselessRef1 is assigned the local method value
    // MUST BE OUTSIDE AT TOP TO BE GLOBAL
        uselessRef1 = args[0] +"  "+args[1]; // join static arguments 0 and 1 from the main method args[] array

}// end main



    public void printOut(){
    JOptionPane.showConfirmDialog(null,uselessRef1b, uselessRef1b, 0);
}//end method


} // end class

31

Since Java promotes the use of classes rather than global variables, I would highly recommend you to use a class for storing the data. That way, you do not need to use static methods or static variables.

One example of this is shown below:

import java.util.*;
public class Main{
    public static void main(String[] args) {
        int initialValue = 1;
        Holder holder = new Holder(initialValue);

        int currentValue = holder.getValue();
        System.out.println("Value after initial creation: " + currentValue);

        System.out.println("Set value to 10");
        holder.setValue(10);

        currentValue = holder.getValue();
        System.out.println("New value is " + currentValue);
    }
}

Holder class:

public class Holder {
        private int val;
        public Holder(int value){
            setValue(value);
        }
        public void setValue(int value){
            this.val=value;
        }
        public int getValue(){
            return this.val;
        }
    }