Monday, April 26, 2004

(Myth v/s Fact) Value or Reference

Java uses Pass-by-value (duh!!) what's so great about it ??,The fact is this innocous looking statement has been twisted, contorted to versions like " Java uses pass-by-value for primitive values and uses pass- by- reference for Objects."
The above statement is false since Java NEVER uses Pass -by -reference only pass -by -value. And when u pass an object to a method its the object reference that is passed by value and not the object itself.

What this means is that the following code will not work as expected
class DBConn {
// wrapper to connection object
}

class Appln{

// create and use DBConn to openConnection
DBConn dbObj = new DBConn(...);
// close the dbconn and make it avail for garbage collection
closeDBConn(dbObj);
// THE db OBJ is still visible here

public closeDBConn(dbObj)
{
dbObj=null;
}
}

THe above snippet of code uses closeDB(dbObj) where the dbobj is initialized to null this would
have worked if Java employs Pass-BY- reference but here it will not . for the simple reason that a duplicate/alias copy of the dbobj reference variable is made and this variable exists within the method scope .so initializing this reference to null will not make the object null

No comments: