Chapter 1 -- An Overview of Java
Chapter 1
An Overview of Java
CONTENTS
If you have purchased this book, you are probably planning to
program with Java. There are many reasons for using Java as your
programming language. You might want to learn an object-oriented
programming language, and maybe you've heard that Java is simple
to use. You might have come across some interesting applets while
browsing the Internet (if you're using a Java-capable browser),
and perhaps you want to learn to write applets of your own and
add them to your Internet or intranet HTML documents. You might
want to learn how to add Internet functionality to your C applications
or how to use Java to write full-fledged applications that are
portable. This book helps you accomplish any and all of these
goals.
This overview introduces the many features of Java and explains
why they are important to you, the Java programmer. It is worthwhile
for you to understand the richness and usefulness of Java before
getting into the specifics of the Java environment and language.
Java is an interpreted language that is similar, superficially,
to C++, but different in many important ways. Java was originally
intended to be an extension of the C compiler but has been completely
rebuilt from the ground up to be a smaller, portable, purely object-oriented
language that eliminates many of the sources of bugs and complexities
common in C++.
Java has been around since 1991, developed by a small team of
Sun Microsystems developers in a project originally called the
Green project. The intent of the project was to develop a platform-independent
software technology that would be used in the consumer electronics
industry. The language that the team created was originally called
Oak.
The first implementation of Oak was in a PDA-type device called
Star Seven (*7) that consisted of the Oak language, an operating
system called GreenOS, a user interface, and hardware. The name
*7 was derived from the telephone sequence that was used in the
team's office and that was dialed in order to answer any ringing
telephone from any other phone in the office. This PDA-type device
was intended to be sold to consumer electronics manufacturers
who would distribute the boxes under their company name. In 1993,
the team, then incorporated as FirstPerson, Inc., decided to gear
their technology toward a new implementation for which demand
was building in the entertainment industry-interactive television.
They proposed their technology to Time Warner as an operating
system for set-top boxes and video-on-demand technology that would
decode the data stream that Time Warner would be sending to television
sets around the country. In June of 1993, Time Warner selected
Silicon Graphics' technology over Sun's. A later deal fell apart
and FirstPerson decided to disband. Half of the members of the
original FirstPerson team continued to work with the Oak technology,
however, applying it to multimedia and network computing.
Around the time the FirstPerson project was floundering in consumer
electronics, a new craze was gaining momentum in America; the
craze was called "Web surfing." The World Wide Web,
a name applied to the Internet's millions of linked HTML documents
was suddenly becoming popular for use by the masses. The reason
for this was the introduction of a graphical Web browser called
Mosaic, developed by ncSA. The browser simplified Web browsing
by combining text and graphics into a single interface to eliminate
the need for users to learn many confusing UNIX and DOS commands.
Navigating around the Web was much easier using Mosaic.
It has only been since 1994 that Oak technology has been applied
to the Web. In 1994, two Sun developers created the first version
of HotJava, then called WebRunner, which is a graphical browser
for the Web that exists today. The browser was coded entirely
in the Oak language, by this time called Java. Soon after, the
Java compiler was rewritten in the Java language from its original
C code, thus proving that Java could be used effectively as an
application language. Sun introduced Java in May 1995 at the SunWorld
95 convention.
Web surfing has become an enormously popular practice among millions
of computer users. Until Java, however, the content of information
on the Internet has been a bland series of HTML documents. Web
users are hungry for applications that are interactive, that users
can execute no matter what hardware or software platform they
are using, and that travel across heterogeneous networks and do
not spread viruses to their computers. Java can create such applications.
On the Internet, Java programs are called applets. Applets are
Java applications that are embedded inside HTML files and can
be downloaded into a Java-capable browser with the click of a
mouse. Applets are different from regular Java applications. A
Java application simply has a single main()
method that indicates to the Java runtime system that it is an
application. A Java applet is an application that includes several
additional methods that the runtime system uses that tell it how
to handle the applet, such as what to do when a user clicks an
applet icon and how it looks on a page.
Before your browser's runtime Java interpreter downloads and executes
the applet's code, the Java interpreter verifies the code's integrity.
Java is more than a tool to help you write applets, however. It
is a new, powerful programming environment.
Sun describes Java as a "simple, object-oriented, interpreted,
robust, secure, architecture-neutral, portable, high-performance,
multithreaded, and dynamic language."
Each of the features mentioned in this quotation from Sun's Web
page is an important part of the Java development environment
as well as a critical requirement for Web programming. The combination
of these features makes Java a powerful and useful programming
language that empowers you, the programmer, with the tools you
need to easily create powerful programs for today's distributed
environments.
Java is simple to use for three main reasons: First, Java is familiar
to you if you know C. Second, Java eliminates components of C
that cause bugs and memory leaks and replaces their functionality
with more efficient solutions and automated tasks, so you have
a lot less debugging to worry about than you would using C or
C++. Third, Java provides a powerful set of pre-tested class libraries
that give you the ability to use their advanced features with
just a few additional lines of code.
Java is an object-oriented programming language that uses software
objects called classes and is based upon reusable, extensible
code. This means that you can use Java's classes, which are sets
of variables and methods, as templates to create other classes
with added functionality without rewriting the code from the parent
classes or superclasses. If you plan your application's class
hierarchy well, your application will be small and easy to develop.
The hierarchy of classes is explained later in this chapter.
Java is robust because the language removes the use of pointers
and the Java runtime system manages memory for you. The problems
with pointers in C and C++ was that pointers directly addressed
memory space. In a distributed environment like the Internet,
when code is downloaded to diverse systems, there is no way of
knowing for sure that memory space addressed by pointers is not
occupied by the system. Overwriting this memory space could crash
a system. Java also gives you automatic bounds checking for arrays,
so they cannot index address space not allocated to the array.
Automatic memory management is done using the Garbage Collector,
which is explained in detail in Chapter 4, "Creating Your
Own Objects."
Java is interpreted, so your development cycle is much faster.
As you learn later when the Java interpreter is discussed, you
need only to compile for a single, virtual machine and your code
can run on any hardware platform that has the Java interpreter
ported to it.
Java is secure, so you can download Java programs from anywhere
with confidence that they will not damage your system. Java provides
extensive compile-time checking, followed by a second, multilayered
level of runtime checking. Java's security structure is described
in detail in Chapter 19, "Security
Issues."
Java is architecture neutral, so your applications are portable
across multiple platforms. Java's applications are written and
compiled into bytecode for Java's virtual machine, which emulates
an actual hardware chip. Bytecode is converted to binary machine
code by the Java interpreter installed at the client, so applications
need not be written for individual platforms and then ported from
platform to platform. Java additionally ensures that your applications
are the same on every platform by strictly defining the sizes
of its basic data types and the behavior of its arithmetic operators.
Operator overloading, the process of modifying the behavior of
operators, is prohibited by Java.
Java is "high performance" because its bytecode is efficient
and has multithreading built in for applications that need to
perform multiple concurrent activities. Although threads still
require the use of classes, Java balances the addition of thread
synchronization between the language and class levels. Java's
bytecode is efficient because it is compiled to an intermediate
level that is near enough to native machine code that performance
is not significantly sacrificed when the Java bytecode is run
by the interpreter.
Java is dynamic, so your applications are adaptable to changing
environments because Java's architecture allows you to dynamically
load classes at runtime from anywhere on the network, which means
that you can add functionality to existing applications by simply
linking in new classes. For example, if your applet is being run
by a browser that doesn't have one of the classes included in
your applet's bytecode, the browser can download the appropriate
class from the server that is storing your applet, check the bytecode,
and execute it. This is assuming your browser has not been configured
with strict security. Chapter 19 covers
browser security.
This chapter introduces you to the basic concepts and functions
of the Java programming language and gives you brief examples
to illustrate important points. The later, more advanced chapters
guide you through extensive samples of code, and so the examples
in this chapter are short. By the end of this chapter, you should
have a basic understanding of the Java language and be ready to
explore in detail Java's class libraries in Chapter 3,
"An Introduction to Java Classes."
Java programming will be fairly easy for you if you have had experience
with C++ because Java is designed to look and feel like C++. If
you are an experienced C programmer, you will have to let go of
some old habits to program Java, however, as you will discover
later in this chapter. Please do not be concerned if you have
little or no experience in programming-this book assumes no prior
knowledge of C++. You may need to read through the chapters more
slowly and carefully than an experienced programmer.
Java's class structure is made up of the following major components:
classes, hierarchy, variables, methods, and inheritance.
The key to understanding Java's object-oriented design is understanding
what classes are and what you can do with them. Classes are templates
that you use to create actual objects. The instructions contained
in a class are used to create one or more objects, which can be
called instances of classes in Java. When you create an
object from a class, you instantiate the object, which
means you create an instance of the class. The words instances
and objects are used interchangeably throughout the discussions
of classes in this book, depending on the context of the sentence
in which they're used.
In object-oriented programming, you can think of an object as
you would any real-world object, for example, a rectangle. The
actual rectangle would be an instance of the class Rectangle.
A very rudimentary declaration of a class is as follows:
class classname {
//class instructions
}
The instructions in a class are made of two basic components:
variables that hold data, and methods that manipulate the data.
Before you begin creating the classes in your application, you
must design the class structure. Java's class structure is organized
into a hierarchy.
Classes are organized into a hierarchy to allow you to easily
reuse code. When you write a Java program, first determine which
objects you'll need to use in your code. Then determine what variables
and methods the object's class must store. When you know what
instructions your classes contain, plan your hierarchy.
Without planning your hierarchy first, you would begin creating
a class for each object individually and undoubtedly would find
that you are repeating instructions from class to class. In a
hierarchy, instructions common to groups of objects are separated
out in parent classes, or superclasses, and can be used
by all of their subclasses. Therefore, when you plan your
hierarchy, you would group objects by the instructions that they
have in common and organize them into a hierarchy.
Superclasses are used as templates to create subclasses with variables
and methods that make each subclass unique. Each superclass can
be a parent to one or many other subclasses. Unlike in C++, a
subclass can have only one superclass. Therefore, the Java class
hierarchy looks something like the one shown in Figure 1.1.
Figure 1.1: Java class hierarchy.
If a superclass is not defined when a class is declared, the class
is automatically made a subclass of Java's Object
class. Every class in a Java program is a descendant of Object.
Object itself has no superclass.
Classes store information that describe objects in instance
variables. When objects are created from a class, they contain
new instances of the class' variables. These instance variables
can have values that are different from one object to the next.
Values of instance variables are called data. When an instance
variable's data is changed, it affects only the individual object.
There is a way in Java to assign a variable to a class that, if
changed, is changed in all instances of the class. Such a variable
is called a static variable, which you learn about later
in this chapter in the section called "Static Methods and
Variables."
The basic declaration statement of a variable is this:
datatype
variablename;
Two variables that might be declared for a rectangle are length
and width. They could be
declared in one line because they have the same data type. (You
explore data types in Table 1.1 of this chapter.) Their declaration
statement might be this:
int length, width;
If you created an object from a class with only these two variables
declared, the object would simply hold this data. It would not
know to draw lines with these values to form a rectangle. Methods
must be declared to use the data in variables.
Methods are functions that must be associated with individual
classes. In C and C++ and other procedural languages, functions
can be placed anywhere in the code. In Java, they must be stored
within classes. Instances of methods are created when instances
of classes are created. Unlike variables, methods are not duplicated
in objects-their code is stored only in the class.
When an object's method is invoked from its class, it uses the
data of variables in the object.
Every method returns a value if it is not declared as void.
To declare a method, you use the following statement:
returntype methodname (parameter
list) {
//method code
}
At this point in the chapter, you won't get into coding the method
that draws the rectangle. After you've learned the basic coding
elements of Java later in this chapter, exercises in coding methods
will be more useful.
Variables and methods that are stored in classes in the class
hierarchy are inherited by subclasses, so you do not need to re-create
them. Objects created from a subclass will contain not only the
instances of the variables and methods of the subclass, but also
its superclass' variables and methods, as well as those of the
parent of its superclass, and so on. When a variable or method
is referenced in an object, it is retrieved in a specific order:
Java first searches for it in the current class, then, if it is
not found, it searches the parent class, and so on.
In summary, objects in your Java program are created from classes
that contain variables and methods to describe the object. Classes
are organized into a hierarchy in which classes inherit functionality
from parent classes, which allows for reusable code. These basic
concepts of the structure of Java's object-oriented programming
language will become clearer to you as you read through the rest
of the sections.
Your Java code is used to create classes, objects, interfaces,
and packages. You'll learn how to create each of these in Chapter 4.
This section outlines the elements of the code you need to use
to create them.
Your code is written in a series of statements, which can be organized
into blocks. These statements contain data and operators, which
are components of expressions. You can annotate your code using
comments, which makes the code more understandable.
Any line of code before a semicolon is known as a statement
and is executed by the Java interpreter when it hits the semicolon;
after executing that statement, the interpreter moves to the next
statement. Each statement contains instructions for using data
and operators.
An expression is a part of a statement that uses data and
operators to return a value.
A block is a collection of statements enclosed in curly
braces. Any variables that you declare and that assign values
within a block are erased when the flow of execution leaves the
block. The block in which the variable's value exists is called
the scope of the variable.
Comments are used to annotate the code so that a reader can understand
the purpose of certain lines and blocks of code. Comments are
ignored by the Java compiler. Multiline comments are preceded
by /* and are ended with
*/. Single line comments
are preceded by //. The double
slash "comments out" text only to the end of a line.
A comment would appear as follows:
/* This declares the length
variable for the Rectangle class */
int length;
or
int length; //Declares
the length variable for the Rectangle class
To represent data values in your code you use literals.
Literals are described by types, named by identifiers, and stored
in variables, which were outlined earlier in the chapter and are
explored further in this section.
When you use literals in your code, they appear in their raw form
rather than as a result of an expression. Several types of literals
are commonly used: numbers, integers, floating points, characters,
Booleans, and strings.
Table 1.1 outlines Java's strict definitions of these data types.
Table 1.1. Rules for Java literals.
Literal Type | Typename
| Rule |
Number | Num
| Can_ be integer, floating point, or character.
|
Integer | | Can be decimal, hexadecimal, or octal.
|
| Byte
| 8-bit integers between -128 and 127. |
| Short
| 16-bit integers between -32768 and 32767. |
| Int
| 32-bit integers between -2147483648 and 2147483647.
|
| Long
| 64-bit integers between -9223372036854775808 and 9223372036854775807 or have L or l appended to them.
|
| Hex
| Preceded by 0x or 0X. |
| Oct
| Preceded by 0. |
Floating point | | Any number with a decimal point. Can be made exponential by appending an e or E, followed by the exponent.
|
| Float
| 32-bit. |
| Double
| 64-bit. |
Character | Char
| 16-bit integers represented by a single character and enclosed in single quotes.
|
| | In Java, the Unicode character map is used. The following special characters must be represented by escape sequences:
|
| | backspace b
|
| | backslash \
|
| | carriage return r
|
| | double quote "
|
| | formfeed f
|
| | hex number xhh
|
| | horizontal tab t
|
| | newline n
|
| | octal number | |