A custom tool library
With this knowledge, you can now create your own libraries of tools to reduce or eliminate duplicate code. Consider, for example, creating an alias for System.out.println( ) to reduce typing. This can be part of a package called tools:
//: com:bruceeckel:tools:P.java
// The P.rint & P.rintln shorthand.
package com.bruceeckel.tools;
public class P {
public static void rint(String s) {
System.out.print(s);
}
public static void rintln(String s) {
System.out.println(s);
}
} ///:~
You can use this shorthand to print a String either with a newline (P.rintln( )) or without a newline (P.rint( )).
You can guess that the location of this file must be in a directory that starts at one of the CLASSPATH locations, then continues com/bruceeckel/tools. After compiling, the P.class file can be used anywhere on your system with an import statement:
//: c05:ToolTest.java
// Uses the tools library.
import com.bruceeckel.tools.*;
import com.bruceeckel.simpletest.*;
public class ToolTest {
static Test monitor = new Test();
public static void main(String[] args) {
P.rintln("Available from now on!");
P.rintln("" + 100); // Force it to be a String
P.rintln("" + 100L);
P.rintln("" + 3.14159);
monitor.expect(new String[] {
"Available from now on!",
"100",
"100",
"3.14159"
});
}
} ///:~
Notice that all objects can easily be forced into String representations by putting them in a String expression; in the preceding example, starting the expression with an empty String does the trick. But this brings up an interesting observation. If you call System.out.println(100), it works without casting it to a String. With some extra overloading, you can get the P class to do this as well (this is an exercise at the end of this chapter).
So from now on, whenever you come up with a useful new utility, you can add it to your own tools or util directory.