what is difference between declaring variable out of main method and inside main method?

前端 未结 6 562
我在风中等你
我在风中等你 2021-01-31 22:36

When I was reading book about Java , I saw one example written like this. And I am wondering can I declare variable in outside of main method ? What is difference between declar

6条回答
  •  遥遥无期
    2021-01-31 22:50

    The difference is now your an_integer has more scope.

    Example if you have another method.

    public class Printstuff {
          static int an_integer = 0;
            public static void main(String[] args) {
              int an_integer = 2;
              String[] some_strings = {"Shoes", "Suit", "Tie" };
              an_integer = an_integer - 1;
              some_strings[an_integer] = some_strings[an_integer] +"+++";
              for (int i = 0; i < some_strings.length; i++)
                System.out.println(some_strings[Printstuff.an_integer]);
            }
    
          public void anotherMethod(){
             an_integer++;
          }
    
    
        }
    

    As you declared

    int an_integer=0;

    All clases in the same package has access to this variable.

提交回复
热议问题