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
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 this Object/Variable belongs to the class itself, and not to its objects.
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