2

I'm very sorry to have asked such a basic question but I just cant understand how this output is generated.If someone has time to answer my dumb question,it will be very much appreciated.Thanks in advance.

this is the code

public class EchoTestDrive { public static void main(String[] args) { Echo e1= new Echo(); Echo e2= new Echo(); int x=0; while(x < 4) { e1.hello(); e1.count=e1.count +1; if(x==3) { e2.count=e2.count+1; } if(x>0) { e2.count=e2.count+e1.count; } x=x+1; } System.outprintln(e2.count); } } class Echo { int count =0; void hello() { System.outprintln("helloo..."); } } 

This gives the output:

helloo... helloo... helloo... helloo... 10 

now to get 24 instead of 10 we declare Echo e2=e1; instead of Echo e2=new Echo; I want to know how does this generate this particular output.for 10 i can literally put values in each and get that answer but what happens when i make them equal(that i cant understand).

0

2 Answers 2

11

When you make e2 = e1, it makes e1 also points to the same object.

Hence count is incremented twice as both e1 and e2 are incrementing it.

When you do Echo e2 = new Echo() and Echo e1 = new Echo() both e1 and e2 are pointing to two different objects and hence incrementing count of e1 won't have any impact on e2.count.

Edit:

I will add a picture to explain the same.

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

2

When you use the keyword "new" you create a new object.

For example, the following creates different objects

Echo e1= new Echo(); Echo e2 new Echo(); 

And both objects are independent of each other,

However, if you do

Echo e1= new Echo(); Echo e2= e1; 

Both e1 and e2 reference to the same object, every manipulation you do to e2 is also affecting e1 and viceversa, since they are pointing the same new Echo().

However,consider the following:

Echo e1= new Echo(); Echo e2= e1; e2 = new Echo(); 

Does this destroys e1? The answer is no. e2 stops referencing e1 and instead references a new object (hence the keyword).

Maybe this doesn't answer your questions directly, but should clarify a few points.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.