1

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.

7
  • No it doesnt, please read my question, i want the variable to be accessed throughout the class, not just from one method. Commented May 28, 2020 at 7:04
  • Yeah, misinterpreted your question, sorry. Still, either you use a static field, or you use a non-static one which you won't be able to access from static methods and will be different for each instance. I'm not sure I understand why you don't want to use a static field. Commented May 28, 2020 at 7:07
  • , so am afraid values which are declared as static may not change as it is defined on the class level, What do you mean, do you want it to be mutable? Commented May 28, 2020 at 7:09
  • as I said, i have observed over the years that if we put different values or keep on changing the values of static variable, it doesnt really reflect sometime, this is my worry Commented May 28, 2020 at 7:12
  • 1
    Static doesn't mean 'unchanging', it means 'belongs to a class, not to an instance'. However, in a lot of cases, using static for things that change is a code smell, and better solved in other ways. Commented May 28, 2020 at 9:49

3 Answers 3

1

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
   }
 }
Sign up to request clarification or add additional context in comments.

2 Comments

Since you are declaring the variables in new class, will it be accessible from the calling class(main)?
check answer now
1

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;
        }
    }

Comments

0

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

1 Comment

Can you please explain with one small program?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.