Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions




Thinking in Java
Prev Contents / Index Next

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:

// The P.rint & P.rintln shorthand.

public class P {
  public static void rint(String s) {
  public static void rintln(String 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:

// Uses the tools library.
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!",
} ///:~

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.
Thinking in Java
Prev Contents / Index Next

   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire