Hash set with static initilazation parameters - java

I was going through some classes in which I have found one hashset implementation like this
public static HashSet<String> set = new HashSet<String>();
static{
set.add("abc");
set.add("def");
set.add("eghi");
}
In static block, I just want to know what this pattern known as,static initialization.Does it mean initially when the jvm is up we have the set with initialized values.
Please advise.

StaticInitializer:
static Block
If you see JLS-8.7
A static initializer declared in a class is executed when the class is initialized (§12.4.2). Together with any field initializers for class variables (§8.3.2), static initializers may be used to initialize the class variables of the class.
Note :
Use of class variables whose declarations appear textually after the use is sometimes restricted, even though these class variables are in scope. See §8.3.2.3 for the precise rules governing forward reference to class variables.

The static block only gets called once at the time of class loading, no matter how many objects of that type you create.
Static block will have no access to the non static instance variables or methods.
You can use static block to handle exceptions during initialization.
The fact that static blocks are executed during the loading of class and even before the constructor is called, this feature can be used in singleton pattern.

Yes this is static initialization block.
About Static initialization block:
A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword.
When it will load:
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.

Related

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.

What really happens when loading a class in java?

I'm confused with the process of loading a class. What is the order in which members of a class are executed?
See the following:
class L {
static void fr(){
a=1;
b=3;
a=b;
}
static{
a=3;
b=1;
a=b;// here the problem:cannot reference a field before it is defined
}
static int a;
static int b;
public static void main(String args[]) {
}
}
Whenever I move the declarations of a and b to the top before the static block, compilation works fine. So I need to understand how this stuff works to resolve the problem above.
In Java, it is illegal to refer to a class variable before it is declared, if it's not an expression initializing it. Java will execute initializers in a class in textual order.
Section 12.4.2 of the JLS states:
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.
Section 8.3.3 of the JLS states:
Use of class variables whose declarations appear textually after the use is sometimes restricted, even though these class variables are in scope (§6.3). Specifically, it is a compile-time error if all of the following are true:
The declaration of a class variable in a class or interface C appears textually after a use of the class variable;
The use is a simple name in either a class variable initializer of C or a static initializer of C;
The use is not on the left hand side of an assignment;
C is the innermost class or interface enclosing the use.
All of these are true. The declaration appears after the use in a=b;. It's in a static initializer. It's not on the left side of an assignment, and it's the innermost (only) class.
The simplest way to get this to compile is to move the declarations above the static initializer in the source code.
Interestingly, replacing a=b; with a=L.b; will also get this to compile, because the reference to b is no longer "simple".
First the class is loaded and the overall structure verified. Then the methods are verified and external linkages checked. Then the static init is performed. This is when the static block is executed.
But your problem is apparently with the compiler, not class loading. You need to move your static variable declarations up above the static block. Has nothing at all to do with class loading.
Hint: Learn the difference between a compile-time error and a run-time exception. What you were seeing was an error message from the compiler. (And you're lucky you didn't catch bloody hell and close votes for not including the EXACT error message in your question.)

Static Initializers vs Instance Initializers vs Constructors [duplicate]

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.

Why can you access static field before it is defined through a method in Java?

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

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