Socket s = null; Scanner sc = null; try { s = new Socket("localhost", 12452); sc = new Scanner(s.getInputStream()); ........... // work } finally { if (sc != null) { sc.close(); } if (s != null) { s.close(); } } AutoCloseable // resource // try-with-resources try ( Socket s = new Socket("localhost", 12452); Scanner sc = new Scanner(s.getInputStream()); ) { ........... // work }