Wednesday, June 27, 2007

Chapter 9 - The java.lang Package

Chapter 9: The java.lang Package

Objectives

This chapter helps you to prepare for the exam by covering the following objectives:

Know the important classes and interfaces provided by the java.lang package.

.
The java.lang package is the main Java API package. It provides the fundamental
classes and interfaces, such as Object, Class and System, upon which the rest of the
Java API is built. You need to know how these classes and interfaces are used in order to
answer several exam questions.
Know what the wrapped classes are and how they are used.

.
Several exam questions require you to be familiar with the java.lang classes that are
used to represent primitive values as objects. You need to know how to create object
wrappers for primitive types, what methods the wrapped classes support, and how to
convert from wrapped objects back to primitive values.
Know the differences between the String and StringBuffer classes. Describe the
significance of the immutability of String objects.

.
Several exam questions require knowledge of the String and StringBuffer classes. To
correctly answer these exam questions, you need to know the relationships between these
classes and the types of methods that they support.
Know how the methods of the Math class are used to perform mathematical calculations. Write
code using the following methods of the java.lang.Math class: abs(), ceil(), floor(),
max(), min(), random(), round(), sin(), cos(), tan(), and sqrt().

.
Knowledge of the methods of the Math class were required for the JDK 1.1 exam. Although
these methods are not emphasized as much on the JDK 1.2 exam, you'll still need to know
them in order to answer a few exam questions.
Know how other java.lang classes and interfaces are used.

.
Although the certification exam focuses on classes described for the previous objectives,
knowledge of other classes and interfaces is important to be able to program in Java.
- 144



Familiarity with these other classes and interfaces may help you answer some exam
questions.

Chapter 9: The java.lang Package

Objectives

This chapter helps you to prepare for the exam by covering the following objectives:

Know the important classes and interfaces provided by the java.lang package.

.
The java.lang package is the main Java API package. It provides the fundamental
classes and interfaces, such as Object, Class and System, upon which the rest of the
Java API is built. You need to know how these classes and interfaces are used in order to
answer several exam questions.
Know what the wrapped classes are and how they are used.

.
Several exam questions require you to be familiar with the java.lang classes that are
used to represent primitive values as objects. You need to know how to create object
wrappers for primitive types, what methods the wrapped classes support, and how to
convert from wrapped objects back to primitive values.
Know the differences between the String and StringBuffer classes. Describe the
significance of the immutability of String objects.

.
Several exam questions require knowledge of the String and StringBuffer classes. To
correctly answer these exam questions, you need to know the relationships between these
classes and the types of methods that they support.
Know how the methods of the Math class are used to perform mathematical calculations. Write
code using the following methods of the java.lang.Math class: abs(), ceil(), floor(),
max(), min(), random(), round(), sin(), cos(), tan(), and sqrt().

.
Knowledge of the methods of the Math class were required for the JDK 1.1 exam. Although
these methods are not emphasized as much on the JDK 1.2 exam, you'll still need to know
them in order to answer a few exam questions.
Know how other java.lang classes and interfaces are used.

.
Although the certification exam focuses on classes described for the previous objectives,
knowledge of other classes and interfaces is important to be able to program in Java.
Familiarity with these other classes and interfaces may help you answer some exam
questions.
Chapter Introduction

This chapter covers the classes and interfaces of the java.lang package. This chapter is important
because there are several exam questions that require knowledge of this package. This chapter, like the
exam, focuses on the few important classes of java.lang: Object, Class, System, String,
StringBuffer, Math, and the wrapped classes. It also briefly covers the other classes and interfaces
of java.lang. If you read through this chapter and master the review questions, then you should be
able to significantly improve your score on the certification exam.
The java.lang package provides 30 classes and 3 interfaces (not counting the Error and
Exception classes (and their subclasses)) that are fundamental to Java programming. These classes
and interfaces are described in the following sections.

The Object, Class, and Package Classes

