Tutorial by Examples

(This pitfall applies equally to all primitive wrapper types, but we will illustrate it for Integer and int.) When working with Integer objects, it is tempting to use == to compare values, because that is what you would do with int values. And in some cases this will seem to work: Integer int1_1 =...
Every time a program opens a resource, such as a file or network connection, it is important to free the resource once you are done using it. Similar caution should be taken if any exception were to be thrown during operations on such resources. One could argue that the FileInputStream has a finaliz...
Java manages memory automatically. You are not required to free memory manually. An object's memory on the heap may be freed by a garbage collector when the object is no longer reachable by a live thread. However, you can prevent memory from being freed, by allowing objects to be reachable that are...
A common mistake for Java beginners is to use the == operator to test if two strings are equal. For example: public class Hello { public static void main(String[] args) { if (args.length > 0) { if (args[0] == "hello") { System.out.println(&q...
Some people recommend that you should apply various tests to a file before attempting to open it either to provide better diagnostics or avoid dealing with exceptions. For example, this method attempts to check if path corresponds to a readable file: public static File getValidatedFile(String path...
No Java variable represents an object. String foo; // NOT AN OBJECT Neither does any Java array contain objects. String bar[] = new String[100]; // No member is an object. If you mistakenly think of variables as objects, the actual behavior of the Java language will surprise you. For...
Occasionally we see StackOverflow Java questions (and C or C++ questions) that ask what something like this: i += a[i++] + b[i--]; evaluates to ... for some known initial states of i, a and b. Generally speaking: for Java the answer is always specified1, but non-obvious, and often difficult ...
New Java programmers often forget, or fail to fully comprehend, that the Java String class is immutable. This leads to problems like the one in the following example: public class Shout { public static void main(String[] args) { for (String s : args) { s.toUpperCase(); ...

Page 1 of 1