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
This question already has answers here:
What is an initialization block?
(10 answers)
Closed 5 years ago.
What is the need of initialization block in Java? How does it help in coding?
Do we just add a set of curly braces extra in our code?
Eg:
public class GFG
{
// Initializer block starts..
{
// This code is executed before every constructor.
System.out.println("Common part of constructors invoked !!");
}
// Initializer block ends
public GFG()
{
System.out.println("Default Constructor invoked");
}
public static void main(String arr[])
{
GFG obj1;
obj1 = new GFG();
}
}
There are two types of initializer blocks.
You have a static initializer block which runs on creation of class. Its syntax is
static {
//stuff here
}
The other one is instance initialization block which runs when you instantiate an object. Its syntax is
{
//stuff here
}
If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. 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.
This is to answer your question on when you should use them. You basically use them to initialize a variable with some kind of specific logic. It's from the official Oracle documentation.
Is it possible to check that class has static block ?
For example to check that class has static fields reflection can be used by calling clazz.getDeclaredFields() and then iterate it to found static field.
With static methods the same - clazz.getDeclaredMethods()
But getDeclaredMethods doesn't return methods for init and clinit. Is there are any other way to check that class have static initialization block?
There is no way to test for the presence of static initializers, as that information isn’t even available at byte code level. In a class file, there might be a single initialization method, <clinit>, whose existence might be caused by the existence of static field initializers, static initialization blocks, or the mere presence of an assert statement somewhere in that class, to name some possible reasons. Of course, there could be more than one reason, including reasons not mentioned here. Since that bytecode artifact has no language semantic, there is no Reflection method to test for its presence.
However, if a class has no mutable static fields, there is nothing to manipulate by a static initializer, that could make a difference between a “fresh class” and a class state that is not “fresh”. While initializers could have side effects, these could not alter the class, if there are no static fields to change. But if the initializer is manipulating the state of other classes, you get initialization order dependency issues anyway.
Also, the idea to reload a single class because of fulfilling certain criteria, without reloading the others, which interact with that class, doesn’t work at all, as these old classes will also stay linked as they are, not using the newly loaded class version.
The simplest (if not only) solution is to reload all classes of a particular class loader, to get a fresh new state. Trying to selectively reload some classes only, is just an optimization attempt, but there is no point in trying to optimize a testing environment…
Use below code.
public static boolean check(Class<?> cls) {
try {
Method method = ObjectStreamClass.class.getDeclaredMethod("hasStaticInitializer", Class.class);
method.setAccessible(true);
return (boolean) method.invoke(null, cls);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
}
// trivial
throw new RuntimeException();
}
static class Test { static { } }
static class Test2 { }
public static void main(String[] args) {
assert check(Test.class);
assert !check(Test2.class);
}
You can not do what you are wanting to do because that is not how things work. Even if you could it is a terrible idea and means you have a fundamental flaw in your design of your system.
Static Initialization Blocks
A static initialization block is a normal block of code enclosed in
braces, { }, and preceded by the static keyword. Here is an example:
static {
// whatever code is needed for initialization goes here
}
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.
There is an alternative to static blocks — you can write a private
static method:
class Whatever {
public static varType myVar = initializeClassVariable();
private static varType initializeClassVariable() {
// initialization code goes here
}
}
The advantage of private static methods is that they can be reused
later if you need to reinitialize the class variable.
I'm working on a basic webapp tutorial using jqGrid, a plugin for jquery that just presents data in a grid. I'm following this tutorial and I don't understand what's happening on the lines following the declaration of my data Map.
public class Data {
private static Map<String, List<Person>> data = new HashMap<String, List<Person>>();
static
{
populateBS217RHData();
poplateBS18QTData();
}
public List<Person> getData(String postcode)
{
return data.get(postcode.toUpperCase());
}
private static void populateBS217RHData()
{
// do thing
}
private static void poplateBS18QTData()
{
// do other thing
}
}
I understand the purpose of the static keyword is to make methods / properties available without instantiating the class, but I don't really "get" what it's doing in this context.
I have lots of experience with .NET but next to none with Java so I'm not really sure what's going on here. Is there a special name for this syntax / use?
It is a static initializer, and as per the JLS, it is ...
... executed when the class is initialized.
They are usually used to initialize static fields (known as class variables) from a non-trivial multi-line expression. This is simply as a single static function call or variable assignment can be done on the same line as the field declaration resulting in far fewer lines of code.
The Java Tutorials > Initializing Fields also talks about it:
A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword
A single class can have one or more of these. They are called in "left to right" order (i.e. the order of declaration in the class body).
You can also declare "instance initialization" blocks, which are similar, but not preceded by the static keyword - they run every time a class is instantiated.
Initialization blocks can be tricky if you declare fields after the block. There are rules about reading and writing to fields in initialization blocks which depend on declaration order of the field and block.
It is, frankly, simpler to declare fields first, and if you must use an initialization block then do that afterwards.
static
{
populateBS217RHData();
poplateBS18QTData();
}
This is a static block
Static blocks are also called Static initialization blocks . A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Static blocks are executed when JVM loads the class.
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 executable statements in the static block, JVM will
automatically execute these statements when the class is loaded into
JVM.
static
{
populateBS217RHData();
poplateBS18QTData();
}
Here this is static initialization block . The code placed between the curly braces of static initialization block will be executed only once for the residing class even though the class object is created multiple times.
In java there is a another initialization block which is called - instance initialization block where the static keyword is not present. The instance initialization block will be executed for the each object/instance of the class. It is like other instance member of a class.
This question already has answers here:
Use of Initializers vs Constructors in Java
(10 answers)
Closed 8 years ago.
I am studying for an exam about Java. While I was studying, I have encountered syntaxes in java which are unfamiliar to me. Such as a curly braces({}) unside a class body without a name, some has a static keyword. I have found out that they are called "Initializers". Can anyone help me point out key differences among them and how they differ from a Constructor. Thanks
The main difference between them is the order they are executed. To illustrate, I will explain them with an example:
public class SomeTest {
static int staticVariable;
int instanceVariable;
// Static initialization block:
static {
System.out.println("Static initialization.");
staticVariable = 5;
}
// Instance initialization block:
{
System.out.println("Instance initialization.");
instanceVariable = 10;
}
// Constructor
public SomeTest() {
System.out.println("Constructor executed.");
}
public static void main(String[] args) {
new SomeTest();
new SomeTest();
}
}
The output will be:
Static initalization.
Instance initialization.
Constructor executed.
Instance initialization.
Constructor executed.
Briefly talking:
Static initialization blocks run once the class is loaded by the JVM.
Instance initialization blocks run before the constructor each time you instantiate an object.
Constructor (obviously) run each time you instantiate an object.
A Constructor is called once when a new instance of a class is created. The values initialized in the constructor belong to the scope of the instance. Each Instance may have a different value for the same field initialized in the Constructor.
Static Initializers are useful for executing setup code in Static Classes and filling out data structures in Enums. They are called once, in order from top to bottom when the Class is loaded into the JVM and the data exists within the scope of the Class or Enum. All references to the Class will return the same value for fields initialized in the Static Initializers
Unnamed Curly Braces are Anonymous code blocks that scope reference names. If you create a reference inside the blocks, you can not get the value of that reference outside the block. If you find yourself needing them it's a sign you need to refactor your code into more methods.
This is the kind of thing you really need to look in your textbook to get an answer. However I can give you some pointers. Its been some years since I programmed Java, so any information I gave you is general.
Generally a nameless block with curly braces is an anonymous function. Static initializers initialize data that is global to all instances of that class, and runs once the first time the class is referenced. You need to be careful about how you use static properties or methods. With this information you can find accurate details in your text books.
I ran into an interesting thing:
static {
System.out.println(test); // error cannot reference a field before it is defined
System.out.println(cheat()); // OK!
}
private static boolean cheat() {
return test;
}
private static boolean test = true;
public static void main(String args[]) {}
The first way is wrong and both your compiler and IDE will tell you it's wrong. In the second case, cheating is OK, but it actually defaults the field test to false. Using Sun JDK 6.
This is defined in the JLS 8.3.2.3. In particular:
The declaration of a member needs to appear textually before it is used [...] if the usage occurs in a [...] static initializer of C.
When you call cheat() you go around that rule. This is actually the 5th example in the list of the examples of that section.
Note that cheat() will return false in the static initializer block because test has not been initialised yet.
Because class loading works in this order:
Loads Class definition (methods, signatures)
Allocates the memory for the static variable references (for test) - does not initialize yet
Executes the static initializers (for variables) and the static blocks - in order they are defined
So, by the time you have reachstatic block, you have the method definition ready, but don't have the variable ready. With cheat() you're actually reading an uninitialized value.
This is the generic steps by which class loading happens.
Loading - Load the class to memory
Verification - checks binary representation of a class e is correct
Preparation - create the static fields for the class and initialize those fields to their standard default values.
Initializing - will invoke static initializers and initializers for static fields
After preparation, your test will be false.Then before you assign static variable to true, your static block will execute.That is why you are getting false.
Try making your static variable final.In that case,you will be getting true.This is because your compiler itself will embed the value in bytecode(since the field is final) as part of optimisation