class

Static array shared between class instances

This is an example of how to create a static array shared between class instances. The example is described in short below: 

  • We have created a class, SharedArray, that has a static int array, initialized with length 10.
  • In a static block, the array is initialized with random int values, using random() API method of Math.
  • The class also has a printArray() method, that prints the values of the array.
  • We create a new instance of SharedArray that is a1 and use printArray() method to print the values of the static array.
  • Then we create a new instance of SharedArray, that is a2 and print out the static array values again.
  • Then we use printArray() method of a1 object.
  • The static array in a1 instance has the same values that it had when a2 was initialized.

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

package com.javacodegeeks.snippets.core;

public class SharedArray {

    static int[] array = new int[10];

    {

  System.out.println();

  System.out.println("Running initialization block.");


  for (int i = 0; i < array.length; i++) {


array[i] = (int) (100.0 * Math.random());

  }
    }

    void printArray() {


  for (int i = 0; i < array.length; i++) {



System.out.print(" " + array[i]);

  }

    }

    public static void main(String[] args) {


  SharedArray a1 = new SharedArray();

  a1.printArray();


  SharedArray a2 = new SharedArray();

  a2.printArray();

  System.out.println();


  a1.printArray();

  System.out.println();

    }
}

Output:

Running initialization block.
 33 33 35 56 75 66 73 68 69 35
Running initialization block.
 63 2 0 76 78 34 35 80 91 92
 63 2 0 76 78 34 35 80 91 92

  
This was an example of how to create a static array shared between class instances in Java.

Ilias Tsagklis

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

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button