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
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"
}
}