john
john

Reputation: 834

How many objects are created in the memory runtime?

I'm studying for 1z0-803 Java certificate exam at the moment. We have to find out, how many instances of MarkList are created in this application:

public class MarkList {
   int num;

   public static void graceMarks(MarkList obj4) {
       obj4.num += 10;
   }

   public static void main(String[] args) {
       MarkList obj1 = new MarkList();
       MarkList obj2 = obj1;            
       obj2.num = 60;
       graceMarks(obj2);
    }
}

A friend of mine said that in this question the answer is two objects. I think it's only one (obj1), though I may be wrong since I'm new with Java but have some experience with C#.

Upvotes: 3

Views: 2368

Answers (3)

Man Coding
Man Coding

Reputation: 451

Forget about this question. This exam question has a typo if you randomly search online. Many websites mentioned obj3 but it wasn't there. Your friend might read from a source that contains a typo.

Upvotes: 1

slartidan
slartidan

Reputation: 21576

Only one instance of MarkList is created.

For to find out how many objects are created you can use this procedure:

  • search for any call of an constructor (looks like new MarkList(...)). You can use an IDE like eclipse to find all references.
  • check how often the code containing the constructor is called (could be inside of a loop or inside of a method that gets called several times).
  • putting the once created objects into different variables, or handing them over from one method to another will not create additional instances => irrelevant

However thousands of other instances are created (in my Oracle JDK 1.8).

  • MarkList.class is created
  • String[] args is created
  • MarkList obj1 is created
  • Many, many runtime objects (like Thread.currentThread() are created)

Use a profiler, run your code and count the objects. But keep in mind, that that result will be quite dependent on your JVM implementation.

VisualVM profiling results

Upvotes: 7

MartinS
MartinS

Reputation: 2790

The answer is one object. MarkList obj1 = new MarkList(); creates a new MarkList object, MarkList obj2 = obj1; only creates a reference to obj1 so both point to the exact same object. All the other code is just boilerplate and does not create objects.

Upvotes: 9

Related Questions