Object and Class are two of the most important classes in the Java API. The Object class is at the
top of the Java class hierarchy. All classes are subclasses of Object and, therefore, inherit its
methods. The Class class is used to provide information about each class loaded by the Java Virtual
Machine. The Package class is new to JDK 1.2. It is used to provide version information about a
package.

Object

The Object class does not have any variables and has only one constructor. However, it provides 11
methods that are inherited by all Java classes and support general operations used by all objects. For
example, the equals() and hashCode() methods are used to compare Java objects. Hash tables are
like arrays, but are indexed by key values (referred to as hash codes) and dynamically grow in size. A
hash table associates objects with hash codes, so that the objects can be efficiently stored and

- 145



retrieved. They make use of hash functions that map objects to their hash codes. The hashCode()
method creates a hash code for an object and is an example of a hash function. Hash codes can be
used used to quickly determine whether two objects are different.
The clone() method creates an identical copy of an object. (Object references are copied but not the
objects referenced by the references.) A cloned object must implement the clonable interface. This
interface is defined within the java.lang package. It contains no methods and is used only to
differentiate clonable classes from nonclonable classes.
The getClass() method identifies the class of an object by returning an object of Class. The
toString() method creates a String representation of the value of an object. This method is handy
for quickly displaying the contents of an object. When an object is displayed, using print() or
println(), the toString() method of its class is automatically called to convert the object into a
string before printing. Classes that override the toString() method can easily provide a custom
display for their objects.
The finalize() method of an object is executed when an object is garbage-collected. The method
performs no action, by default, and needs to be overridden by any class that requires specialized
finalization processing.
The Object class provides three wait() and two notify() methods that support thread
synchronization control. These methods are implemented by the Object class so that they can be
made available to threads that are not created from subclasses of class Thread. The wait() methods
cause a thread to wait until it is notified or until a specified amount of time has elapsed. The notify()
methods are used to notify waiting threads that their wait is over.

Class

The Class class provides over 30 methods that support the runtime processing of an object's class and
interface information. This class does not have a constructor. Objects of this class, referred to as class
descriptors, are automatically created as classes are loaded by the Java virtual machine. Despite their
name, class descriptors are used for interfaces as well as classes.
The getName() and toString() methods return the String containing the name of a class or
interface. The toString() method differs in that it prepends the string class or interface, depending
on whether the class descriptor is a class or an interface. The static forName() method loads the class
specified by a String object and returns a class descriptor for that class.
The getSuperclass() method returns the class descriptor of the superclass of a class. The
isInterface() method identifies whether a class descriptor applies to a class or an interface. The
getInterfaces() method returns an array of Class objects that specify the interfaces of a class, if
any.
The newInstance() method creates an object that is a new instance of the specified class. It can be
used in lieu of a class's constructor, although it is generally safer and clearer to use a constructor rather
than newInstance(). The newInstance() method is useful to create instances of classes not
known at compile time.
The getClassLoader() method returns the class loader of a class, if one exists. Classes are not
usually loaded by a class loader. However, if a class is loaded from outside the CLASSPATH, such as
over a network, a class loader is used to convert the class byte stream into a class descriptor. The
ClassLoader class is covered later in this chapter in the "ClassLoader, Security Manager, and
Runtime Classes" section.
The Class class contains a number of other methods that begin with get and is. These methods are
used to obtain detailed information about classes and interfaces. You don't have to remember all the
methods of the Class class. For the purposes of the exam, remember that the Class class supports
the runtime processing of an object's class and interface information and that the methods of Class
provide detailed access to this information.

Package

Java software development is based upon the use and reuse of packages. Both Java 1.0 and Java 1.1
used packages. However, the Package class is new to JDK 1.2. It provides methods for obtaining
package version information stored in the manifest of .jar files. The Package class provides several
methods that can be used to retrieve information about packages. The static getPackage() and
getAllPackages() methods provide Package objects that are known to the current class loader.
Other methods return name, title, version, security, and vendor information about the specification and
implementation of packages. The isCompatibleWith() method is used to determine whether a
package is comparable with a particular version.

- 146



The Classloader, Securitymanager, and Runtime Classes

