Answer the question
In order to leave comments, you need to log in
Why is a static block required when initializing static variables that require evaluation?
Now I'm learning Java from Schildt's book. I got to the static keyword. It says that if calculations are required to initialize static variables, then a static block is declared for this purpose.
class UseStatic{
static int a=3;
static int b;
static{
b=a*4;
}
}
class UseStatic{
static int a=3;
static int b=a*4;
}
Answer the question
In order to leave comments, you need to log in
Well, it's just arithmetic operations. And if you need to make a more complex initialization of a static field? For example, with a method call that throws an exception? Then it's done in a static block.
But it's better not to do that. Complex initialization is better to take out in a separate private stat method and already assign it to a variable.
static int a = intA();
private static intA() {
...
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question