Using the initialization block in Java “double-{“


Using the class initialisation block can help tremendously in initialising objects, take a look at the following code:

JMenuItem menuItem = new JMenuItem("My Menu Item");
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, InputEvent.ALT_MASK));
menuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // etc etc

This can be also written as:

myMenu.add(new JMenuItem("My Menu Item") \{{
    setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, InputEvent.ALT_MASK));
    addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

This is sometimes referred to as the "double-{" initialisation block, but is merely just extending the JMenuItem using an anonymous class and adding the object initialisation block to that (recall there is also a static initialisation block in classes: static {...}

This article does not necessarily reflect the technical opinion of EDC4IT, but purely of the writer. If you want to discuss about this content, please send us an email at