OPK
OPK

Reputation: 4180

Why can create non-static variable in the main but not outside the main. Java

Why when doing this, IDE says you need to change str1 and str2 to static:

public class Test {

    String str1;
    String str2;

    public static void main(String[] args){


        str1 = "A";
        str2 = "B";
    }
}

But this is fine:

public class Test {



        public static void main(String[] args){

            String str1;
            String str2;
            str1 = "A";
            str2 = "B";
        }
    }

Why is it ok to declare a non-static variable inside a static method but not ok outside the static method?

Upvotes: 0

Views: 244

Answers (2)

j_v_wow_d
j_v_wow_d

Reputation: 511

public class Test {

    String str1; //This is a variable that will be specific to each instance of the class Test
    String str2; //This is a variable that will be specific to each instance of the class Test

    public static void main(String[] args){


        str1 = "A"; //This static method is not dependent on any instance
                    //so as far as a static method is concerned there is not str1
        str2 = "B"; //This static method is not dependent on any instance
                    //so as far as a static method is concerned there is not str3
    }
}

public class Test {



        public static void main(String[] args){

            String str1; //This variable is now independent of any instances of Test
            String str2; //This variable is now independent of any instances of Test
            str1 = "A"; //You can access those static variables from outside an instance
            str2 = "B"; //You can access those static variables from outside an instance
        }
    }

Upvotes: 0

Dongqing
Dongqing

Reputation: 686

Static method in a class only has reference to static member of the classes. "main" method is same as normal static method and follows the same rule.

For non-static members of a class, you must initialize an instance of the class firstly, then you can access the member.

public class Test {

    String str1;
    String str2;

    public String getStr1(){
        return str1;
    }

    public String setStr1(){
        this.str1 = str1; 
    }

    public static void main(String[] args){
       //create an instance of the class firstly.
       Test test = new Test();

       // read and write the str1
       System.out.println(test.getStr1());
       test.setStr1("A")
       System.out.println(test.getStr1());
    }
}

Upvotes: 1

Related Questions