The ClassLoader, SecurityManager, and Runtime classes provide a fine level of control over the
operation of the Java runtime system. Most of the time, however, you will not want or need to exercise
this control because Java is set up to perform optimally for a variety of applications. The ClassLoader
class enables you to define custom loaders for classes that you load outside of your CLASSPATH—for
example, over a network. The SecurityManager class enables you to define a variety of security
policies that govern the accesses that classes may make to threads, executable programs, your
network, and your file system. The Runtime class provides you with the capability to control and
monitor the Java runtime system. It also allows you to execute external programs.

The System Class

The System class is one of the most important and useful classes provided by java.lang. It provides
a standard interface to common system resources and functions. It implements the standard input,
output, and error streams, and supplies a set of methods that provide control over the Java runtime
system. Some of these methods duplicate those provided by the Runtime class.

Standard Streams

The in, out, and err variables are, by default, assigned to the standard input, output, and error
streams, which are used to support console I/O. The setIn(), setOut(), and setErr() methods
can be used to reassign these variables to other streams.

Properties-Related Methods

The System class provides several properties-related methods. Properties are extensions of the
Dictionary and Hashtable classes and are defined in the java.util package. Properties are a
list of key–value pairs where the keys are String objects that specify a property's name and the values
are String objects that specify the property's value. Properties are used for storing configuration
information. A set of system properties is available through the System class that describes the general
characteristics of the operating system and runtime system you are using. The getProperties()
method gets all the system properties and stores them in an object of class Properties. The
getProperty() method gets a single property, as specified by a key. The setProperties()
method sets the system properties to the values of a Properties object. The setProperty()
method sets the value of a particular property. The identityClone() method returns the hash code
associated with an object.

Security Manager-Related Methods

The getSecurityManager() and setSecurityManager() methods provide access to the security
manager that is currently in effect. The setSecurityManager() method can be used to implement a
custom security policy. However, as of JDK 1.2, the best way to implement a custom policy is via an
external security policy.

Runtime-Related Methods

Several of the methods defined for the Runtime class are made available through the System class.
These methods include exit(), gc(), load(), loadLibrary(), runFinalizersOnExit(), and
runFinalization().

Odds and Ends

The arraycopy() method is used to copy data from one array to another. This function provides the
opportunity for system-specific, memory-copying operations to optimize memory-to-memory copies.
The currentTimeMillis() method returns the current time in milli-seconds since January 1, 1970. If
you want more capable date and time methods, check out the Date class in java.util.
The getenv() method is used to obtain the value of an environment variable. However, this method is
identified as obsolete in the Java API documentation and can no longer be used.

The Wrapped Classes

Variables that are declared using the primitive Java types are not objects and cannot be created and
accessed using methods. Primitive types also cannot be subclassed. To get around the limitations of
primitive types, the java.lang package defines class wrappers for these types. These class wrappers

- 147



furnish methods that provide basic capabilities such as class conversion, value testing, hash codes, and
equality checks. The constructors for the wrapped classes allow objects to be created and converted
from primitive values and strings. Be sure to browse the API pages for each of these classes to
familiarize yourself with the methods they provide.

The Boolean Class

The Boolean class is a wrapper for the boolean primitive type. It provides the getBoolean(),
toString(), valueOf(), and booleanValue() methods to support type and class conversion. The
toString(), equals(), and hashCode() methods override those of class Object.

The Character Class

The Character class is a wrapper for the char primitive type. It provides several methods that support
case, type, and class testing and conversion.

The Byte, Short, Integer, and Long Classes

These classes wrap the byte, short, int, and long primitive types. They provide the MIN_VALUE
and MAX_VALUE constants, as well as a number of type and class testing and conversion methods. The
parseInt() and parseLong() methods are used to parse String objects and convert them to
Byte, Short, Integer, and Long objects.

The Doubleand Float Classes

The Double and Float classes wrap the double and float primitive types. They provide the
MIN_VALUE, MAX_VALUE, POSITIVE_INFINITY, and NEGATIVE_INFINITY constants, as well as the
NaN (not-a-number) constant. NaN is used as a value that is not equal to any value, including itself.
These classes provide a number of type and class testing and conversion methods, including methods
that support conversion to and from integer bit representations.

