• Home
  • About

Snippet IT

IT News, Programming, Internet and Blogging

  • Programming and Scripting
  • Tips and Tricks
  • Software and Hardware
  • New and Happening
You are here: Home / Programming and Scripting / Java Static Constructor

Java Static Constructor

March 20, 2009 by Sze Hau 1 Comment

Recently I wrote a Java class that maps ISO 3166-1-alpha-2 country code to country name and encountered a static constructor initialization problem. My code is as following:

import java.util.Collection;
import java.util.HashMap;
public class Country {
    private final static HashMap<String,String> countryMap;
    public final static Country XX = new Country("Unknown");
    public final static Country MY = new Country("MY", "Malaysia");
    public final static Country SG = new Country("SG", "Singapore");

    static {
        countryMap = new HashMap<String,String>();
    }

    public static Collection values() {
        return countryMap.values();
    }

    public static Country find(String code) {
        if (countryMap.containsKey(code))
            return countryMap.get(code);
        else
            return XX;
    }

    private String code;
    private String name;

    public Country(String name) {
        this.code = null;
        this.name = name;
    }

    public Country(String code, String name) {
        this.code = code;
        this.name = name;
        countryMap.put(code, this);
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

It seems everything is correct to me. During runtime, the class throw an NullPointerException at line countryMap.put(code, this);. Looks like the static constructor is not called and countryMap is not initialized. What I expected during runtime is that the static constructor will always run first before the others.

When refered to Java documentation at http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html, I still can’t get any hint. After read and re-read the documentation a few times, finally I found the keywords: …The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code…. So for the above code the static variable XX and MY are actually initialize first. Therefore the order of calling the static constructor is important in this case.

I rewrote the code and it runs without any problem. The correct code is as following:

import java.util.Collection;
import java.util.HashMap;
public class Country {
    private final static HashMap<String,String> countryMap;
    static {
        countryMap = new HashMap<String,String>();
    }

    public final static Country XX = new Country("Unknown");
    public final static Country MY = new Country("MY", "Malaysia");
    public final static Country SG = new Country("SG", "Singapore");

    public static Collection values() {
        return countryMap.values();
    }

    public static Country find(String code) {
        if (countryMap.containsKey(code))
            return countryMap.get(code);
        else
            return XX;
    }

    private String code;
    private String name;

    public Country(String name) {
        this.code = null;
        this.name = name;
    }

    public Country(String code, String name) {
        this.code = code;
        this.name = name;
        countryMap.put(code, this);
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Or simply

import java.util.Collection;
import java.util.HashMap;
public class Country {
    private final static HashMap<String,String> countryMap = new HashMap<String,String>();
    public final static Country XX = new Country("Unknown");
    public final static Country MY = new Country("MY", "Malaysia");
    public final static Country SG = new Country("SG", "Singapore");

    public static Collection values() {
        return countryMap.values();
    }

    public static Country find(String code) {
        if (countryMap.containsKey(code))
            return countryMap.get(code);
        else
            return XX;
    }

    private String code;
    private String name;

    public Country(String name) {
        this.code = null;
        this.name = name;
    }

    public Country(String code, String name) {
        this.code = code;
        this.name = name;
        countryMap.put(code, this);
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

More from my site

  • Java: Static Initializer (Static Constructor)Java: Static Initializer (Static Constructor)
  • Java: How To Select Top N Objects From A ListJava: How To Select Top N Objects From A List
  • Java: How To Create A Simple Web Server Using HttpServerJava: How To Create A Simple Web Server Using HttpServer
  • Java: Format Integer Into Fixed Width StringJava: Format Integer Into Fixed Width String
  • Java: Continuously Read Data From FileChannel Without MappedByteBufferJava: Continuously Read Data From FileChannel Without MappedByteBuffer
  • Java: Loading Large Data into JTable or JListJava: Loading Large Data into JTable or JList

Filed Under: Programming and Scripting Tagged With: how to, Java, static constructor

About Sze Hau

Geek. Love programming. Coffee addicted. Married with two children. Working towards financial freedom.

Trackbacks

  1. Blogs Updates for March 2009 - szehau’s weblog says:
    April 2, 2009 at 1:54 am

    […] Java Static Constructor […]

Leave a Reply Cancel reply

Advertisement

  • Facebook
  • Google+
  • Instagram
  • Twitter

Email News Letter

Sign up to receive updates daily and to hear what's going on with us

Software and Hardware

MD5 and SHA1 Checksum Using Windows

July 5, 2017 By Sze Hau Leave a Comment

Blog Network

  • Personal Fincance Personal Finance – Personal Money Tips, Stock Investment, Small Business and Make Money Online
  • szehau's weblog Life, Internet, Software, Gadgets, Programming and Investments

Snippet IT

This is the place where I want to share anything about information technology.

Search

Recent

  • MD5 and SHA1 Checksum Using Windows
  • MD5 and SHA1 Checksum Using Linux
  • Java: Unlimited Strength Jurisdiction Policy
  • WordPress: How To Change Admin Username
  • Linux: How To Compress And Decompress Folders And Files

Tags

Adsense advertisement advertising apache blog blogging tips C# EGPC error estimation format format Integer Gmail Google Google Adsense Google Chrome Google Search Engine Google search result how to HTTP internet marketing Java JavaScript Linux money password performance PHP programming search engine optimization secure security short URL SQL static constructor String tiny URL Tips and Tricks twitter video Windows Vista Wordpress wordpress plugin wordpress theme Youtube

Copyright © 2025 · Magazine Pro Theme on Genesis Framework · WordPress · Log in