This question already has answers here:
What is the difference between a static and a non-static initialization code block
(9 answers)
Closed 8 years ago.
I was looking over some code the other day and I came across:
static {
...
}
Coming from C++, I had no idea why that was there. Its not an error because the code compiled fine. What is this "static" block of code?
It's a static initializer. It's executed when the class is loaded (or initialized, to be precise, but you usually don't notice the difference).
It can be thought of as a "class constructor".
Note that there are also instance initializers, which look the same, except that they don't have the static keyword. Those are run in addition to the code in the constructor when a new instance of the object is created.
It is a static initializer. It's executed when the class is loaded and a good place to put initialization of static variables.
From http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
If you have a class with a static look-up map it could look like this
class MyClass {
static Map<Double, String> labels;
static {
labels = new HashMap<Double, String>();
labels.put(5.5, "five and a half");
labels.put(7.1, "seven point 1");
}
//...
}
It's useful since the above static field could not have been initialized using labels = .... It needs to call the put-method somehow.
It's a block of code which is executed when the class gets loaded by a classloader. It is meant to do initialization of static members of the class.
It is also possible to write non-static initializers, which look even stranger:
public class Foo {
{
// This code will be executed before every constructor
// but after the call to super()
}
Foo() {
}
}
Static block can be used to show that a program can run without main function also.
//static block
//static block is used to initlize static data member of the clas at the time of clas loading
//static block is exeuted before the main
class B
{
static
{
System.out.println("Welcome to Java");
System.exit(0);
}
}
A static block executes once in the life cycle of any program,
another property of static block is that it executes before the main method.
Static blocks are used for initializaing the code and will be executed when JVM loads the class.Refer to the below link which gives the detailed explanation.
http://www.jusfortechies.com/java/core-java/static-blocks.php
yes, static block is used for initialize the code and it will load at the time JVM start for execution.
static block is used in previous versions of java but in latest version it doesn't work.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I was wondering whether it is possible to call a static method from a static block in order to initialize static variables. Is e.g. the following possible:
public class AppProperties {
private static final Logger logger = LoggerFactory.getLogger(AppProperties.class);
private static final String PARSER_PROPERTIES_FILE = "/parser.properties";
private static final Properties PARSER_PROPERTIES = new Properties();
private static final Properties DAO_PROPERTIES = new Properties();
static {
loadParserProperties();
loadDaoProperties();
// Some other configuration
}
public static void loadParserProperties() {
// Loading parser properties
}
// Further methods omitted
}
Is it good practice?
EDIT:
Oracle recommends initialization as follows:
class Whatever {
public static VarType myVar = initializeClassVariable();
private static VarType initializeClassVariable() {
// Initialization code goes here
}
}
Their explanation is:
The advantage of private static methods is that they can be reused
later if you need to reinitialize the class variable.
However, the AppProperties code is also reusable. I have a feeling that I am missing something. Calling static methods from static blocks isn't mentioned, that's why I assume it is bad practice.
Static block call your method only once at time of class creation, If you want to call method at time of class creation you can call it.
Static block is only way by which you can call your static methods at time of class creation.
This should not be any issue related to design or best practice.
Anyways, it is advisable to divide chunk of code/functionality into different functions, and making them static and calling from static block is something your applications demands during loading of class by JVM.
The advantage of static methods is that they can be reused later if you need . So, you kind of get more flexibility with a static method in comparison to the corresponding static initialization block.
for more info here
Calling to static method from static block it acceptable in the case of you really want to execute the content in the referred static method only one time when the class is getting initialize in the JVM first time. Further you have to keep it in mind this static block won't ever execute again even though you created multiple object in same type with in your application except the first creation.
However you have to use static variables to store if there any values need to be use with the other object creation cycles.
Some extra points about static block might help someone.
Calling static methods inside of static block is accepted only in below conditions.
1) It must contain main method if the java version is 7 or above. Else it will throw below error
Error: Main method not found in class MyClass, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
2) If java version is 6 or below, it will work fine even if we don't have main method.
Example :
// The below code would not work in JDK 1.7 and above
class staticExample {
// static block execution without main method in JDK 1.6.
static
{
System.out.println("Inside Static Block.");
System.exit(0);
}
}
Output:(In JDK 1.6)
Inside Static Block.
But from JDK 1.7 onwards the above code gives an error in output.
Output:
Error: Main method not found in class staticExample, please define the main method as:
public static void main(String args[])
or a JavaFX application class must extend javafx.application.Application
You can do this. But it is not the best idea for a couple reasons.
One is that you have hard-wired your class to whatever property files the static method is reading, complicating testing. You can't exercise the class without having the actual files present.
Another is that exception-handling in static blocks is problematic, there's no way to handle an unchecked exception thrown from a static block. See Why doesn't Java allow to throw a checked exception from static initialization block?. You would have to specifically catch everything coming out of the block, and anything that was missed couldn't be caught anywhere in the application.
Dependency injection frameworks will handle injecting this stuff into your classes for you with easier testing and no exception-handling issues.
I was able to do some experiment using the Java language and surprisingly I came up using this lines of code {{ }}. More over I've noticed using that code structure, I can use any method of the class without creating an object variable for it.
For example:
class Sample {
public void hello() {
// Do something here.
}
}
class SampleTest {
public void testHello() {
new Sample {{ hello(); }};
}
// PSVM ...
}
The question is what is the concept/term called for the statement of line 8?
The first brace creates a new AnonymousInnerClass, the second declares an instance initializer block that is run when the anonymous inner class is instantiated. This type of initializer block is formally called an "instance initializer", because it is declared within the instance scope of the class -- "static initializers" are a related concept where the keyword static is placed before the brace that starts the block, and which is executed at the class level as soon as the classloader completes loading the class (specified at http://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#8.6) The initializer block can use any methods, fields and final variables available in the containing scope, but one has to be wary of the fact that initializers are run before constructors (but not before superclass constructors).
If you want some examples look here: http://c2.com/cgi/wiki?DoubleBraceInitialization
Sarajog
My projects had some developer who loved a static initialization block. What is the alternative to this? What is the downside of this alternative?
public class BlockTest {
String test = new String();
static{
test = "test string";
}
}
As far as I understood the static initialization block is used to set values of static field if it cannot be done in one line. But I do not understand why we need a special block for that. This leads to less readability and some confusion.
The example is not good. First of all it does not compile, you cannot assign a instance variable from static init block. But if even it were correct
public class BlockTest {
static String test = new String();
static{
test = "test string";
}
it would make no sense since it is equivalent to
public class BlockTest {
static String test = "test string";
but this static init block has no alternative
public class Object {
private static native void registerNatives();
static {
registerNatives();
}
...
It can be used for performing all the tasks that needs to be done when the class is referred for the first time, even before the instances of the class are created. It could have call to different methods or just initialization of static members. Static block ensures that these activities will be performed only once in the lifetime of the class and will be performed before any other operation takes place with regard to the class.
Programmer can depend on static block as it is ensured that the block will be executed only once and before any other activity related to that class is performed.
Moreover, I do not think it hampers readability at all. It again may vary from person to person.
If you have static members in your class which require a longer handling, you won't get around a static initializer (constructor). These must be initialized somewhere after all. You could do that in the constructor of your class, but then you would reinitialize these values EVERYTIME you create a new object.
There is no real alternative if you must handle more than just a simple initialization.
See this post and this.
If you have simple assignments, you can do the assignment directly in the member declaration. No need for a separate block which just extends the complexity and readabillity.
An alternative would be to use a lazy initialization. Advantage is that it can also be arbitrary complex, but is only executed when actually needed. But of course this only works if you have getters in your classes. If you access the members directly, then this would be a big change.
IMHO,There is no need for static block.
String test = "test string";
And From docs
Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.
But
Note: It is not necessary to declare fields at the beginning of the class definition, although this is the most common practice. It is only necessary that they be declared and initialized before they are used.
This question already has answers here:
Why is this Java code in curly braces ({}) outside of a method?
(3 answers)
Java empty block scope
(3 answers)
Closed 9 years ago.
I accidently made a pair of {} outside of all method and worked.
public static void main(String[] args) {
System.out.println("ddd");
}
{
System.out.println("ttt");
}
Of course if you run this code the result is "ddd" and it writes "ttt" only if I create a new instance of it.
And if I make it static {System.out.println("ttt");} it works as designed and the result is "ttt" then "ddd"
Is there any practical use of this? Why would anyone use it with contructor or without a written constructor?
My impressions are: it seems working, but smells like bad and strange practice. Am I right?
{} define the scope of a module or block of code (like a method, static block, class, etc.)
And every module should have a name of something to identify it from other modules.
In your case, simply putting {} means you are creating a block of code but not naming, hence it gives error. But putting {} inside a method will work fine.
But when you put static keyword before it, you are making a static block that has got special meaning in java. it means that everything inside static block will be executed when your class gets loaded first time.
See this link for initializer blocks from Java Tutorials website
Is there any practical use of this?
There is one "idiom" that makes use of instance initializer blocks:
Map mymap = new HashMap() {{put("a", 1); put("b", 2);}};
This is a concise way to create a map that is initialized with a given set of entries. And when you break it down, it is declaring and instantiating an anonymous subclass of HashMap which uses an instance initializer block to populate the new map.
My impressions are: it seems working, but smells like bad and strange practice.
That's a subjective statement. The only rational argument I can think of for initializer blocks being bad / strange is that people don't use them. And that argument smells of circular logic.
Its all about Initializer blocks
Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
{
// will execute when intialization
}
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
These are called initializer blocks. They are called along with all constructor. So any constructor call will invoke this code.
A static block is called only when class is loaded.
Normally, you have to put the code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods.
Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
Source: here
It may be unfamiliar, but it is not bad per se. It's an initializer block that is executed on construction. See here for a more detailed explanation that includes static initialization blocks also.
Our application is using initialization code that depends on the order static code is executed and I'm wondering if this order will be consistent across all JVMs.
Here is a sample of what I mean:
public class Main {
static String staticVar = "init_value";
public static void main(String[] args) {
System.out.println(A.staticVar);
staticVar = "mainValue";
System.out.println(A.staticVar);
}
}
public class A {
static String staticVar = Main.staticVar;
}
will give:
init_value
init_value
and
public class Main {
static String staticVar = "init_value";
public static void main(String[] args) {
// System.out.println(A.staticVar);
staticVar = "mainValue";
System.out.println(A.staticVar);
}
}
public class A {
static String staticVar = Main.staticVar;
}
will give (on my environment):
mainValue
To summarize, across all JVMs, is static code always executed when we use a class for the first time?
EDIT: Despite all the reassurances below, if you're thinking of relying on this sort of thing, I would try hard to refactor your code so that it doesn't crop up. While it is guaranteed to work, it's also likely to make your code very brittle. The fact that static initializers get called "invisibly" makes them relatively hard to reason about and debug.
Yes, this is guaranteed by the language specification. From section 8.7 of the spec:
Any static initializers declared in a class are executed when the class is initialized and, together with any field initializers (§8.3.2) for class variables, may be used to initialize the class variables of the class (§12.4).
StaticInitializer: static Block
It is a compile-time error for a static initializer to be able to complete abruptly (§14.1, §15.6) with a checked exception (§11.2). It is a compile-time error if a static initializer cannot complete normally (§14.21).
The static initializers and class variable initializers are executed in textual order.
And from section 12.4:
Initialization of a class consists of
executing its static initializers and
the initializers for static fields
declared in the class. Initialization
of an interface consists of executing
the initializers for fields declared
in the interface.
Before a class is
initialized, its direct superclass
must be initialized, but interfaces
implemented by the class need not be
initialized. Similarly, the
superinterfaces of an interface need
not be initialized before the
interface is initialized.
A class or interface type T will be
initialized immediately before the
first occurrence of any one of the
following:
T is a class and an instance of T is
created.
T is a class and a static
method declared by T is invoked.
A
static field declared by T is
assigned.
A static field declared by T
is used and the field is not a
constant variable (§4.12.4).
T is a
top-level class, and an assert
statement (§14.10) lexically nested
Static initialisers (e.g. your staticVar declarations) are always executed when you use a class for the first time.
Static methods are only executed when they are called. In your case, this is happening because the static void main(String[] args) is the entry point to your application. But if you defined a different static method then it would not be called.
It is also possible to create a static initialiser block that will also be called automatically before the class is first used, e.g.
static {
// some initialisation code here
}
That should be all the same on all platforms. See JVM Specification : http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#19075
A quote from Java specification:
Initialization of a class consists of
executing its static initializers and
the initializers for static fields
declared in the class. Initialization
of an interface consists of executing
the initializers for fields declared
in the interface.
Yes, according to the Java Language Specification static code is always executed in the same order on all (compliant) JVM's.
8.7 Static Initializers
The static initializers and class variable initializers are executed in textual order.
Dittos to other posters, but let me add that a static initializer that depends on the state of other classes like in your example seems to me to make for very fragile and difficult-to-maintain code. I'll use static intializers to populate internal class data -- to fill up an array with default values or that sort of thing. But I don't think I've ever had one peek at the data in another class. Technically legal, and maybe there are odd cases where it's a good idea, but yuck.
Yes, I believe that would be the point by definition.
Static Block will always run first not just the first time... Before executing any code block, JVM execute the static code block first, and then only it run the code block as it has been designed...