The NumberClass

The Number class is an abstract numeric class that is subclassed by Byte, Short, Integer, Long,
Float, and Double. It provides several methods that support conversion of objects from one class to
another.

All Wrapped Up

The program in Listing 9.1 shows some of the methods that can be used with the primitive types when
they are wrapped as objects. Look up these methods in the API pages for each class and try to figure

out how they work before moving on to their explanations.
Listing 9.1: Using Wrapper Classes
public class WrappedClassApp {

public static void main(String args[]) {
Boolean b1 = new Boolean("TRUE");
Boolean b2 = new Boolean("FALSE");
System.out.println(b1.toString()+" or "+b2.toString());
for(int j=0;j<16;++j)

System.out.print(Character.forDigit(j,16))
;
System.out.println()
;
Integer i = new Integer(Integer.parseInt("ef",16))
;
Long l = new Long(Long.parseLong("abcd",16))
;
long m=l.longValue()*i.longValue()
;
System.out.println(Long.toString(m,8))
;


- 148



System.out.println(Float.MIN_VALUE);

System.out.println(Double.MAX_VALUE);
}

}
The program examines some of the more useful methods provided by the wrapped classes. It creates
two objects of class Boolean from string arguments passed to their constructors. It assigns these
objects to b1 and b2 and then converts them back to String objects when it displays them. They are
displayed in lowercase, as boolean values are traditionally represented.
The program then executes a for loop that prints out the character corresponding to each of the
hexadecimal digits. The static forDigit() method of the Character class is used to generate the
character values of digits in a number system of a different radix.
The static parseInt() and parseLong() methods are used to parse strings according to different
radices. In the example, they are used to convert strings representing hexadecimal numbers into
Integer and Long values. These values are then multiplied together and converted to a string that
represents the resulting value in base 8. This is accomplished using an overloaded version of the
toString() method.
The sample program concludes by displaying the minimum float value and the maximum double
value, using the predefined class constants of the Float and Double classes.

The program's output is as follows:

true or false

0123456789abcdef

50062143

1.4E-45

1.7976931348623157E308

The Math Class

The Math class provides an extensive set of mathematical methods in the form of a static class library.
It also defines the mathematical constants E and PI. The supported methods include arithmetic,
trigonometric, exponential, logarithmic, random number, and conversion routines. You should browse
the API page of this class to get a feel for the methods it provides. The example in Listing 9.2 only
touches on a few of these methods.

Listing 9.2: Using the Methods of the Math Class
public class MathApp {
public static void main(String args[]) {
System.out.println(Math.E);
System.out.println(Math.PI);
System.out.println(Math.abs(-1234));
System.out.println(Math.cos(Math.PI/4));
System.out.println(Math.sin(Math.PI/2));
System.out.println(Math.tan(Math.PI/4));

- 149



System.out.println(Math.log(1));
System.out.println(Math.exp(Math.PI));
for(int i=0;i<3;++i)

System.out.print(Math.random()+" ");

System.out.println();
}

}
This program prints the constants e and p, |-1234|, cos(p/4), sin(p/2), tan(p/4), ln(1), ep
,
and then three random double numbers between 0.0 and 1.1. Its output is as follows:
2.718281828459045
3.141592653589793
1234
0.7071067811865476

1.0

0.9999999999999999

0.0

23.14069263277926
0.5214844573332809 0.7036104523989761 0.15555052349418896

The random numbers you generate may differ from those shown here.

The Comparable Interface

The Comparable interface is a new interface that was added with JDK 1.2. This interface defines the
compareTo() method. Objects of classes that implement the Comparable interface can be compared
to each other and sorted.

The String and Stringbuffer Classes

The String and StringBuffer classes are used to support operations on strings of characters. The
String class supports constant (unchanging or immutable) strings, whereas the StringBuffer class
supports growable, modifiable strings. String objects are more compact than StringBuffer objects,
but StringBuffer objects are more flexible.

