Static Initializers And Static Methods In Java - java

Does calling a static method on a class in Java trigger the static initalization blocks to get executed?
Empirically, I'd say no. I have something like this:
public class Country {
static {
init();
List<Country> countries = DataSource.read(...); // get from a DAO
addCountries(countries);
}
private static Map<String, Country> allCountries = null;
private static void init() {
allCountries = new HashMap<String, Country>();
}
private static void addCountries(List<Country> countries) {
for (Country country : countries) {
if ((country.getISO() != null) && (country.getISO().length() > 0)) {
allCountries.put(country.getISO(), country);
}
}
}
public static Country findByISO(String cc) {
return allCountries.get(cc);
}
}
In the code using the class, I do something like:
Country country = Country.findByISO("RO");
The problem is that I get a NullPointerException because the map (allCountries) is not initialized. If I set up breakpoints in the static block I can see the map getting populated correctly, but it's as if the static method has no knowledge of the initializer being executed.
Can anyone explain this behavior?
Update: I've added more detail to the code. It's still not 1:1 (there are several maps in there and more logic), but I've explicitly looked at the declarations/references of allCountries and they are as listed above.
You can see the full initialization code here.
Update #2: I tried to simplify the code as much as possible and wrote it down on the fly. The actual code had the static variable declaration after the initializer. That caused it to reset the reference, as Jon pointed out in the answer below.
I modified the code in my post to reflect this, so it's clearer for people who find the question. Sorry about the confusion everyone. I was just trying to make everyone's life easier :).
Thanks for your answers!

