Say, I'm using connection to database named con
(or socket or anything else which is Closable
). What happens after close()
? Does con
become equal to null
or there is still something in it? And what is the difference between con.close()
and con = null
?
The reference variables will store null if they are explicitly referencing an object in memory. The main difference between primitive and reference type is that primitive type always has a value, it can never be null but reference type can be null, which denotes the absence of value.
But just to make it clear - no, you can't call an instance method with a null pointer.
When you call close
, the object should free all the resources it uses behind the scenes. In case of an instance of java.sql.Connection
, it will one of two things:
DriverManager.getConnection(...)
.Connection
is handled by a DataSource
which is handled by a database connection pool.Setting the object con = null
just assigns null
value to a variable, the reference will still be alive until the Garbage Collector decides to remove it. Still, setting the Connection
to null
doesn't call close
method, thus you can have memory leaks.
As a best practice, you should ALWAYS call close
method on instances of Closeable
or use try-with-resources
(available since Java 7) to make sure the resource(s) is(are) always closed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With