sum2000
sum2000

Reputation: 1393

Object and references in java

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

Upvotes: 2

Views: 202

Answers (5)

Eng.Fouad
Eng.Fouad

Reputation: 117569

A picture is worth more than a thousand words:

enter image description here

Upvotes: 6

nfechner
nfechner

Reputation: 17525

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)

Upvotes: 0

James Hull
James Hull

Reputation: 3689

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.

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240860

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

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272457

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.

Upvotes: 2

Related Questions