Tutorial by Examples

Sometimes, programmers who are new Java will use primitive types and wrappers interchangeably. This can lead to problems. Consider this example: public class MyRecord { public int a, b; public Integer c, d; } ... MyRecord record = new MyRecord(); record.a = 1; // OK ...
Some programmers think that it is a good idea to save space by using a null to represent an empty array or collection. While it is true that you can save a small amount of space, the flipside is that it makes your code more complicated, and more fragile. Compare these two versions of a method for ...
On StackOverflow, we often see code like this in Answers: public String joinStrings(String a, String b) { if (a == null) { a = ""; } if (b == null) { b = ""; } return a + ": " + b; } Often, this is accompanied with an asse...
Some Java programmers have a general aversion to throwing or propagating exceptions. This leads to code like the following: public Reader getReader(String pathname) { try { return new BufferedReader(FileReader(pathname)); } catch (IOException ex) { System.out.println(&q...
To prevent memory leaks, one should not forget to close an input stream or an output stream whose job is done. This is usually done with a try-catch-finally statement without the catch part: void writeNullBytesToAFile(int count, String filename) throws IOException { FileOutputStream out = null...
A lot of example code posted on StackOverflow includes snippets like this: if ("A".equals(someString)) { // do something } This does "prevent" or "avoid" a possible NullPointerException in the case that someString is null. Furthermore, it is arguable that ...

Page 1 of 1