Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does static succeeded only by two curly brackets means? [duplicate]

Tags:

java

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;
};
}
like image 577
Student Avatar asked Jan 24 '15 19:01

Student


People also ask

What does a curly bracket represent?

: either one of the marks { or } that are used as a pair around words or items that are to be considered together.

What is static {} in Java?

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.

What is the meaning of curly brackets in Java?

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. \

What does curly braces mean in typescript?

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.


1 Answers

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.

like image 133
Eran Avatar answered Oct 15 '22 23:10

Eran