Essentials of the Java Programming Language

Text-only Preview

of the
Programming Language
Joan Krone
Thomas Bressoud
R. Matthew Kretchmar
Department of Mathematics and Computer Science
Denison University


Chapter 1
Learning a Language
Programming a computer is both a creative activity and a process structured by
rules. Computers are programmed or given instruction, through the use of pro-
gramming languages, so to program a computer, one must learn a programming
language. The goal of this book is to introduce a programming language called
Learning a programming language has similarities to learning a natural lan-
guage, such as English or Spanish or Japanese. Natural languages have a lexicon,
a syntax, and a semantics. The lexicon is the vocabulary and punctuation. The
rules of syntax dictate how the lexicon can be ordered to form correct sentences.
The semantics conveys the meaning when the chosen words are combined in the
chosen syntax of each sentence. The semantics changes, sometimes in subtle ways,
depending on both the words chosen and the sentence syntax.
So too, a programming language has lexical elements, a syntax, and a seman-
tics. The lexical elements are comprised of keywords in the programming lan-
guage, symbols such as arithmetic operators or parenthesis or braces, and words
denoting identi?ers by which we can name what is being operated upon. The
syntax speci?es precise rules for how the lexical elements are ordered to form cor-
rect language statements and programs. The semantics is the meaning of the con-
structed language statements. In this context, the meaning is operational, telling
the computer “what to do” as the statements are encountered, in a well de?ned
sequence, in the execution of the program.
Learning programming languages and learning natural languages share other
similarities. First, the typical method for learning a language is a spiral approach.

We start with a very limited vocabulary, a few simple syntactic constructs and their
semantics. We then build our repertoire, adding vocabulary, syntax, and semantics,
and often returning to previously covered topics. Second, mastering a language
takes practice through active participation. You should practice by repeating each
example and by working out the exercises and problems posed in the book. Finally,
memorization of example patterns is no substitute for understanding the semantics
associated with each syntactic structure. As the syntax changes, we must under-
stand the corresponding change in the semantics.
The Program and the Computer
Learning a programming language, and particularly learning your ?rst program-
ming language, is intimately tied with learning how a computer works. Under-
standing how a computer works involves understanding how numbers and charac-
ters and aggregate data may be encoded and stored in the memory of the computer,
and how the data stored in memory can be operated upon by the central processing
unit (CPU) executing millions of very simple instructions.
Programming languages such as Java, C, or C++ are known as high-level lan-
guages. They allow speci?cation of program instructions in a manner closer to
natural languages, but without the ambiguity and lack of precision. Computers,
on the other hand, are only capable of executing exceedingly primitive instructions
in a low-level language known as the computer’s machine language. We bridge
the gap by translating a high-level language into a low-level language through a
program known as a compiler.
Problem Solving through Programming
Programming is about solving problems. Regardless of the language used, this
activity proceeds through a set of well-de?ned stages during the development of
the program.
Design In the design stage, a careful problem statement is articulated, indicating
the desired outcomes of the program. The problem statement is then re?ned
by listing a set of steps designed to accomplish the goal. The set of steps is
called an algorithm, and may be presented in English or in some other ap-
propriate notation. The design stage does not require the use of a computer.
Edit In the edit stage, a program is created in a text editor and stored in one or
more ?les on disk. These ?les are known as the program source code.

Compile During the compile stage, the compiler translates the program source
code in the source ?le(s) into the machine code appropriate for the machine
on which the program will execute.
Execute The execute stage is the time when the compiled program is loaded from
disk into its execution environment and the machine carries out the instruc-
By its very nature as a human endeavor, problem solving is rarely completely suc-
cessful on the ?rst attempt. Some or all of the above phases may be revisited as we
re?ne and iterate toward a correct solution.
The above development description applies to any programming language, not
just Java. It is worthwhile to make some additional observations about program
development speci?c to Java.
The source code for a Java program are contained in text ?les with the
.java extension.
The Edit, Compile, and Execute stages of program development can some-
times be brought together in the context of a computer program known as an
Integrated Development Environment (IDE). Such IDEs vary in power and
facilities provided to the developer, and many are overkill for a student’s ?rst
introduction to a programming language. There are two Java IDEs that are
well suited to a new student, Dr. Java[1] and Blue J[2].
Many common programming subproblems have already been solved and it
is not necessary to build these again. For Java, an extensive set of libraries
is available and is part of the what is known as the Java Platform. The Java
Application Programming Interface
(API) de?nes the facilities available for
use from our Java programs.
Different hardware platforms, such as Intel x86, Mac G4/5, or SGI MIPS,
have different machine languages. For Java to be able to run without mod-
i?cation on multiple platforms, the Java platform includes a Java Virtual
(JVM). This is a computer program that simulates a machine that is
speci?c to Java. The machine code for the JVM is called bytecode and when
we compile a Java program, the compiler generates the bytecode and places
it in a ?le with a .class extension.
During the Execute stage, the class ?le for our program is loaded into the
JVM, and combined with the class ?les that realize the Java API.