String Literals

String literals are strings that are specified using double quotes. "This is a string" and "xyz"
are examples of string literals. String literals are different than the literal values used with primitive
types. When the javac compiler encounters a String literal, it converts it to a String constructor.
For example, this


String str = "text"
;


is equivalent to this
String str = new String("text")
;
Because the compiler automatically supplies String constructors, you can use String literals
everywhere that you can use objects of the String class.


- 150



The + Operator and StringBuffer

If String objects are constant, how can they be concatenated with the + operator and be assigned to
existing String objects? In the following example, the code will result in the string "ab" being
assigned to the s object:


String s = ""
;


s = s + "a" + "b"
;
How can this be possible if Strings are constant? The answer lies in the fact that the Java compiler
uses StringBuffer objects to accomplish the string manipulations. This code would be rendered as
something similar to the following by the Java compiler:


String s = ""
;


s = new StringBuffer("").append("a").append("b").toString()
;
A new object of class StringBuffer is created with the "" argument. The StringBuffer
append() method is used to append the strings "a" and "b" to the new object, and then the object is
converted to an object of class String via the toString() method. The toString() method
creates a new object of class String before it is assigned to the s variable. In this way, the s variable
always refers to a constant (although new) String object.


String Constructors

The String class provides several constructors for the creation and initialization of String objects.
These constructors enable strings to be created from other strings, string literals, arrays of characters,
arrays of bytes, and StringBuffer objects. Browse through the API page for the String class to
become familiar with these constructors.

String Access Methods

The String class provides a very powerful set of methods for working with String objects. These
methods enable you to access individual characters and substrings; test and compare strings; copy,
concatenate, and replace parts of strings; convert and create strings; and perform other useful string
operations.
The most important String methods are the length() method, which returns an integer value
identifying the length of a string; the charAt() method, which allows the individual characters of a
string to be accessed; the substring() method, which allows substrings of a string to be accessed;
and the valueOf() method, which enables primitive data types to be converted into strings.
In addition to these methods, the Object class provides a toString() method for converting other
objects to String objects. This method is often overridden by subclasses to provide a more
appropriate object-to-string conversion.

Character and Substring Methods

Several String methods enable you to access individual characters and substrings of a string. These
include charAt(), getBytes(), getChars(), indexOf(), lastIndexOf(), and substring().
Whenever you need to perform string manipulations, be sure to check the API documentation to make
sure that you don't overlook an easy-to-use, predefined String method.

String Comparison and Test Methods

Several String methods allow you to compare strings, substrings, byte arrays, and other objects with
a given string. Some of these methods are compareTo(), endsWith(), equals(),
equalsIgnoreCase(), regionMatches(), and startsWith().

Copy, Concatenation, and Replace Methods

The following methods are useful for copying, concatenating, and manipulating strings: concat(),
copyValueOf(), replace(), and trim().

String Conversion and Generation

A number of string methods support String conversion. These are intern(), toCharArray(),
toLowerCase(), toString(), toUpperCase(), and valueOf(). You'll explore the use of some of
these methods in the following section.

- 151



Stringing Along

The program in Listing 9.3 provides a glimpse at the operation of some of the methods identified in the
previous subsections. Because strings are frequently used in application programs, learning to use the
available methods is essential to being able to use the String class most effectively.

Listing 9.3: Working with Strings


public class StringApp {

public static void main(String args[]) {
String s = " Java 2 Certification ";
System.out.println(s);
System.out.println(s.toUpperCase());
System.out.println(s.toLowerCase());
System.out.println("["+s+"]");
s=s.trim();
System.out.println("["+s+"]");
s=s.replace('J','X');
s=s.replace('C','Y');
s=s.replace('2','Z');
System.out.println(s);
int i1 = s.indexOf('X');
int i2 = s.indexOf('Y');
int i3 = s.indexOf('Z');
char ch[] = s.toCharArray();
ch[i1]='J';
ch[i2]='C';
ch[i3]='2';
s = new String(ch);
System.out.println(s);

}

}
This program performs several manipulations of a string s, which is initially set to " Java 2
Certification ". It prints the original string and then prints uppercase and lowercase versions of it,

