Wednesday 13 December 2006

SCJP Chapter 6

Of strings, I/O, formatting and parsing.

Starting with Strings, which are immutable, there are also mutable StringBuffers and StringBuilders (added as of Java 5). The latter two are the same except that StringBuilders are faster because they are not synchronized (and therefore thread-unsafe). Important stuff to remember; know the methods of all three classes, Strings have length() method and arrays have length variable, know the differences between Strings and the other two, and beware chained methods.

For I/O, there are six classes to contend with; File, FileReader, BufferedReader, FileWriter, BufferedWriter and PrintWriter. Know about File's existential and creation problems. Know about wrapping classes up to enable higher-level usage and which ones are legal. Be aware that PrintWriter, as of Java 5, can now be used by wrapping a File or String.

Serialization is the saving of state of objects into a file for them to be read later (deserialization), reconstituting back the class objects. ObjectOutputStream and ObjectInputStream with their respective writeObject() and readObject() methods are the ones that allow the saving and loading of objects. Being higher-level classes, they need to be wrapped around the lower-level classes FileOutputStream and FileInputStream. A few things to note: all the classes to be serialized must either implement the Serializable interface or have a superclass that did. Any non-serializable object will cough up a runtime exception by the JVM. The transient keyword tells the serialization to skip a variable, not saving it. However, if there is need for that variable's state to be saved, one can override the writeObject() and readObject() to include it (the overriding code has to be in the class to be serialized). Constructors do not run for serialization, however a non-serializable superclass will run its constructor, potentially changing inherited variables. Lastly, serialization does not work for statics.

To work with dates, numbers and currencies, these classes are available: Date, Calendar and Locale from java.util.*, DateFormat and NumberFormat from java.text.*. Calendar, DateFormat and NumberFormat use factory methods to initialize. Knowing how to use all the classes is essential.

The last section of Chapter 6 deals with finding stuff (through regular expressions, of which there are two ways, pattern matching and searching using the Scanner class), tokenizing stuff (through String.split and using the Scanner class) and formatting stuff (Using printf and format, which are identical, C-style).

Chapter 7, the return of the Generics!

No comments: