I’m confused with variable declarations in Java code.
I read… don’t try to use global variables declarations .
Don’t use something like this:
package cls;
public class test {
private String var;
public someMethod(){ ... }
}
And use ?
package cls;
public class test {
public someMethod(){
String var = null;
}
}
I don’t know which is the correct way….
It totally depends on what you need.
Your first example, however, isn’t a global variable–it’s an instance variable.
Variables should have as small a scope as possible. This makes code easier to reason about.
Instance variables are central to what OOP is all about–classes (objects) exist to encapsulate object state, and the methods that operate on that state. For example, a
Personclass would likely have first and last name instance variables:This allows instance methods to access the first and last name variables directly without having to pass them between all the methods that need them.
The second example is a local variable. It’s visible only in the method it’s declared in. A reference to it may be passed to other methods.