- 152



illustrating the use of the toUpperCase() and toLowerCase() methods. It prints the string enclosed
between two braces to show that it contains leading and trailing spaces. It then trims away these spaces
using the trim() method and reprints the string to show that these spaces were removed.
The program uses the replace() method to replace 'J', 'C', and '2' with 'X', 'Y', and 'Z', and
prints out the string to show the changes. The replace() method is case sensitive. It uses the
indexOf() method to get the indices of 'X', 'Y', and 'Z' within s. It uses the toCharArray() to
convert the string to a char array. It then uses the indices to put 'J', 'C', and '2' back in their proper
locations within the character array. The String() constructor is used to construct a new string from
the character array. The new string is assigned to s and is printed.

The program's output is as follows:

Java 2 Certification

JAVA 2 CERTIFICATION

java 2 certification

[ Java 2 Certification ]

[Java 2 Certification]

Xava Z Yertification

Java 2 Certification

The StringBuffer Class

The StringBuffer class is the force behind the scenes for most complex string manipulations. The
compiler automatically declares and manipulates objects of this class to implement common string
operations.
The StringBuffer class provides three constructors: an empty constructor, a constructor with a
specified initial buffer length, and a constructor that creates a StringBuffer object from a String
object. In general, you will find yourself constructing StringBuffer objects from String objects, and
the last constructor will be the one you use most often.
The StringBuffer class provides several versions of the append() method to convert and append
other objects and primitive data types to StringBuffer objects. It provides a similar set of insert()
methods for inserting objects and primitive data types into StringBuffer objects. It also provides
methods to access the character-buffering capacity of StringBuffer and methods for accessing the
characters contained in a string. It is well worth a visit to the StringBuffer API pages to take a look
at the methods that it has to offer.

Strung Out

The program in Listing 9.4 shows how StringBuffer objects can be manipulated using the
append(), insert(), and setCharAt() methods.


StringbufferListing 9.4: Using the Object

public class StringBufferApp {

public static void main(String args[]) {
StringBuffer sb = new StringBuffer(" is ");
sb.append("Hot");
sb.append('!');
sb.insert(0,"Java");
sb.append('\n');
sb.append("This is ");
sb.append(true);

- 153



sb.setCharAt(21,'T')
;
sb.append('\n')
;
sb.append("Java is #")
;
sb.append(1)
;
String s = sb.toString()
;
System.out.println(s)
;


}


}
The program creates a StringBuffer object using the string " is ". It appends the string "Hot"
using the append() method and the character '!' using an overloaded version of the same method.
The insert() method is used to insert the string "Java" at the beginning of the string buffer.
Three appends are used to tack on a newline character (\n), the string "This is ", and the boolean
value true. The append() method is overloaded to support the appending of the primitive data types
as well as arbitrary Java objects.
The setCharAt() method is used to replace the letter 't' at index 21 with the letter 'T'. The
charAt() and setCharAt() methods allow StringBuffer objects to be treated as arrays of
characters.
Finally, another newline character is appended to sb, followed by the string "Java is #" and the int
value 1. The StringBuffer object is then converted to a string and displayed to the console window.


The output of the program is as follows:


Java is Hot!


This is True


Java is #
1


Threads and Processes

This section describes the classes and interfaces of java.lang that support multithreading. Chapter 8,
"Threads," covers the important ones in more detail. It also covers the Process class, which is used to
manipulate processes that are executed using the System.exec() methods.

Runnable

The Runnable interface provides a common approach to identifying the code to be executed as part of
an active thread. It consists of a single method, run(), which is executed when a thread is activated.
The Runnable interface is implemented by the Thread class and by other classes that support
threaded execution.

Thread