Does calling a static method on a class in Java trigger the static initalization blocks to get executed?
Empirically, I'd say no.
You're wrong.
From the JLS section 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.
Section 12.4.1 of the JLS states:
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 (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.
This is easily shown:
class Foo {
static int x = 0;
static {
x = 10;
}
static int getX() {
return x;
}
}
public class Test {
public static void main(String[] args) throws Exception {
System.out.println(Foo.getX()); // Prints 10
}
}
Your problem is in some part of the code that you didn't show us. My guess is that you're actually declaring a local variable, like this:
static {
Map<String, Country> allCountries = new HashMap<String, Country>();
// Add entries to the map
}
That hides the static variable, leaving the static variable null. If this is the case, just change it to an assignment instead of a declaration:
static {
allCountries = new HashMap<String, Country>();
// Add entries to the map
}
EDIT: One point worth noting - although you've got init() as the very first line of your static initializer, if you're actually doing anything else before then (possibly in other variable initializers) which calls out to another class, and that class calls back into your Country class, then that code will be executed while allCountries is still null.
EDIT: Okay, now we can see your real code, I've found the problem. Your post code has this:
private static Map<String, Country> allCountries;
static {
...
}
But your real code has this:
static {
...
}
private static Collection<Country> allCountries = null;
There are two important differences here:
The variable declaration occurs after the static initializer block
The variable declaration includes an explicit assignment to null
The combination of those is messing you up: the variable initializers aren't all run before the static initializer - initialization occurs in textual order.
So you're populating the collection... and then setting the reference to null.
Section 12.4.2 of the JLS guarantees it in step 9 of the initialization:
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.
Demonstration code:
class Foo {
private static String before = "before";
static {
before = "in init";
after = "in init";
leftDefault = "in init";
}
private static String after = "after";
private static String leftDefault;
static void dump() {
System.out.println("before = " + before);
System.out.println("after = " + after);
System.out.println("leftDefault = " + leftDefault);
}
}
public class Test {
public static void main(String[] args) throws Exception {
Foo.dump();
}
}
Output:
before = in init
after = after
leftDefault = in init
So the solution is either to get rid of the explicit assignment to null, or to move the declarations (and therefore initializers) to before the static initializer, or (my preference) both.

The static initializer will get called when the class is loaded, which is normally when it is first 'mentioned'. So calling a static method would indeed trigger the initializer if this is the first time that the class gets referenced.
Are you sure the null pointer exception is from the allcountries.get(), and not from a null Country returned by get()? In other words, are you certain which object is null?

Theoretically, static block should get executed by the time classloader loads the class.
Country country = Country.findByISO("RO");
^
In your code, it is initialized the first time you mention the class Country (probably the line above).
I ran this:
public class Country {
private static Map<String, Country> allCountries;
static {
allCountries = new HashMap<String, Country>();
allCountries.put("RO", new Country());
}
public static Country findByISO(String cc) {
return allCountries.get(cc);
}
}
with this:
public class Start
{
public static void main(String[] args){
Country country = Country.findByISO("RO");
System.out.println(country);
}
}
and everything worked correctly. Can you post the stack trace of the error?
I would say that the problem lies in the fact that the static block is declared before the actual field.

Do you have allCountries = new HashMap(); in your static initializer block? The static initializer block is actually called upon class initialization.

Related

Static Initialization in Java?

I was trying to execute the following code:
public class StaticTest {
private static List<String> dat1;
{
dat1 = new ArrayList<>();
}
private StaticTest(){
System.out.println(dat1.contains("a")); //Marked Line 2: this one is not throwing
}
public static void main(String[] args) {
System.out.println(dat1.contains("a")); //Marked Line 1: This line throws null pointer
new StaticTest();
}
}
I tried to execute the above code, I got Null pointer exception at Marked Line 1. But when I commented Marked Line 1 I got the output.
Why am I getting the exception in first case and not in second ?
When I use private static List<String> dat1= new ArrayList<>();, no exception is thrown.
Simple:
System.out.println(dat1.contains("a"));
runs a constructor (because it is inside the constructor!).
And part of running the constructor is: to run all non-static initializer blocks of a class.
Whereas:
public static void main(String[] args) {
System.out.println(dat1.contains("a")); //Marked Line 1: This line
does only run your static initializers - but no constructor code (it does - but after that line).
So your problem is that this initializer block:
{
dat1 = new ArrayList<>();
}
isn't static!
In other words: your problem is caused by mixing static/non-static in very unhealthy ways. If a field is static, make sure that a static init code will initialize it.
Btw: the reasonable solution is to simply do:
private final static List<String> data = new ArrayList<>();
This makes sure that the list is initialized as soon as possible; and then compiler will even tell you when you forgot to initialize it.
This code
{
dat1 = new ArrayList<>();
}
This constructor block. Which will be executed every constructor after super() , so it will not run on Mark1 yet.
If you have code like this, it will be executed when class is loaded.
static {
dat1 = new ArrayList<>();
}
more detail here
http://www.jusfortechies.com/java/core-java/static-blocks.php
Hi #kajal please refer to the correct code below:-
public class StaticTest {
private static List<String> dat1;
static
{
dat1 = new ArrayList<String>();
}
private StaticTest(){
System.out.println(dat1.contains("a")); //Marked Line 2: this one is not throwing
}
public static void main(String[] args) {
System.out.println(dat1.contains("a")); //Marked Line 1: This line throws null pointer
new StaticTest();
}
}
Instance block is executes when you create a instance of that class.
Question why you are getting the NullPointerException :-
Please find the below flow of the StaticTest class execution :-
First all the import class will load like :-
Object class 2.java.lang Package Class 3.java.util.ArrayList Class.
The compiler goes through the StaticTest Class and allocate the Memory for the all the Static Members in your case it is dat1.
Now the javac compiler searches for the Static block for the execution. in your case their is no Static block.
Now the compiler executes the main method and executes the System.out.println(dat1.contains("a")); is called as null.contains("a"); which trhows the execption but as i said the Instance block is executes when you create a instance of that class. so dat1 is initialized when you create object new StaticTest();
Your code:
{
dat1 = new ArrayList<>();
}
Is a non-static initializer. This is called, when you are calling the constructor with: new StaticTest(). After that dat1 will be initialized.
You can change your code to static initializing by preceding it with the static keyword:
static
{
dat1 = new ArrayList<>();
}
Then it will work for both cases.

The static field should be accessed in a static way

I have different Exception category Enum as below
public enum GSBBCacheCategory {
SEARCH(9001),
UPDATE_PERSECURITY(9002),
CROSS_REFERENCING_PERSECURITY(9003),
METADATA_SEARCH(9004),
REMOVEALL(9005),
UPDATE_BACKOFFICE(9002);
private int exceptionCode;
GSBBCacheCategory(int exceptionCode)
{
this.exceptionCode = exceptionCode;
}
public int getExceptionCode()
{
return exceptionCode;
}
}
public enum GSBBEncryptionCategory {
.
.
.
}
I want to provide one place to access these Enum in client code. Presently I achieved this as below
public class GSBBExceptionCodes
{
public static GSBBDecryptionCategory decryptionCategory;
public static GSBBCacheCategory cacheCategory;
}
Now to access exception code I have do something like below
public static void main(String[] args) {
System.out.println(GSBBExceptionCodes.decryptionCategory.ERRORCODE_DECRYPTION_FAILURE);
System.out.println(GSBBExceptionCodes.cacheCategory.UPDATE_PERSECURITY);
}
Which says “The static field GSBBDecryptionCategory.ERRORCODE_DECRYPTION_FAILURE should be accessed in a static way”
Is it possible to achieve above without any warning?
There are two ways to reference a static member (either a field or a method). One is WhateverClass.theField, and the other is someInstance.theField where someInstance has a compile-time type of WhateverClass. The former is much clearer, and so your IDE is helpfully telling you to use it instead of the latter.
The reason it's better is that referencing a static member by an instance makes it look like the method has something to do with that instance, which it doesn't. Here's a real-life example:
Thread myThread = getMyThread();
myThread.start();
myThread.sleep(5000);
At first blush, it looks like you're asking myThread to sleep for 5 seconds (5000 milliseconds), but that's not what you're doing at all. You're asking the current thread to sleep, because that last line is exactly the same as invoking Thread.sleep(5000). That second example is much more clearly a static method.
Or, here's another example. Let's say your static fields were mutable.
public class Foo {
public static int value = 1;
}
(This public static mutable field is a bad idea for other reasons, but simplifies the example). Now let's say you do:
Foo one = new Foo();
Foo two = new Foo();
one.value = 2;
two.value = 3;
System.out.println(one.value);
System.out.println(two.value);
Kinda looks like that should print "2" and then "3", right? But no -- it'll print "3", "3" because both assignments to .value are in fact to the same, static field. It's just an optical illusion that the one or two instances have anything to do with anything.
Imho, the ability to reference static members from instances is a misfeature. But it's there, so you should avoid it. Which is what the compiler is trying to suggest you do.
Try this :
public static void main(String[] args) {
System.out.println(GSBBDecryptionCategory.ERRORCODE_DECRYPTION_FAILURE);
System.out.println(GSBBCacheCategory.UPDATE_PERSECURITY);
}
You are now accessing the field in a static way which should remove the warning.
It sounds like instead of having these as public static fields, they should be inner classes:
public class GSBBExceptionCodes {
public enum GSBBCacheCategory {
...
}
}

Static block is never run

I have a utility class that looks like this:
public final class MyUtils {
public static final List<String> MY_VALUES = new ArrayList<String>();
{
MY_VALUES.add("foo");
MY_VALUES.add("bar");
}
}
I call this from another class just like this:
MyUtils.MY_VALUES
If I do so, the list is empty and if I debug I see the static block is never run.
As I understand from the answers to When does static class initialization happen? and How to force a class to be initialised? the block should run when a static field of the class is assigned, which I do right away. I also tried making the variable non-final to fulfill the condition "a non-constant static field is used".
I could use an init method as also sugested in the two other questions and als in Why doesn't my static block of code execute? but I would still like to understand why it isn't working in the first place although I seem to have fulfilled the conditions from the language specification.
You have to add the static keyword in front of your block in order to make it static:
public final class MyUtils {
public static final List<String> MY_VALUES = new ArrayList<String>();
static {
MY_VALUES.add("foo");
MY_VALUES.add("bar");
}
}
A initialization block gets called everytime the class is constructed.
A static initialization block gets called only once at the start of your program.

Regarding static and final variable effect on class

If you execute this program you will get only the i value but not SIB, my question is when class loading into the memory SIB should execute and should give ooutput, but here I am getting only the i value? Then keep one method in class test then call that method from another class then you will get output of SIB, i method ( keep method also as static final)
class Test
{
static final int i =3;
static
{
System.out.println("SIB");
}
{
System.out.println("IIB");
}
}
class A1
{
public static void main(String[] args)
{
System.out.println(Test.i);
}
}
A static final variable is a compile-time constant and its value is copied into the other class referencing it. Therefore your class Test won't load and no initializers will be executed. When the variable is only static, then the class must be loaded to read the current value and your SIB block will be executed. The IIB block will be executed only when you instantiate Test with new Test().

Static Initialization Blocks

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. For example we declare a field as static (without a value assignment). And then write several lines of the code which generate and assign a value to the above declared static field.
Why do we need this lines in a special block like: static {...}?
The non-static block:
{
// Do Something...
}
Gets called every time an instance of the class is constructed. The static block only gets called once, when the class itself is initialized, no matter how many objects of that type you create.
Example:
public class Test {
static{
System.out.println("Static");
}
{
System.out.println("Non-static block");
}
public static void main(String[] args) {
Test t = new Test();
Test t2 = new Test();
}
}
This prints:
Static
Non-static block
Non-static block
If they weren't in a static initialization block, where would they be? How would you declare a variable which was only meant to be local for the purposes of initialization, and distinguish it from a field? For example, how would you want to write:
public class Foo {
private static final int widgets;
static {
int first = Widgets.getFirstCount();
int second = Widgets.getSecondCount();
// Imagine more complex logic here which really used first/second
widgets = first + second;
}
}
If first and second weren't in a block, they'd look like fields. If they were in a block without static in front of it, that would count as an instance initialization block instead of a static initialization block, so it would be executed once per constructed instance rather than once in total.
Now in this particular case, you could use a static method instead:
public class Foo {
private static final int widgets = getWidgets();
static int getWidgets() {
int first = Widgets.getFirstCount();
int second = Widgets.getSecondCount();
// Imagine more complex logic here which really used first/second
return first + second;
}
}
... but that doesn't work when there are multiple variables you wish to assign within the same block, or none (e.g. if you just want to log something - or maybe initialize a native library).
Here's an example:
private static final HashMap<String, String> MAP = new HashMap<String, String>();
static {
MAP.put("banana", "honey");
MAP.put("peanut butter", "jelly");
MAP.put("rice", "beans");
}
The code in the "static" section(s) will be executed at class load time, before any instances of the class are constructed (and before any static methods are called from elsewhere). That way you can make sure that the class resources are all ready to use.
It's also possible to have non-static initializer blocks. Those act like extensions to the set of constructor methods defined for the class. They look just like static initializer blocks, except the keyword "static" is left off.
It's also useful when you actually don't want to assign the value to anything, such as loading some class only once during runtime.
E.g.
static {
try {
Class.forName("com.example.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError("Cannot load JDBC driver.", e);
}
}
Hey, there's another benefit, you can use it to handle exceptions. Imagine that getStuff() here throws an Exception which really belongs in a catch block:
private static Object stuff = getStuff(); // Won't compile: unhandled exception.
then a static initializer is useful here. You can handle the exception there.
Another example is to do stuff afterwards which can't be done during assigning:
private static Properties config = new Properties();
static {
try {
config.load(Thread.currentThread().getClassLoader().getResourceAsStream("config.properties");
} catch (IOException e) {
throw new ExceptionInInitializerError("Cannot load properties file.", e);
}
}
To come back to the JDBC driver example, any decent JDBC driver itself also makes use of the static initializer to register itself in the DriverManager. Also see this and this answer.
I would say static block is just syntactic sugar. There is nothing you could do with static block and not with anything else.
To re-use some examples posted here.
This piece of code could be re-written without using static initialiser.
Method #1: With static
private static final HashMap<String, String> MAP;
static {
MAP.put("banana", "honey");
MAP.put("peanut butter", "jelly");
MAP.put("rice", "beans");
}
Method #2: Without static
private static final HashMap<String, String> MAP = getMap();
private static HashMap<String, String> getMap()
{
HashMap<String, String> ret = new HashMap<>();
ret.put("banana", "honey");
ret.put("peanut butter", "jelly");
ret.put("rice", "beans");
return ret;
}
There are a few actual reasons that it is required to exist:
initializing static final members whose initialization might throw an exception
initializing static final members with calculated values
People tend to use static {} blocks as a convenient way to initialize things that the class depends on within the runtime as well - such as ensuring that particular class is loaded (e.g., JDBC drivers). That can be done in other ways; however, the two things that I mention above can only be done with a construct like the static {} block.
You can execute bits of code once for a class before an object is constructed in the static blocks.
E.g.
class A {
static int var1 = 6;
static int var2 = 9;
static int var3;
static long var4;
static Date date1;
static Date date2;
static {
date1 = new Date();
for(int cnt = 0; cnt < var2; cnt++){
var3 += var1;
}
System.out.println("End first static init: " + new Date());
}
}
It is a common misconception to think that a static block has only access to static fields. For this I would like to show below piece of code that I quite often use in real-life projects (copied partially from another answer in a slightly different context):
public enum Language {
ENGLISH("eng", "en", "en_GB", "en_US"),
GERMAN("de", "ge"),
CROATIAN("hr", "cro"),
RUSSIAN("ru"),
BELGIAN("be",";-)");
static final private Map<String,Language> ALIAS_MAP = new HashMap<String,Language>();
static {
for (Language l:Language.values()) {
// ignoring the case by normalizing to uppercase
ALIAS_MAP.put(l.name().toUpperCase(),l);
for (String alias:l.aliases) ALIAS_MAP.put(alias.toUpperCase(),l);
}
}
static public boolean has(String value) {
// ignoring the case by normalizing to uppercase
return ALIAS_MAP.containsKey(value.toUpper());
}
static public Language fromString(String value) {
if (value == null) throw new NullPointerException("alias null");
Language l = ALIAS_MAP.get(value);
if (l == null) throw new IllegalArgumentException("Not an alias: "+value);
return l;
}
private List<String> aliases;
private Language(String... aliases) {
this.aliases = Arrays.asList(aliases);
}
}
Here the initializer is used to maintain an index (ALIAS_MAP), to map a set of aliases back to the original enum type. It is intended as an extension to the built-in valueOf method provided by the Enum itself.
As you can see, the static initializer accesses even the private field aliases. It is important to understand that the static block already has access to the Enum value instances (e.g. ENGLISH). This is because the order of initialization and execution in the case of Enum types, just as if the static private fields have been initialized with instances before the static blocks have been called:
The Enum constants which are implicit static fields. This requires the Enum constructor and instance blocks, and instance initialization to occur first as well.
static block and initialization of static fields in the order of occurrence.
This out-of-order initialization (constructor before static block) is important to note. It also happens when we initialize static fields with the instances similarly to a Singleton (simplifications made):
public class Foo {
static { System.out.println("Static Block 1"); }
public static final Foo FOO = new Foo();
static { System.out.println("Static Block 2"); }
public Foo() { System.out.println("Constructor"); }
static public void main(String p[]) {
System.out.println("In Main");
new Foo();
}
}
What we see is the following output:
Static Block 1
Constructor
Static Block 2
In Main
Constructor
Clear is that the static initialization actually can happen before the constructor, and even after:
Simply accessing Foo in the main method, causes the class to be loaded and the static initialization to start. But as part of the Static initialization we again call the constructors for the static fields, after which it resumes static initialization, and completes the constructor called from within the main method. Rather complex situation for which I hope that in normal coding we would not have to deal with.
For more info on this see the book "Effective Java".
So you have a static field (it's also called "class variable" because it belongs to the class rather than to an instance of the class; in other words it's associated with the class rather than with any object) and you want to initialize it. So if you do NOT want to create an instance of this class and you want to manipulate this static field, you can do it in three ways:
1- Just initialize it when you declare the variable:
static int x = 3;
2- Have a static initializing block:
static int x;
static {
x=3;
}
3- Have a class method (static method) that accesses the class variable and initializes it:
this is the alternative to the above static block; you can write a private static method:
public static int x=initializeX();
private static int initializeX(){
return 3;
}
Now why would you use static initializing block instead of static methods?
It's really up to what you need in your program. But you have to know that static initializing block is called once and the only advantage of the class method is that they can be reused later if you need to reinitialize the class variable.
let's say you have a complex array in your program. You initialize it (using for loop for example) and then the values in this array will change throughout the program but then at some point you want to reinitialize it (go back to the initial value). In this case you can call the private static method. In case you do not need in your program to reinitialize the values, you can just use the static block and no need for a static method since you're not gonna use it later in the program.
Note: the static blocks are called in the order they appear in the code.
Example 1:
class A{
public static int a =f();
// this is a static method
private static int f(){
return 3;
}
// this is a static block
static {
a=5;
}
public static void main(String args[]) {
// As I mentioned, you do not need to create an instance of the class to use the class variable
System.out.print(A.a); // this will print 5
}
}
Example 2:
class A{
static {
a=5;
}
public static int a =f();
private static int f(){
return 3;
}
public static void main(String args[]) {
System.out.print(A.a); // this will print 3
}
}
If your static variables need to be set at runtime then a static {...} block is very helpful.
For example, if you need to set the static member to a value which is stored in a config file or database.
Also useful when you want to add values to a static Map member as you can't add these values in the initial member declaration.
It is important to understand that classes are instantiated from java.class.Class during runtime. That is when static blocks are executed, which allows you to execute code without instantiating a class:
public class Main {
private static int myInt;
static {
myInt = 1;
System.out.println("myInt is 1");
}
// needed only to run this class
public static void main(String[] args) {
}
}
The result is myInt is 1 printed to the console.
As supplementary, like #Pointy said
The code in the "static" section(s) will be executed at class load
time, before any instances of the class are constructed (and before
any static methods are called from elsewhere).
It's supposed to add System.loadLibrary("I_am_native_library") into static block.
static{
System.loadLibrary("I_am_a_library");
}
It will guarantee no native method be called before the related library is loaded into memory.
According to loadLibrary from oracle:
If this method is called more than once with the same library name,
the second and subsequent calls are ignored.
So quite unexpectedly, putting System.loadLibrary is not used to avoid library be loaded multi-times.
static block is used for any technology to initialize static data member in dynamic way,or we can say for the dynamic initialization of static data member static block is being used..Because for non static data member initialization we have constructor but we do not have any place where we can dynamically initialize static data member
Eg:-class Solution{
// static int x=10;
static int x;
static{
try{
x=System.out.println();
}
catch(Exception e){}
}
}
class Solution1{
public static void main(String a[]){
System.out.println(Solution.x);
}
}
Now my static int x will initialize dynamically ..Bcoz when compiler will go to Solution.x it will load Solution Class and static block load at class loading time..So we can able to dynamically initialize that static data member..
}
static int B,H;
static boolean flag = true;
static{
Scanner scan = new Scanner(System.in);
B = scan.nextInt();
scan.nextLine();
H = scan.nextInt();
if(B < 0 || H < 0){
flag = false;
System.out.println("java.lang.Exception: Breadth and height must be positive");
}
}

Categories

Resources