Good programming practices

Easier programming with Java 7

July 27th, 2011

Java 7 has several improvements in the language itself. In my opinion the most important is the try-with-resources statement. It makes work with resources much easier. You will no longer have to manually close used resources. It will be done automatically when used the new statement.

  1. void oldResourceHandling(String file) {
  2. byte[] buf = new byte[1024];
  3. int read;
  4. InputStream is = null;
  5. try {
  6. is = new FileInputStream(file);
  7. while ((read = is.read(buf)) > 0) {
  8. System.out.print(new String(buf, 0, read));
  9. }
  10. } catch (IOException ex) {
  11. ex.printStackTrace();
  12. } finally {
  13. if (is != null) {
  14. try {
  15. is.close();
  16. } catch (IOException ex) {
  17. ex.printStackTrace();
  18. }
  19. }
  20. }
  21. }
  22.  
  23. void newResourceHandling(String file) {
  24. byte[] buf = new byte[1024];
  25. int read;
  26. try (InputStream is = new FileInputStream(file)) {
  27. while ((read = is.read(buf)) > 0) {
  28. System.out.print(new String(buf, 0, read));
  29. }
  30. } catch (IOException ex) {
  31. ex.printStackTrace();
  32. }
  33. }

All classes that can be used in try-with-resources statement implements java.lang.AutoCloseable interface. In the documentation you can find which classes implement it. You can also implement it in your classes which have to release resources after leave try block.

Another facilitation is String switch. It’s known construction from script languages like PHP. It may be useful when application gets commands as String, i.e. command line argument.

  1. int oldStringSwitch(String s) {
  2. int i;
  3. if ("first".equals(s)) {
  4. i = 1;
  5. } else if ("second".equals(s)) {
  6. i = 2;
  7. } else if ("third".equals(s)) {
  8. i = 3;
  9. } else {
  10. i = 0;
  11. }
  12. return i;
  13. }
  14.  
  15. int newStringSwitch(String s) {
  16. int i;
  17. switch (s) {
  18. case "first":
  19. i = 1;
  20. break;
  21. case "second":
  22. i = 1;
  23. break;
  24. case "third":
  25. i = 1;
  26. break;
  27. default:
  28. i = 0;
  29. }
  30. return i;
  31. }

However, using String as constant is discouraged. It would be better to use enum type instead if possible.

Leave a Response