How many object can be created for a class in java

Recommended Answers

All 3 Replies

In practice it's limited by the available memory, but if each instance does not have big data members you can create tens of millions of instances

commented: The technical term in "gazillions"... :-) +12
commented: :) +0

technically, only 1 class instance is created for any class per classloader.
After that, any number of instance of that class can also be created, as needed, discarded, reused, serialised, deserialised, etc. etc.

Just for fun I created a small class (one int as its members)

class X{
   int i=0;
}

and an array to keep them in

X[] instances = new X[100_000_000];

then looped creating instances until it ran out of memory

for (int i = 0; i < instances.length; i++) {
    instances[i] = new X();
    if (i % 1_000_000 == 0) {
        System.out.println(i / 1_000_000 + " million");
    }
}

Using NetBeans with its default memory settings (2 Gig on my 8 Gig machine)it ran for 1 1/2 minutes before crashing with an out of memory exception, having created and kept over 54 million instances.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.