what is difference between declaring variable out of main method and inside main method?
java
Solution
1) Inside vs Outside:
If you declare your object inside a method, it will be visible only in this method. Basically, if you put brackets around it, it's only visible/accessible from within these brackets.
If you declare your object outside the method (inside the class), it depends on the access modifier. By default, it's visible/accessible from within that class and the whole package.
2) Static
Static means, that static methods / variables belongs to the class itself, and not to its objects (instances of that class).
Example:
public class Members {
static int memberCount;
public Members() {
memberCount++;
}
}
`memberCount` exists only once, no matter how many Objects of the class exists. (even before any object is created!)
Every time you create a new Object of `Members`, `memberCount` is increased. Now you can access it like this: `Members.memberCount`
Problem
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 declaring variable outside and inside main method? what is " static" 's role in here ? Please some one explain to me? I am new in java. ``` 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]); } } ``` Best regards.