Wednesday, 7 October 2020

What Is The Actual Difference Between Closeable And AutoCloseable In Java

Well, practically there is not much difference. If you check Java doc, you will notice that Closeable interface extends AutoCloseable interface. But there is one difference & that explains the reason why AutoCloseable interface was introduced in Java 7. Closeable  close() method can throw IOException only. And that made  sense as you will be using Closeable mostly with IO resources. But to handle other generic exceptions too with close() method, AutoCloseable was introduced.

public interface Closeable extends AutoCloseable {

              public void close() throws IOException;


public interface AutoCloseable {

                void close() throws Exception;


There is a misconception that Closeable can't be used with try-with-resources code block. But that is not true from Java 7 & hopefully everybody has a more upgraded version than that 😀. Both interfaces work with try-with-resources statement so that you don't have to call close() method explicitly.

No comments:

Post a comment

Evaluate Reverse Polish Notation In Java

Here is a fully working Java solution for evaluation of Reverse Polish Notation (Postfix Expression). This is a common interview question th...