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
What you refer to is the scope of a variable.
Variables inside methods are only accessible inside this method, ie an_integer
inside the main
-method cannot be referenced outside the main
method. Variables can even have narrower scopes, for exammple inside loops. The classic iterating variable of a for
loop is only avaiable inside its loop, afterwards its gone.
Variables outside methods are called fields. It depends on its access modifier where it can be seen. Private
fields for example are only avaiable inside this class, public
fields can be accessed from anywhere (other access modifiers are protected
and none, which falls back on a default). Basically, you can use a field inside a class to access its value from every method inside this class, this, however, might be dangerous if multiple threads access the same instance of a class, but this is a whole other story.
A field and a local variable may have the same name, which can lead to confusion. I would generally prefer not to do this, or, maybe better, always refer to fields with a this
accessor. I am not entierly sure whether there is a preference of local variables versus fields of the same name, but I would guess local variables are of higher priority when determining which one was meant.
Static
fields now mean that this variable does not belong to an instance of a class, but to the class itself. Static
fields (and methods) can be read (or invoked) without having to initialize the class first. An example could be a standardvalue of a class, or maybe a factorymethod (if its a method). Static
fields may also come in handy for constants, together with the final
modifier. A public final static
field is pretty much a global constant.