The Thread class is used to construct and access individual threads of execution that are executed as
part of a multithreaded program. It defines the priority constants that are used to control task
scheduling: MIN_PRIORITY, MAX_PRIORITY, and NORM_PRIORITY. It provides seven constructors for
creating instances of class Thread. The four constructors with the Runnable parameters are used to
construct threads for classes that do not subclass the Thread class. The other constructors are used
for the construction of Thread objects from Thread subclasses.
Thread supports many methods for accessing Thread objects. These methods provide the capabilities
to work with a thread's group; obtain detailed information about a thread's activities; set and test a
thread's properties; and cause a thread to wait, be interrupted, or be destroyed.

ThreadGroup

The ThreadGroup class is used to encapsulate a group of threads as a single object so that it can be
accessed as a single unit. A number of access methods is provided for manipulating ThreadGroup

- 154



objects. These methods keep track of the threads and thread groups contained in a thread group and
perform global operations on all threads in the group. The global operations are group versions of the
operations that are provided by the Thread class.

ThreadLocal

The ThreadLocal class is used to implement variables that are local to a thread. The get(), set(),
and initialize() methods are used to set and retrieve the values of these variables.

Process

The Process class is used to encapsulate processes that are executed with the System.exec()
methods. An instance of class Process is returned by the Runtime class exec() method when it
executes a process that is external to the Java runtime system. This Process object can be destroyed
using the destroy() method and waited on using the waitFor() method. The exitValue()
method returns the system exit value of the process. The getInputStream(),
getOutputStream(), and getErrorStream() methods are used to access the standard input,
output, and error streams of the process.

The Compiler Class

The Compiler class consists of static methods that are used to compile Java classes in the rare
event that you want to compile classes directly from a program or applet. These methods enable you to
build your own customized Java development environment.

Exceptions and Errors

The java.lang package establishes the Java exception hierarchy and declares numerous exceptions
and errors. Errors are used to indicate the occurrence of abnormal and fatal events that should not be
handled within application programs.

The Throwable Class

The Throwable class is at the top of the Java error-and-exception hierarchy. It is extended by the
Error and Exception classes and provides methods that are common to both classes. These
methods consist of stack tracing methods, the getMessage() method, and the toString() method,
which is an override of the method inherited from the Object class. The getMessage() method is
used to retrieve any messages that are supplied in the creation of Throwable objects.
The fillInStackTrace() and printStackTrace() methods supply and print information that is
used to trace the propagation of exceptions and errors throughout a program's execution.

The Error Class

The Error class is used to provide a common superclass to define abnormal and fatal events that
should not occur. It provides two constructors and no other methods. Four major classes of errors
extend the Error class: AWTError, LinkageError, ThreadDeath, and VirtualMachineError.
The AWTError class identifies fatal errors that occur in the Abstract Window Toolkit packages. It is a
single identifier for all AWT errors and is not subclassed.
The LinkageError class is used to define errors that occur as the result of incompatibilities between
dependent classes. These incompatibilities result when class Y depends on class X, which is changed
before class Y can be recompiled. The LinkageError class is extensively subclassed to identify
specific manifestations of this type of error.
The ThreadDeath error class is used to indicate that a thread has been stopped. Instances of this
class can be caught and then rethrown to ensure that a thread is gracefully terminated, although this is
not recommended. The ThreadDeath class is not subclassed.
The VirtualMachineError class is used to identify fatal errors occurring in the operation of the Java
Virtual Machine. It has four subclasses: InternalError, OutOfMemoryError,
StackOverflowError, and UnknownError.

The Exception Class

The Exception class provides a common superclass for the exceptions that can be defined for Java
programs and applets.

The Void Class

The Void class is used to reference the Class object representing the void type. It is provided for
completeness and is used for reflection. It has no constructors or methods.

- 155



Chapter Summary

This chapter covered the classes and interfaces of the java.lang package. It focused on the wrapped
classes, String and StringBuffer, and the Math class. It presented several examples of how these
classes are used. It also covered the Object, Class, System, and other important classes and
interfaces of java.lang. You should now be prepared to test your knowledge of these topics. The
following review questions and exam questions will let you know how well you understand this material
and will give you an idea of how you'll do in related exam questions. They'll also indicate which material
you need to study further.

