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

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

    Declaring a variable in the main method will make it available only in the main. Declaring a variable outside will make it available to all the methods of the class, including the main method.

    Example :

    public class Foo {
       private String varOne = "Test";
    
       public void testOne() {
         System.out.println(varOne);
         System.out.println(varTwo); // Error, this variable is available in the testTwo method only
       }
    
       public void testTwo() {
         String varTwo = "Bar";
         System.out.println(varOne); // Will display "Test"
         System.out.println(varTwo); // Will display "Bar"
       }
    }
    

提交回复
热议问题