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.
Related
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:
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.
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.
This question already has answers here:
In what order do static/instance initializer blocks in Java run?
(8 answers)
Closed 9 years ago.
I'm trying to discover the order in which initialization occurs, or rather the reason behind why initialization occurs in this order. Given the code:
public class Main {
{
System.out.printf("NON-STATIC BLOCK\n");
}
static{
System.out.printf("STATIC BLOCK\n");
}
public static Main m = new Main();
public Main(){
System.out.printf("MAIN CONSTRUCTOR\n");
}
public static void main(String... args) {
//Main m = new Main();
System.out.printf("MAIN METHOD\n");
}
}
Output:
STATIC BLOCK
NON-STATIC BLOCK
MAIN CONSTRUCTOR
MAIN METHOD
However, moving m's declaration before the initialization block produces:
NON-STATIC BLOCK
MAIN CONSTRUCTOR
STATIC BLOCK
MAIN METHOD
and I have absolutely no idea why it occurs in this order. Furthermore, if I eliminate the static keyword in the declaration of m, neither the init block nor the constructor fire. Can anyone help me out with this?
I think you're just missing section 12.4.2 of the JLS, which includes:
Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
The "in textual order" part is the important bit.
If you change m from being static variable to an instance variable, then the field won't be initialized by class initialization - it'll only be initialized by instance initialization (i.e. when an instance is constructed). At the moment, that'll cause a stack overflow - creating one instance requires creating another instance, which requires creating another instance, etc.
EDIT: Similarly section 12.5 specifies instance initialization, including these steps:
Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. If execution of any of these initializers results in an exception, then no further initializers are processed and this procedure completes abruptly with that same exception. Otherwise, continue with step 5.
Execute the rest of the body of this constructor. If that execution completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, this procedure completes normally.
So that's why you're seeing "NON-STATIC BLOCK" before "MAIN CONSTRUCTOR".
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is Double Brace initialization in Java?
While looking at some legacy code I came across something very confusing:
public class A{
public A(){
//constructor
}
public void foo(){
//implementation ommitted
}
}
public class B{
public void bar(){
A a = new A(){
{ foo(); }
}
}
}
After running the code in debug mode I found that the anonymous block { foo() } is called after the constructor A() is called. How is the above functionally different from doing:
public void bar(){
A a = new A();
a.foo();
}
? I would think they are functionally equivalent, and would think the latter way is the better/cleaner way of writing code.
{ foo(); }
is called instance initializer.
why?
As per java tutorial
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
"Instance initializers are a useful alternative to instance variable initializers whenever: (1) initializer code must catch exceptions, or (2) perform fancy calculations that can't be expressed with an instance variable initializer. You could, of course, always write such code in constructors. But in a class that had multiple constructors, you would have to repeat the code in each constructor. With an instance initializer, you can just write the code once, and it will be executed no matter what constructor is used to create the object. Instance initializers are also useful in anonymous inner classes, which can't declare any constructors at all."Source
This was also quoted in this answer.
Unless the runtime class of the object is accessed (by means of calling getClass()) and needs to be different from A for some reason (for instance because it serves as super type token), there is indeed no difference, and simply invoking foo() after construction would indeed be the more common idiom.