Key Terms

.
Wrapped class
.. String
.. StringBuffer
.
Random number
.. Object
.. Class
.. Class loaded
.
Security manager
Review Questions

1. What are the Object and Class classes used for?
2. What are wrapped classes?
3. What is the difference between the String and StringBuffer classes?
4. Why are the methods of the Math class static?
5. Which class is extended by all other classes?
6. Which class should you use to obtain design information about an object?
7. What is the purpose of the Runtime class?
8. What is the purpose of the System class?
9. Which Math method is used to calculate the absolute value of a number?
10. What are E and PI?
Exam Questions

1. Which of the following are true?
A. The Class class is the superclass of the Object class.
B. The Object class is final.
C. The Class class can be used to load other classes.
D. The ClassLoader class can be used to load other classes.
2. Which of the following classes is used to perform basic console I/O?
A. System
B. SecurityManager
C. Math
D. Runtime
3. Which of the following is not a wrapper class?
A. String
B. Integer
C. Boolean
D. Character
4. What's wrong with the following code?
5. public class Question {
6. public static void main(String args[]) {
- 156



7. Boolean b = new Boolean("TRUE");
8. if(b) {
9. for(Integer i=0;i<10;++i) {
10. System.out.println(i);
11. }
12. }
13.
}
}
A. There is nothing wrong with the code. It compiles and runs fine.
B. The if condition should be a boolean instead of a Boolean.
C. The index of the for statement should be an int instead of an Integer.
D. It is illegal to construct a Boolean value.
14. Which of the following methods cause the String object referenced by s to be
changed?
A. s.concat()
B. s.toUpperCase()
C. s.replace()
D. None of the above
15. What is the output of the following program?
16. public class Question {
17. public static void main(String args[]) {
18. String s1 = "abc";
19. String s2 = "def";
20. String s3 = s1.concat(s2.toUpperCase());
21. System.out.println(s1+s2+s3);
22.
}
}
A. abcdefabcdef
B. abcabcDEFDEF
C. abcdefabcDEF
D. None of the above
23. Which of the following methods are methods of the Math class?
A. absolute()
B. log()
C. cosine()
D. sine()
24. Which of the following methods are methods of the String class?
A. delete()
B. append()
C. reverse()
D. replace()
25. Which of the following are true about the Error and Exception classes?
A. Both classes extend Throwable.
B. The Error class is final and the Exception class is not.
C. The Exception class is final and the Error class is not.
D. Both classes implement Throwable.
26. Which of the following are true?
A. The Void class extends the Class class.
B. The Float class extends the Double class.
C. The System class extends the Runtime class.
D. The Integer class extends the Number class.
- 157



Answers to Review Questions

1.
The Object class is the highest-level class in the Java class hierarchy. The Class
class is used to represent the classes and interfaces that are loaded by a Java program.
2.
Wrapped classes are classes that allow primitive types to be accessed as objects.
3.
String objects are constants. StringBuffer objects are not.
4.
So they can be invoked as if they are a mathematical code library.
5.
The Object class is extended by all other classes.
6.
The Class class is used to obtain information about an object's design.
7.
The purpose of the Runtime class is to provide access to the Java runtime system.
8.
The purpose of the System class is to provide access to system resources.
9.
The abs() method is used to calculate absolute values.
10. E is the base of the natural logarithm and PI is mathematical value pi.
Answers to Exam Questions

1.
C and D. The Object class is the highest-level class in the Java 2 API and therefore
cannot be a subclass of Class or final.
2.
A. System.in, System.err, and System.out support console I/O.
3.
A. There is no primitive string type to wrap.
4.
B and C.
5.
A and B. The toUpperCase() and concat() methods change their associated
String object.
6.
D. String objects are immutable and cannot be changed.
7.
B. The absolute() value method, cosine(), and sine() methods are abbreviated
abs(), cos(), and since().
8.
D A, B, and C. look like String methods, but they are not.
9.
A. Throwable is the superclass of both Error and Exception.
10. D.

No comments: