A
A
Artyom2016-05-26 13:47:31
Java
Artyom, 2016-05-26 13:47:31

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;
}
}

So the question is, why do this if changing the class to something like this, the result will be the same?
class UseStatic{
static int a=3;
static int b=a*4;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evhen, 2016-05-26
@JustAnotherGuyInWeb

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() {
...
}

I
IceJOKER, 2016-05-26
@IceJOKER

But what if you need something more than just multiplying numbers?
For example a static array with data?
stackoverflow.com/questions/2943556/static-block-i... - various examples and explanations here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question