Tuesday, December 25, 2018

java - What does static succeeded only by two curly brackets means?




What does static succeeded only by two curly brackets means?
Sorry for the beginner question. I tried to look for a tutorial on it, but couldn't find one.
This use of static as: static {}, is not clear for me. I found it being used by others heredeveloperWorks.
I thought it may be a multiline, or group, modifier and tried the code below, but other type modifiers give errors not like static.



public class MyClass {
private volatile int v1=0;

private final int v2=0;
private static int v3=0;
static { <----- No error here.
int i1=0;
String s1="abc";
double d1=0;
};
final { <----- Error here.
int i2=0;
String s2="abc";

double d2=0;
};
volatile { <----- Error here.
int i3=0;
String s3="abc";
double d3=0;
};
}

Answer




It is a static initializer block, which is used to initialize static members of the class. It is executed when the class is initialized.



Your example :



static {            
int i1=0;
String s1="abc";
double d1=0;
};



makes no sense, since it declares variables that are only in scope until the execution of that block is done.



A more meaningful static initializer block would be :



static int i1;
static String s1;
static double d1;

static {

i1=0;
s1="abc";
d1=0;
};


This example still doesn't justify using a static initializer, since you can simply initialize those static variable when you declare them. The static initializer block makes sense when the initialization of static variables is more complex.


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...