The remainder of this chapter is a short tutorial, introducing you to a small
set of elements of the Java language. The intent is to give you an initial ?avor
of programming in Java without getting immersed in too many details and formal
rules. Think of it as your very ?rst increment of vocabulary, syntax, and semantics
of the language. The goal is to quickly get to the point where you can write simple,
but complete, programs. Subsequent chapters of the book will delve into all of the
elements touched upon here, and in much greater detail.
A Java Tutorial
This tutorial will lead you through a sequence of Java programs designed to intro-
duce some basic concepts of Java programming. We begin with an application to
print a welcome message.
Welcome Application
Your ?rst application, WelcomeApp, has the simple problem statement:
Print the string of characters “Welcome to Java Programming!” to a
text console window.
As we shall see, part of the Java system API includes a Java statement that allows
us to print strings of characters as output to the text console window. Thus we can
complete our design stage with a single step:
1. Print the string "Welcome to Java Programming!".
The following Java language code accomplishes the goal of our ?rst program. The
line numbers on the left are included only for our reference; they are not part of the
source program itself.
* The WelcomeApp class implements a simple application
* that prints a welcome message to the standard output.
public class WelcomeApp {

// The WelcomeApp class consists of a single method,
// namely the application entry method called ’main’.
public static void main(String[] args) {
// Invoke a system-provided method to
// print a String argument to standard output.
System.out.println("Welcome to Java Programming!");
Successful completion of the edit stage requires the creation of the source
code text ?le whose contents are the Java code given above. The ?le must end
in the .java extension and, due to requirements discussed later, must be named
The edit, compile, and execute stages may all be accomplished within the Dr. Java
Integrated Development Environment. First, you must launch the Dr. Java appli-
Depending on how Dr. Java was installed, there may exist a shortcut or
desktop icon that may be used to launch the application.
Once the application is launched, you will see three primary window panes in
the Dr. Java window. On the left side is the Files Pane, a pane that will display the
set of Java source ?les that are currently active in Dr. Java. Upon initial launch,
there are no active source ?les, and (Untitled) should appear in this window
pane indicating an empty unnamed Java source ?le is ready for entry of code. The
largest window pane, on the right, is the De?nitions Pane and displays the content
of a single active source ?le. Since we have not entered any Java code yet, this pane
will be empty. The window pane across the bottom of the application window starts
in the tab for Dr. Java Interactions, and is referred to as the Interactions Pane.
Click in the De?nitions Pane and enter the given Java code exactly as it appears
above (but without the listing line numbers). When you make modi?cations to a
source ?le, the condition of having an unsaved source ?le is indicated by a ‘*’ ap-
pearing next to the source ?le in the File Pane. As you type code in the De?nitions
Pane, you may note that parts of the code will be displayed in different colors. This
is called syntax highlighting and is used to show different parts of the vocabulary
of the Java language and their place in the syntax of the source ?le.

Once the Java code has been entered, the source ?le must be saved. This op-
eration writes the text source ?le out to the ?le system on the disk of the com-
puter. From the File menu, select the Save menu item. You can also click the
Save button on the button bar that appears underneath the Menu bar. This will
result in a Save dialog box. The ‘File Name’ and the ‘Files of Type’ items will
be ?lled in with “WelcomeApp” and “Java source ?les”. These are the correct
entries and should not be changed. This is specifying that the name of the ?le is Use the upper portion of the Save dialog box to navigate
to the folder/directory where you want the source ?le (and ultimately the bytecode
?le) to reside. Then click the Save button. Upon successful completion of the
save, the File Pane will change to
If you have successfully entered and saved the Java source code exactly as it ap-
pears, then the compile stage should be very straightforward. We only have to
specify the source ?le to the compiler, which will, without any further interaction,
generate the output bytecode ?le. Problems arise in the form of compiler errors
if typographical errors have resulted when the code was entered. If this occurs,
compare your code carefully with the given code; correct any errors, and retry the
compile step given below.
Ensure that appears and is highlighted in the Files Pane and
that the Java source code that you entered appears in the De?nitions Pane of the
Dr. Java application. This should be the current state of affairs following the Edit
stage. If Dr. Java had been closed after the Edit stage, you can return to this point
by selecting the Open menu item from the File menu and navigating to, and
opening, the source ?le from the prior step.
Compile the source ?le by clicking the Tools menu and selecting either the
Compile All Documents or the Compile Current Document menu
item1. During compilation, the bottom pane will switch to the “Compiler Output”
tab and display the message “Compilation in Progress, please wait ...”. If there
are no syntax errors, the completion of the compilation will be indicated by the
1These two are equivalent when there is a single ?le listed in the Files Pane. They differ when
more than one source ?le is active, and thus the Files Pane contains more than one entry.

message “Last compilation completed successfully” in the Compiler Output tab of
the bottom pane.
Now for the moment of truth. It is time to execute your ?rst Java program.
Again, ensure that the appears and is highlighted in the
Files Pane and that the Java source code that you entered appears in the De?nitions
Pane of the Dr. Java application. Now, from the Tools menu, select the Run
Document’s Main Method menu item. The bottom pane should change to
the “Interactions” tab, and you will see, at the ’  ’ prompt of the Interactions pane,
the following command:
java WelcomeApp
This should be followed by the output, "Welcome to Java Programming!"
in your console window. This is the result of the successful execution of your
Java program. Alternatively, you can click on the “Interactions” tab of the bottom
pane and manually type the java WelcomeApp command. When you press
Enter/Return, the program will execute and display the "Welcome to Java
Programming!" output.
A Closer Look at the WelcomeApp Java Code
Now for some explanation of the source code. This ?rst program exhibits four ele-
ments of the language: comments, class de?nition, method de?nition, and method
invocation. All four of these elements will be common to almost every Java pro-
A comment is free-form text that adds description to a program suitable for
helping a reader to understand what parts of the program are designed to do. Lines
1-4 together form a syntactic unit that is delimited at the beginning by the char-
acter sequence ‘/**’ and at the end by the character sequence ‘*/’. This de?nes
a multi-line comment in Java. Between the beginning of comment delimiter and
the end-of-comment delimiter, the programmer may type any sequence of charac-
ters available from the keyboard. Lines 7, 8, 12, and 13 are also Java comments,

but these are single-line comments. The comment begins with the the character
sequence ‘//’ and continues until the end of the current line. In this example, the
single line comments are the only element on the line, but this style of comment
is often used following some non-comment Java syntax and is used to explain the
Java on the line on which it resides.
Lines 6, 9, 11, and 13 are blank lines. The use of blank lines and the use of
indentation to show nesting of syntactic structures improves the readability of the
source code, but has no impact on the instructions that will be executed. Neatness
and readability count when we are writing programs.
The ability to cope with problems of any signi?cant size requires the ability to
organize and break a problem up into smaller, more manageable, subproblems. All
high-level languages have some facilities for accomplishing this, and in Java, the
fundamental facilities are the notions of a class and of a method. A method gathers
together a set of program steps that de?ne an action in the program. A class is a
collection of methods.
Line 5 begins the de?nition of the class named WelcomeApp. In that line
public and class are necessary Java keywords, WelcomeApp is providing
the name of the class, and the ‘ ’ is known as a delimeter that begins the contents
of the class. The ‘ ’ on line 17 is the corresponding closing delimeter ending the
class de?nition.
Line 10 begins the de?nition of the method named main. The keywords
public, static, and void are required syntax in the de?nition of this method,
as is the syntax ‘(String[] args)’ following main. Like de?ning a class,
the de?nition of a method delimits the beginning and end of its contents with the
symbols ‘ ’ and ‘ ’.
Every Java program must consist of at least one class, and there must exist a
method named main declared as we see on line 10. Chapters 8 and 9 will treat the
concepts of class and method in much greater detail.
Now that we have covered all the syntax providing the required structure of a
class de?nition for WelcomeApp and its main method de?nition, we are left with
a single statement, on line 15, whose execution actually accomplishes our goal.
System.out.println("Welcome to Java Programming!");
This Java statement is the invocation of the method System.out.println().
(Or, more simply, println()). A method invocation has the semantics of tem-
porarily suspending execution of the steps in the current method and executing
the steps de?ned in the invoked method. Once those steps are complete, execu-
tion continues in the current method at the point following the method invocation