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
  • 158,873
  • 26
  • 254
  • 302
sum2000
  • 1,363
  • 5
  • 21
  • 36

5 Answers5

6

A picture is worth more than a thousand words:

enter image description here

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
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
  • 267,707
  • 33
  • 569
  • 680
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
  • 237,923
  • 42
  • 401
  • 438
  • 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,669
  • 2
  • 27
  • 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
  • 17,295
  • 7
  • 45
  • 64