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;
};
}
: either one of the marks { or } that are used as a pair around words or items that are to be considered together.
In the Java programming language, the keyword static means that the particular member belongs to a type itself, rather than to an instance of that type. This means we'll create only one instance of that static member that is shared across all instances of the class.
In a Java program, everything is subordinate to the top line — the line with class in it. To indicate that everything else in the code is subordinate to this class line, you use curly braces. Everything else in the code goes inside these curly braces. \
Curly braces { } are special syntax in JSX. It is used to evaluate a JavaScript expression during compilation. A JavaScript expression can be a variable, function, an object, or any code that resolves into a value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With