THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1
Henri Poincaré

Chapter 22. Miscellaneous Utilities


The best way to make a fire with two sticks is to make sure one of them is a match.

Will Rogers

You will find several standard utility interfaces and classes in the java.util package. You have seen the
collection classes already in Chapter 21. This chapter covers the remainder of the classes except those used for
localization, which are in Chapter 24. The java.util classes covered in this chapter are



  • Formatter A class for producing formatted text.

  • BitSet A dynamically sized bit vector.
    Observer/Observable An interface/class pair that enables an object to be Observable by
    having one or more Observer objects that are notified when something interesting happens in the
    Observable object.




  • Random A class to generate sequences of pseudorandom numbers.
    Scanner A class for scanning text and parsing it into values of primitive types or strings, based on
    regular expression patterns.



StringTokenizer A class that splits a string into tokens based on delimiters (by default,
whitespace).



  • Timer/TimerTask A way to schedule tasks to be run in the future.

  • UUID A class that represents a universally unique identifier (UUID).


Finally, we look at two other useful classes, housed in the java.lang package:


Math A class for performing basic mathematical operations, such as trigonometric functions,
exponentiation, logarithms, and so on.


StrictMath Defines the same methods as Math but guarantees the use of specific algorithms that
ensure the same results on every virtual machine.


22.1. Formatter


The Formatter class allows you to control the way in which primitive values and objects are represented as
text. The common way to represent objects or values as text is to convert the object or value to a string, using
either the toString method of the object or the toString method of the appropriate wrapper class. This
is often done implicitly, either through use of string concatenation or by invoking a particular overload of the
PrintStream or PrintWriterprint methods. This is easy and convenient, but it doesn't give you any
control over the exact form of the string. For example, if you invoke


System.out.println("The value of Math.PI is " + Math.PI);


the output is


The value of Math.PI is 3.141592653589793

Free download pdf