Java Reference
In-Depth Information
In this example, two different StringTokenizer objects are created using different argu-
ments to the constructor listed after new .
The first instance uses new StringTokenizer() with one argument, a String object
named quote1 (line 9). This creates a StringTokenizer object that uses the default delim-
iters: blank spaces, tab, newline, carriage return, or formfeed characters.
If any of these characters is contained in the string, it is used to divide the tokens. Because
the quote1 string contains spaces, these are used as delimiters dividing each token. Lines
10-12 display the values of all three tokens: VIZY , 3 , and -1/16 .
The second StringTokenizer object in this example has two arguments when it is con-
structed in line 14—a String object named quote2 and an at-sign character ( “@” ). This
second argument indicates that the “@” character should be used as the delimiter between
tokens. The StringTokenizer object created in line 15 contains three tokens: NPLI , 9
27/32 , and 3/32 .
You get a chance to work with live stock data from Yahoo Finance in the
QuoteData project during Day 18, “Accessing Databases with JDBC.”
The application uses StringTokenizer to split up stock quote
fields separated by commas.
NOTE
What new Does
Several things happen when you use the new operator—the new instance of the given class
is created, memory is allocated for it, and a special method defined in the given class is
called. This special method is called a constructor.
A constructor is a special method for creating and initializing a new instance of a class. A
constructor initializes the new object and its variables, creates any other objects that the
object needs, and performs any other operations that the object needs to initialize itself.
Multiple constructor definitions in a class can each have a different number, or type, of
arguments. When you use new , you can specify different arguments in the argument list,
and the correct constructor for those arguments is called. Multiple constructor definitions
enabled the TokenTester class in the previous example to accomplish different things with
the different uses of the new operator. When you create your own classes, you can define
as many constructors as you need to implement the behavior of the class.
A Note on Memory Management
If you are familiar with other object-oriented programming languages, you might wonder
whether the new statement has an opposite that destroys an object when it is no longer needed.
Search WWH ::




Custom Search