Posted by: ahmedashfaque | February 3, 2015

Solution for the programming puzzle


I had provided a programming puzzle and asked you the solution for the same. Today let me give you the solution as well as explanation.

The computer program will print 10 on your computer screen. Many of you people may have expected 9 as the solution but this is wrong.

What we did was to assign e1 to e2. If you do not know then let me state that assigning an object is different from that for variables in computer programming.

Suppose we had 2 variables a and b. Let us do some assignments for them.

a = 4;

b = a;

Now the values will be a= 4 as well as b = 4.

Now if I do

b = b + 1

And add a + b then we will get 9 (a  =4, b = 5)

But when I do this operation with objects then things are different. When I did e2 = e1 then effectively I told the compiler that even though e1 and e2 are 2 entities but they point to same memory. When I did e2 = e2 + 1 then I made e = 5. But since e1 is also now pointing to this same memory so e1 = 5. Thus e1+e2 = 10.

this is funny but objects behave this way.

I hope you now understand difference between assignment of objects and that for variables.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: