-1

I want to create an array of class objects and initialize it also without using any method so i wrote code like this:

package test;

public class Test2 {
    private Test2() {
    }

    static Test2[] arr = new Test2[10];
    static {
        for (Test2 ob : arr) {
            ob = new Test2();
        }
        for (Test2 ob : arr) {
            System.out.println(ob);
        }
    }

    public static void main(String args[]) {
    }
}

But when i run this program, i get o/p:

null
null
null
null
....

Why is it happening? It seems that constructor is not called when i create a new object

jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
Shivam Bansal
  • 37
  • 1
  • 6
  • You don't initialize the array contents properly, so why are you wondering what result you get? – Smutje Jun 10 '14 at 12:04

5 Answers5

4

for (Test2 ob : arr) { gives you a copy of the reference to each element in arr. When you write ob = new Test2(); you're simply changing what ob is referring to. This doesn't change what's in the original array.

You need to write code like arr[n] = new Test2(); instead.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

What you do is changing ob variable 10 times, and never use its value.

At each loop iteration ob points to a null object in arr, then setting its value just changes it to point to new Test2(), not related to arr

You should use:

    for (int i=0;i<arr.length;i++) {
        arr[i] = new Test2();
    }
BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
0

You're creating objects, but they're never stored in the array. You need something like this:

for (int i=0; i < arr.length; i++) {
    arr[i] = new Test2();
}
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
0

You are Initializing array. You are not setting the reference in array to the Test2 instance you initialized.

Hulk
  • 152
  • 3
  • 10
-2

I think constructor is used to initialize the object that why static method is not creating any object . use new operator followed by constructor to allocate memory to that object in static block to create array of objects.

iKing
  • 667
  • 10
  • 15