Posts

Showing posts from December, 2016

Garbage collection question - Java

class A { Boolean b ; A easyMethod ( A a ){ a = null ; // the reference to a2 was passed in, but is set to null // a2 is not set to null - this copy of a reference is! return a ; // null is returned } public static void main ( String [] args ){ A a1 = new A (); // 1 obj A a2 = new A (); // 2 obj A a3 = new A (); // 3 obj a3 = a1 . easyMethod ( a2 ); // a3 set to null and flagged for GC - see above for why a1 = null ; // so far, a1 and a3 have been set to null and flagged // Some other code } } Two objects are eligible for garbage collection (a1 and a3).  b  is not because it's only a reference to null. No  Boolean  was ever made. To get around the inane subtleties of what  // Some other code  might be, I instead posit the question be reworded into the following: Prdict and explain the following output: class A...

Class, Reference and Object

If you like housing metaphors a  class  is like the blueprint for a house. Using this blueprint, you can build as many houses as you like. each house you build (or instantiate, in OO lingo) is an  object , also known as an  instance . each house also has an address, of course. If you want to tell someone where the house is, you give them a card with the address written on it. That card is the object's  reference . If you want to visit the house, you look at the address written on the card. This is called  dereferencing . You can copy that reference as much as you like, but there's just one house -- you're just copying the card that has the address on it, not the house itself. Java methods are always pass-by-value, but the value could be an object's reference. So, if I have: Foo myFoo = new Foo (); // 1 callBar ( myFoo ); // 2 myFoo . doSomething () // 4 void callBar ( Foo foo ) { foo = new Foo (); ...