Static Initializers vs Instance Initializers vs Constructors [duplicate] - java

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.

Related

Lone braces inside a class?

I couldn't find anything about this online, because I didn't know what to search for, but Java doesn't mark this code as having an error:
public class Test {
// ...
{
int test;
}
// ...
}
Does this serve any purpose in Java? If so, what?
This is called an instance initializer (JLS section 8.6)
When creating an object the instance initializer is run after super constructors but before the called constructor of the class they are defined in. See JLS 12.5 Creation of New Class Instances. Specifically, instance initializers are evaluated in step 4 of the object creation process. The key point is that instance initiailzers always get called no matter what constructor is used to instantiate the object.
There are also static initializers which are similar but marked with the static keyword.
public class Test {
static {
// Do something interesting on class load.
}
}
In my experience static intiailzers are more common as you can use them to setup complex class state (like linking JNI libraries) when the class is loaded.

What is the use of static doing in this code sample?

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.

Statement surrounded by static { ... statement; } why, what for? [duplicate]

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.

static fields in Java [duplicate]

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 8 years ago.
I have learned that fields are like global variables which can be accessed by the methods inside the same class. I have done it this way before and never had a problem. I have now a class where I have some fields but the methods cannot access them without having to make them static fields. I get the error "cannot make static reference to non-static..."
I thought static was to access fields on other classes without having to create an object reference to the class. The only difference I have with this code is that I have a single class and my main() method within this class. Does having main() inside this class make a difference?
A static member only exists once for the class itself as opposed to regular class members which are distinct per instance of your class.
Having a main() method does not impact the behavior of your static members, however static methods can only access static members while non-static methods can access both static and non-static class members.
You can't access non static instance inside static method. I think you are trying to access class variable inside main method directly, i.e.
class A
{
int x;
main() method
{
x;//Not accessible here,, create instance of class and access it.like
A a=new A();
a.x;
}
}
Static (methods,variables,classes, etc) belongs to Class not to the particular instance of the class. We define as static when the behaviour or state does not depend on any particular instance of the class. For Example "generate a Random Number " it does not depend on the instance, it always generate a number regardless of instance such behaviour can be defined as static.
Regarding the error, posting you code will helpful to give better solution.
Refer the below link to know more about Static and non-static
http://javarevisited.blogspot.in/2012/02/why-non-static-variable-cannot-be.html

When are static variables initialized?

I am wondering when static variables are initialized to their default values.
Is it correct that when a class is loaded, static vars are created (allocated),
then static initializers and initializations in declarations are executed?
At what point are the default values are given? This leads to the problem of forward reference.
Also please if you can explain this in reference to the question asked on Why static fields are not initialized in time? and especially the answer given by Kevin Brock on the same site. I can't understand the 3rd point.
From See Java Static Variable Methods:
It is a variable which belongs to the class and not to object(instance)
Static variables are initialized only once , at the start of the execution. These variables will be initialized first, before the initialization of any instance variables
A single copy to be shared by all instances of the class
A static variable can be accessed directly by the class name and doesn’t need any object.
Instance and class (static) variables are automatically initialized to standard default values if you fail to purposely initialize them. Although local variables are not automatically initialized, you cannot compile a program that fails to either initialize a local variable or assign a value to that local variable before it is used.
What the compiler actually does is to internally produce a single class initialization routine that combines all the static variable initializers and all of the static initializer blocks of code, in the order that they appear in the class declaration. This single initialization procedure is run automatically, one time only, when the class is first loaded.
In case of inner classes, they can not have static fields
An inner class is a nested class that is not explicitly or implicitly
declared static.
...
Inner classes may not declare static initializers (§8.7) or member interfaces...
Inner classes may not declare static members, unless they are constant variables...
See JLS 8.1.3 Inner Classes and Enclosing Instances
final fields in Java can be initialized separately from their declaration place this is however can not be applicable to static final fields. See the example below.
final class Demo
{
private final int x;
private static final int z; //must be initialized here.
static
{
z = 10; //It can be initialized here.
}
public Demo(int x)
{
this.x=x; //This is possible.
//z=15; compiler-error - can not assign a value to a final variable z
}
}
This is because there is just one copy of the static variables associated with the type, rather than one associated with each instance of the type as with instance variables and if we try to initialize z of type static final within the constructor, it will attempt to reinitialize the static final type field z because the constructor is run on each instantiation of the class that must not occur to static final fields.
Static fields are initialized when the class is loaded by the class loader. Default values are assigned at this time. This is done in the order than they appear in the source code.
See:
JLS 8.7, Static Initializers
JLS 12.2, Loading of Classes and Interfaces
JLS 12.4, Initialization of Classes and Interfaces
The last in particular provides detailed initialization steps that spell out when static variables are initialized, and in what order (with the caveat that final class variables and interface fields that are compile-time constants are initialized first.)
I'm not sure what your specific question about point 3 (assuming you mean the nested one?) is. The detailed sequence states this would be a recursive initialization request so it will continue initialization.
The order of initialization is:
Static initialization blocks
Instance initialization blocks
Constructors
The details of the process are explained in the JVM specification document.
static variable
It is a variable which belongs to the class and not to object(instance)
Static variables are initialized only once , at the start of the execution(when the Classloader load the class for the first time) .
These variables will be initialized first, before the initialization of any instance variables
A single copy to be shared by all instances of the class
A static variable can be accessed directly by the class name and doesn’t need any object
Starting with the code from the other question:
class MyClass {
private static MyClass myClass = new MyClass();
private static final Object obj = new Object();
public MyClass() {
System.out.println(obj); // will print null once
}
}
A reference to this class will start initialization. First, the class will be marked as initialized. Then the first static field will be initialized with a new instance of MyClass(). Note that myClass is immediately given a reference to a blank MyClass instance. The space is there, but all values are null. The constructor is now executed and prints obj, which is null.
Now back to initializing the class: obj is made a reference to a new real object, and we're done.
If this was set off by a statement like: MyClass mc = new MyClass(); space for a new MyClass instance is again allocated (and the reference placed in mc). The constructor is again executed and again prints obj, which now is not null.
The real trick here is that when you use new, as in WhatEverItIs weii = new WhatEverItIs( p1, p2 ); weii is immediately given a reference to a bit of nulled memory. The JVM will then go on to initialize values and run the constructor. But if you somehow reference weii before it does so--by referencing it from another thread or or by referencing from the class initialization, for instance--you are looking at a class instance filled with null values.
The static variable can be intialize in the following three ways as follow choose any one you like
you can intialize it at the time of declaration
or you can do by making static block eg:
static {
// whatever code is needed for initialization goes here
}
There is an alternative to static blocks — you can write a private static method
class name {
public static varType myVar = initializeVar();
private static varType initializeVar() {
// initialization code goes here
}
}

Categories

Resources