Home » Core Java » class » Static clause initialization

About Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Static clause initialization

This is an example of how to make a static clause initialization. In order to do so, we have created two classes as described below:

  • We have a class A that has a method func(int val) that prints the given int value.
  • We also have a class B, that has two static A objects and in a static clause creates two new instances of the two A objects.
  • We call the func() method of a1 field of B in a main() method.

Let’s take a look at the code snippet that follows:
  
  

package com.javacodegeeks.snippets.core;

class A {

    A(int val) {

  System.out.println("A(" + val + ")");
    }

    void func(int val) {

  System.out.println("func(" + val + ")");
    }
}


class B {

    static A a1;
    static A a2;

    static {

  a1 = new A(1);

  a2 = new A(2);
    }

    B() {

  System.out.println("B()");
    }
}

public class StaticClause {

    public static void main(String[] args) {

  System.out.println("Inside main()");

  B.a1.func(99); // (1)
    }
    //uncoment the following code and see what happens
    // static B x = new B(); // (2)
    // static B y = new B(); // (2)
}

Output:

Inside main()
A(1)
A(2)
func(99)

  
This was an example of how to make a static clause initialization in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments