2

I am confused as I am new to java, how many objects and references are created in the following piece of code?

MyClass t = new MyClass();
MyClass s = new MyClass();
MyClass v = s;

Please explain the answer:

2 Objects
3 References
Dave Newton
  • 156,572
  • 25
  • 250
  • 300
sum2000
  • 1,335
  • 5
  • 21
  • 35

5 Answers5

6

A picture is worth more than a thousand words:

enter image description here

Eng.Fouad
  • 111,301
  • 67
  • 311
  • 403
2

An object is an instance of a class, created with new. You use new twice, so there are two objects.*

A variable is, generally speaking, a reference.** So there are three references (t, s, v), although two of them happen to refer to the same object.


* Of course, MyClass itself might create more objects internally.

** Except in the case of primitive types, like int, float, etc.

Oliver Charlesworth
  • 260,367
  • 30
  • 546
  • 667
2

2 Object and

3 reference

if you do new you are creating object so there are two new so simply two Objects

and if you define

Foo a;// you have just created a reference

* Note: new is only a way to create object, it can be created using otherways too

jmj
  • 232,312
  • 42
  • 391
  • 431
  • What are other ways to create an object other than `new` (not including things like `clone` which will call `new` internally?) – Oliver Charlesworth Dec 17 '11 at 18:13
  • @Oli http://stackoverflow.com/questions/95419/what-are-all-the-different-ways-to-create-an-object-in-java – jmj Dec 17 '11 at 18:14
2

So you are creating a new object and storing a reference to that object in t. The same for s. Then you are assigning the s reference to v (not creating a new object). So you have three references and two objects.

James Hull
  • 3,631
  • 2
  • 26
  • 36
0

Actually, your answer is wrong. It's the other way around:

2 objects (in the first two lines)

3 references (t, s, v, v and s share an object)

nfechner
  • 16,925
  • 7
  • 44
  • 64