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

前端 未结 6 577
我在风中等你
我在风中等你 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:45

    There is a scope difference. And you have to declare it as static because your main function is static so it allows you to use only static variables. Variable which declares inside main method would only be used inside main method only.

    Now you might wondering that why I need to have main method as static!!! As any application in java will run from main method so it can be called by class name only without creating any object so we are defining it as static. All static method can call with class reference, no object needed.

提交回复
热议问题