Core Java Samples PDF
Core Java Samples PDF
1
The History and
Evolution of Java
To fully understand Java, one must understand the reasons behind its creation, the forces
that shaped it, and the legacy that it inherits. Like the successful computer languages that
came before, Java is a blend of the best elements of its rich heritage combined with the
innovative concepts required by its unique mission. While the remaining chapters of
this book describe the practical aspects of Java—including its syntax, key libraries, and
applications—this chapter explains how and why Java came about, what makes it so
important, and how it has evolved over the years.
Although Java has become inseparably linked with the online environment of the Internet,
it is important to remember that Java is first and foremost a programming language.
Computer language innovation and development occur for two fundamental reasons:
Java’s Lineage
Java is related to C++, which is a direct descendant of C. Much of the character of Java is
inherited from these two languages. From C, Java derives its syntax. Many of Java’s object-
oriented features were influenced by C++. In fact, several of Java’s defining characteristics
come from—or are responses to—its predecessors. Moreover, the creation of Java was deeply
rooted in the process of refinement and adaptation that has been occurring in computer
programming languages for the past several decades. For these reasons, this section reviews
the sequence of events and forces that led to Java. As you will see, each innovation in language
design was driven by the need to solve a fundamental problem that the preceding languages
could not solve. Java is no exception.
3
24 PART I The Java Language
Figure 2-1 Encapsulation: public methods can be used to protect private data.
If you wanted to describe a more specific class of animals, such as mammals, they would have
more specific attributes, such as type of teeth and mammary glands. This is known as a
subclass of animals, where animals are referred to as mammals’ superclass.
Since mammals are simply more precisely specified animals, they inherit all of the
attributes from animals. A deeply inherited subclass inherits all of the attributes from each
of its ancestors in the class hierarchy.
Inheritance interacts with encapsulation as well. If a given class encapsulates some
attributes, then any subclass will have the same attributes plus any that it adds as part of its
specialization (see Figure 2-2). This is a key concept that lets object-oriented programs grow
in complexity linearly rather than geometrically. A new subclass inherits all of the attributes
of all of its ancestors. It does not have unpredictable interactions with the majority of the rest
of the code in the system.
Chapter 2 An Overview of Java 25
Part I
Figure 2-2 Labrador inherits the encapsulation of all its superclasses.
Polymorphism
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to
be used for a general class of actions. The specific action is determined by the exact nature of
the situation. Consider a stack (which is a last-in, first-out list). You might have a program
that requires three types of stacks. One stack is used for integer values, one for floating-point
values, and one for characters. The algorithm that implements each stack is the same, even
though the data being stored differs. In a non–object-oriented language, you would be
required to create three different sets of stack routines, with each set using different names.
However, because of polymorphism, in Java you can specify a general set of stack routines
that all share the same names.
Chapter 2 An Overview of Java 35
Let’s look at another example. The following program uses a block of code as the target
of a for loop.
/*
Part I
Demonstrate a block of code.
y = 20;
In this case, the target of the for loop is a block of code and not just a single statement.
Thus, each time the loop iterates, the three statements inside the block will be executed. This
fact is, of course, evidenced by the output generated by the program.
As you will see later in this book, blocks of code have additional properties and uses.
However, the main reason for their existence is to create logically inseparable units of code.
52 PART I The Java Language
One last point: Although blocks can be nested, you cannot declare a variable to have the
same name as one in an outer scope. For example, the following program is illegal:
// This program will not compile
class ScopeErr {
class TypeInferenceAndInheritance {
In the program, a hierarchy is created that consists of three classes, at the top of which is
MyClass. FirstDerivedClass is a subclass of MyClass, and SecondDerivedClass is a
subclass of FirstDerivedClass. The program then uses type inference to create three
variables, called mc, mc2, and mc3 by calling getObj( ). The getObj( ) method has a return
type of MyClass (the superclass), but returns objects of type MyClass, FirstDerivedClass,
or SecondDerivedClass, depending on the argument that it is passed. As the output shows,
the inferred type is determined by the return type of getObj( ), not by the actual type of the
object obtained. Thus, all three variables will be of type MyClass.
Chapter 8 Inheritance 197
Part I
That is, Object is a superclass of all other classes. This means that a reference variable of
type Object can refer to an object of any other class. Also, since arrays are implemented as
classes, a variable of type Object can also refer to any array.
Object defines the following methods, which means that they are available in every object.
Method Purpose
Creates a new object that is the same as the object being
Object clone( ) cloned.
boolean equals(Object object) Determines whether one object is equal to another.
void finalize( ) Called before an unused object is recycled. (Deprecated
by JDK 9.)
Obtains the class of an object at run time.
Class<?> getClass( )
Returns the hash code associated with the invoking
int hashCode( )
object.
Resumes execution of a thread waiting on the invoking
void notify( )
object.
Resumes execution of all threads waiting on the invoking
void notifyAll( )
object.
Returns a string that describes the object.
String toString( )
Waits on another thread of execution.
void wait( )
void wait(long milliseconds)
void wait(long milliseconds,
int nanoseconds)
The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. You may
override the others. These methods are described elsewhere in this book. However, notice
two methods now: equals( ) and toString( ). The equals( ) method compares two objects. It
returns true if the objects are equal, and false otherwise. The precise definition of equality
can vary, depending on the type of objects being compared. The toString( ) method returns a
string that contains a description of the object on which it is called. Also, this method is
automatically called when an object is output using println( ). Many classes override this
method. Doing so allows them to tailor a description specifically for the types of objects that
they create.
One last point: Notice the unusual syntax in the return type for getClass( ). This relates
to Java’s generics feature, which is described in Chapter 14.
Chapter 11 Multithreaded Programming 275
Part I
Figure 11-1 Thread states
It is important to understand that a thread’s state may change after the call to getState( ).
Thus, depending on the circumstances, the state obtained by calling getState( ) may not
reflect the actual state of the thread only a moment later. For this (and other) reasons,
getState( ) is not intended to provide a means of synchronizing threads. It’s primarily used
for debugging or for profiling a thread’s run-time characteristics.
Part I
ob = o;
}
// Return ob.
T getOb() {
System.out.print("Gen's getOb(): " );
return ob;
}
}
Gen2(T o) {
super(o);
}
// Override getOb().
T getOb() {
System.out.print("Gen2's getOb(): ");
return ob;
}
}
System.out.println(iOb.getOb());
System.out.println(iOb2.getOb());
System.out.println(strOb2.getOb());
}
}
As the output confirms, the overridden version of getOb( ) is called for objects of type Gen2,
but the superclass version is called for objects of type Gen.
498 PART II The Java Library
class UseTrim {
public static void main(String[] args)
throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in, System.console().charset()));
String str;
if(str.equals("Illinois"))
System.out.println("Capital is Springfield.");
else if(str.equals("Missouri"))
System.out.println("Capital is Jefferson City.");
else if(str.equals("California"))
System.out.println("Capital is Sacramento.");
else if(str.equals("Washington"))
System.out.println("Capital is Olympia.");
// ...
} while(!str.equals("stop"));
}
}
Beginning with JDK 11, Java also provides the methods strip( ), stripLeading( ), and
stripTrailing( ). The strip( ) method removes all whitespace characters (as defined by Java)
from the beginning and end of the invoking string and returns the result. Such whitespace
characters include, among others, spaces, tabs, carriage returns, and line feeds.
Chapter 18 String Handling 501
In the first call to join( ), a space is inserted between each string. In the second call, the
delimiter is a comma followed by a space. This illustrates that the delimiter need not be just a
single character.
The second form of join( ) lets you join a list of strings obtained from an object that
implements the Iterable interface. Iterable is implemented by the Collections Framework
classes described in Chapter 20, among others. See Chapter 19 for information on Iterable.
Part II
Additional String Methods
In addition to those methods discussed earlier, String has many other methods. Several are
summarized in the following table:
Method Description
int codePointAt(int i) Returns the Unicode code point at the location specified by i.
int codePointBefore(int i) Returns the Unicode code point at the location that
precedes that specified by i.
int codePointCount(int start, int end) Returns the number of code points in the portion of the
invoking String that are between start and end–1.
boolean contains(CharSequence str) Returns true if the invoking object contains the string
specified by str. Returns false otherwise.
boolean contentEquals(CharSequence str) Returns true if the invoking string contains the same
string as str. Otherwise, returns false.
boolean contentEquals(StringBuffer str) Returns true if the invoking string contains the same
string as str. Otherwise, returns false.
static String format(String fmtstr, Returns a string formatted as specified by fmtstr.
Object ... args)
(See Chapter 20 for details on formatting.)
static String format(Locale loc,
Returns a string formatted as specified by fmtstr.
String fmtstr,
Object ... args) Formatting is governed by the locale specified by loc.
(See Chapter 20 for details on formatting.)
String formatted(Object .... args)
Returns a string formatted as specified by the invoking string
applied to args. (See Chapter 21 for details on formatting.)
String indent(int num)
When num is positive, indents each line in the invoking string
by num spaces. When num is negative, each line has num
leading white space characters deleted, if possible.
Otherwise,
when
the num is negative, leading white space is deleted until
first non-white space character is encountered. In all cases,
boolean isEmpty( ) including when num is zero, each line will end with a newline
character. Returns the resulting string.
Returns true if the invoking string contains no characters
and has a length of zero.
Chapter 19 Exploring java.lang 549
Trigonometric Functions
The following methods accept a double parameter for an angle in radians and return the
result of their respective trigonometric function:
Method Description
static double sin(double arg) Returns the sine of the angle specified by arg in radians.
static double cos(double arg) Returns the cosine of the angle specified by arg in radians.
static double tan(double arg) Returns the tangent of the angle specified by arg in radians.
Part II
The next methods take as a parameter the result of a trigonometric function and return,
in radians, the angle that would produce that result. They are the inverse of their non-arc
companions.
Method Description
static double asin(double arg) Returns the angle whose sine is specified by arg.
static double acos(double arg) Returns the angle whose cosine is specified by arg.
static double atan(double arg) Returns the angle whose tangent is specified by
static double atan2(double x, double y) arg. Returns the angle whose tangent is x/y.
The next methods compute the hyperbolic sine, cosine, and tangent of an angle:
Method Description
static double sinh(double arg) Returns the hyperbolic sine of the angle specified by arg.
static double cosh(double arg) Returns the hyperbolic cosine of the angle specified by arg.
static double tanh(double arg) Returns the hyperbolic tangent of the angle specified by arg.
Exponential Functions
Math defines the following exponential methods:
Method Description
static double cbrt(double arg) static Returns the cube root of arg. Returns e to the
double exp(double arg) static double arg. Returns e to the arg–1. Returns the natural
expm1(double arg) static double logarithm of arg. Returns the base 10 logarithm
log(double arg) static double for arg. Returns the natural logarithm for arg + 1.
log10(double arg) static double Returns y raised to the x; for example, pow(2.0,
log1p(double arg) static double 3.0) returns 8.0.
pow(double y, double x) Returns arg × 2factor.
Returns arg × 2factor.
static double scalb(double arg, int factor)
Returns the square root of arg.
static float scalb(float arg, int factor)
static double sqrt(double arg)
Chapter 21 java.util Part 2: More Utility Classes 691
Part II
Scanner
Scanner is the complement of Formatter. It reads formatted input and converts it into its
binary form. Scanner can be used to read input from the console, a file, a string, or any
source that implements the Readable interface or ReadableByteChannel. For example, you
can use Scanner to read a number from the keyboard and assign its value to a variable. As
you will see, given its power, Scanner is surprisingly easy to use.
The Scanner Constructors
Scanner defines many constructors. A sampling is shown in Table 21-14. In general, a
Scanner can be created for a String, an InputStream, a File, a Path, or any object that
implements the Readable or ReadableByteChannel interfaces. Here are some examples.
The following sequence creates a Scanner that reads the file Test.txt:
FileReader fin = new FileReader("Test.txt");
Scanner src = new Scanner(fin);
This works because FileReader implements the Readable interface. Thus, the call to the
constructor resolves to Scanner(Readable).
This next line creates a Scanner that reads from standard input, which is the keyboard
by default:
Scanner conin = new Scanner(System.in);
This works because System.in is an object of type InputStream. Thus, the call to the
constructor maps to Scanner(InputStream).
The next sequence creates a Scanner that reads from a string.
String instr = "10 99.88 scanning is easy.";
Scanner conin = new Scanner(instr);
Scanning Basics
Once you have created a Scanner, it is a simple matter to use it to read formatted input.
In general, a Scanner reads tokens from the underlying source that you specified when the
Scanner was created. As it relates to Scanner, a token is a portion of input that is delineated
by a set of delimiters, which is whitespace by default. A token is read by matching it with a
particular regular expression, which defines the format of the data. Although Scanner allows
708 PART II The Java Library
Table 21-18 Functional Interfaces Defined by java.util.function and Their Abstract Methods (continued)
834 PART II The Java Library
techniques needed to use the AWT. From there, you will be able to explore other parts of the
AWT on your own. You will also be ready to move on to Swing.
NOTE If you have not yet read Chapter 25, please do so now. It provides an overview of event handling, which
is used by many of the examples in this chapter.
AWT Classes
The AWT classes are contained in the java.awt package. It is one of Java’s largest packages.
Fortunately, because it is logically organized in a top-down, hierarchical fashion, it is easier to
understand and use than you might at first believe. Beginning with JDK 9, java.awt is part of the
java.desktop module. Table 26-1 lists some of the many AWT classes.
Although the basic structure of the AWT has been the same since Java 1.0, some of the
original methods were deprecated and replaced by new ones. For backward-compatibility,
Java still supports all the original 1.0 methods. However, because these methods are not for
use with new code, this book does not describe them.
Class Description
AWTEvent Encapsulates AWT events. Dispatches events to multiple listeners. The
AWTEventMulticaster border layout manager. Border layouts use five components: North,
B orderL ayout South, East, West, and Center.
Creates a push button control.
Button A blank, semantics-free window.
Canvas The card layout manager. Card layouts emulate index cards. Only the one
C ardL ayout on top is showing.
Creates a check box control.
Checkbox Creates a group of check box controls.
CheckboxGroup Creates an on/off menu item.
C he ckb oxMenuItem Creates a pop-up list.
Choice Manages colors in a portable, platform-independent fashion.
Color An abstract superclass for various AWT components.
Component A subclass of Component that can hold other components.
Container Encapsulates a bitmapped cursor.
Cursor Creates a dialog window.
Dialog Specifies the dimensions of an object. The width is stored in width, and
the height is stored in height. Queues events. Creates a window from which
Dimension
a file can be selected.
EventQueue
FileDialog