Search code examples
javavariablesglobal-variables

How can I access local variable in main code block?


I want to access the checkWord variable in the main code block. I don't know how to access it globally. How can I access a local variable in main in Java?

This is example code blocks.

textField.setOnAction(event -> {
            try{
                ArrayList<String> wordList = wordListReader();
                boolean checkWord = false;
                for(String word:wordList){
                    if(word.equals(textField.getText())){
                        checkWord = true;

                    }

                }
                System.out.println(checkWord);
            }catch (FileNotFoundException ex){
                ex.printStackTrace();
            }
        });
// Error
System.out.println(checkWord);

Solution

  • Design-wise, global variables (static fields in Java) are usually not a great idea because it causes a tight coupling between classes, making it harder to make changes to the system later on.

    That said, to do what you describe you would do this:

    public class YourClass {
    
        // class field
        public static boolean checkWord;
    
        // instance (object) field
        private TextField textField = new TextField("Your text field");
    
        public void yourMethod() {            
            textField.setOnAction(event -> {      
                // ...      
                checkWord = true;
                // ...
            });
            System.out.println(checkWord);
        }
    
        public static void iDoNotKnowAboutInstances() {
            // OK
            System.out.println(checkWord);
            // Compile error - cannot refer to instance field in static context
            System.out.println(textField);
        }        
    }
    

    Meanwhile, in another class:

    public class YourOtherClass {
    
        public void yourOtherMethod() {
            System.out.println(YourClass.checkWord);
        }
    }
    

    A static field exists at class level. It is initialized when the class is loaded by the class loader for the first time, in this case it will be initialized as false (the default for booleans). Then, when yourMethod is executed and an event is handled, the field checkWord is set to true. It can be referred to directly from within the same class. From another class it can be referred to by prefixing the class name, as shown in YourOtherClass.

    EDIT: Not that you can refer to static fields from anywhere (as long as their visibility qualifier allows it) but you only refer to instance field via an actual instance. So for example from the static method iDoNotKnowAboutInstances you cannot refer to instance field textField. You often run into this when you create a simple java application with the entry method public static void main(String[] args). If you then add instance fields to the class you will first need to create an instance of the class using YourClass instance = new YourClass() to be able to read and write those fields.