First, to expand on my comment: the quotation you brought warns you against relying on the default values of fields.
When you define a field, for example:
private int diff;
It will have the value zero. You could write code in one of your methods that does something like:
result = 5 + diff;
And since diff
is zero, this will work. But it's bad practice. If you want to rely on the fact that diff is zero, you should declare it as
private int diff = 0;
Or otherwise initialize it before starting to use it.
This is unrelated to your actual two question. So, which of those two cases would use more hardware?
private static String var1;
This allocates enough bytes in heap memory for a String
reference when the class is loaded. This is part of the heap dedicated to class variables (since the variable is static).
var1 = "Hello";
This allocates memory to the "Hello" (this allocation is done early because this is a literal, but it's nevertheless allocated), and assigns (copies) the reference to the variable var1
.
So:
- 1 reference location in memory allocated.
- 1 string object allocated. (
"Hello"
)
- 1 assignment of that string.
- 1 copy of that reference to the stack for the
println
method.
In the second method, you are using local variables and method parameters. Local variables and parameters are allocated during the execution of the code, on the stack. When a method is called, enough space is allocated for all the parameters and local variables it will use.
- 1 stack location for reference allocated in
main
to var1
- 1 string object allocated to
"Hello"
- 1 assignment of that string to
var1
- 1 stack location for reference allocated in
method1
for chain
.
- 1 assignment to a reference - passing the value of
var1
to chain
in the method call.
- 1 copy of that reference to the stack for the
println
method.
So, without going into how many bytes and how many CPU cycles are spent exactly in these operations, it is clear that the second method takes a bit more hardware than the first.
Does that matter? No, not really. Optimization (saving up resources) should be done only when you actually experience slowness or memory bloat in your application. It is much more important to design the class properly. And to that end, I believe the consensus would be that the second case, with the local variables and parameter passing, is superior to the first case, with its static variable.
Why? It's a long and opinion-prone discussion, but, for example, using class and even instance variable is much like using global variables. You can change them outside of the method that uses them, which means if you change the implementation you might change values your methods are relying on. It's likely to be harder to read and understand, and harder to debug. It's best to keep instance variables to represent true "state" of an object, and class variables (static) should be used as little as possible.
Clean design generally trumps hardware considerations.