Fundamentals Of Java Programming Ogihara Mitsunori instant download
Fundamentals Of Java Programming Ogihara Mitsunori instant download
Mitsunori download
https://ebookbell.com/product/fundamentals-of-java-programming-
ogihara-mitsunori-21896840
https://ebookbell.com/product/fundamentals-of-java-programming-
mitsunori-ogihara-59047274
https://ebookbell.com/product/learn-java-17-programming-learn-the-
fundamentals-of-java-programming-with-this-updated-guide-with-the-
latest-features-2nd-ed-2nd-edition-nick-samoylov-44467076
https://ebookbell.com/product/java-17-for-absolute-beginners-learn-
the-fundamentals-of-java-programming-2nd-edition-iuliana-
cosmina-48643530
https://ebookbell.com/product/java-projects-learn-the-fundamentals-of-
java-11-programming-by-building-industry-grade-practical-projects-2nd-
edition-peter-verhas-22964872
Java Projects Learn The Fundamentals Of Java 11 Programming By
Building Industry Grade Practical Projects 2nd Edition Verhas
https://ebookbell.com/product/java-projects-learn-the-fundamentals-of-
java-11-programming-by-building-industry-grade-practical-projects-2nd-
edition-verhas-55588322
https://ebookbell.com/product/java-for-beginners-a-complete-guide-to-
learn-the-fundamentals-of-java-and-start-programming-today-megane-
noel-47526100
https://ebookbell.com/product/fundamentals-of-java-4th-edition-
kenneth-lambert-martin-osborne-4336886
https://ebookbell.com/product/fundamentals-of-computer-science-using-
java-1st-edition-david-hughes-1021582
https://ebookbell.com/product/fundamentals-of-computer-graphics-with-
java-opengl-and-jogl-david-j-eck-50195618
Mitsunori Ogihara
Fundamentals
of Java
Programming
Fundamentals of Java Programming
Mitsunori Ogihara
Fundamentals of Java
Programming
123
Mitsunori Ogihara
Department of Computer Science
University of Miami
Miami, FL, USA
This Springer imprint is published by the registered company Springer Nature Switzerland AG
The registered company address is: Gewerbestrasse 11, 6330 Cham, Switzerland
To my family
Preface
This book was born from the desire of having an introductory Java programming textbook whose
contents can be covered in one semester. The book was written with two types of audience in mind:
those who intend to major in computer science and those who want to get a glimpse of computer
programming. The book does not cover graphical user interfaces or the materials that are taught in a
data structure course. The book very quickly surveys the Java Collection Framework and the generics
in the penultimate chapter. The book also covers the concepts of online and recursive algorithms in
the last chapter. The instructors who choose to use this textbook are free to skip these chapters if
there is no sufficient time. Except for the code examples that receive parameters from the command
line, the code examples can be compiled and run in a command-line environment as well as in IDEs.
To execute those code examples in an IDE, the user must follow the step of provide args before
execution. The code examples appearing in the book have very few comments, since the actions of
the code are explained in the prose. The code examples with extensive comments are available for the
publisher. There are PDF lecture slides accompanying the book. They are prepared using the Beamer
environment of LATEX. The source codes of the lecture slides may be available through the publisher.
Acknowledgements I would like to take this opportunity to thank those who helped me in
writing this book: Paul Drougas (Springer), Victor Milenkovic (University of Miami), Ted Pawlicki
(University of Rochester), Ken Regan (University at Buffalo), Geoff Sutcliffe (University of Miami),
and Osamu Watanabe (Tokyo Institute of Technology). Huge thanks go to my daughter Ellen, who
painstakingly read through the draft and provided constructive criticisms.
vii
Contents
1 “Hello, World!” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1 The Programming Environment for Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.1 The Java Virtual Machine (JVM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.2 Changing Folders in a Command Line Interface . . . . . . . . . . . . . . . . . . . . . . 4
1.1.3 Source Codes, Bytecodes, and Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2 The First Program, “Hello, World!” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.2.1 Methods and Their Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.2.2 System.out.println and System.out.print . . . . . . . . . . . . . . . . 10
1.2.3 Spacing in the Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.2.4 Commenting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.2.5 Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.3 Using Multiple Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.3.1 System.out.println and System.out.print (Reprise) . . . . . . . 15
1.3.2 Printing Multiple-Line Texts on the Screen . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.3.3 Escaping Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.3.4 Printing Shapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2 Using Data for Computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.1 Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.1.1 Data and Their Taxonomy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.1.2 Number Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.1.3 Variable Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.1.4 Assigning Values to Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.2 The Primitive Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.3 Using Variables for Computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
2.3.1 Quarterbacks Program (Reprise) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
2.3.2 Number Arithmetics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.3.3 Computing the Body-Mass Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
2.3.4 Sum of Integers from 1 to 100 à la Gauss . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
2.3.5 Simplified Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
2.4 An Introduction to the String Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
2.4.1 The String Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
2.4.2 String Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
ix
x Contents
Part II Loops
7 For-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
7.1 Using For-Loops for Repetition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
7.2 Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
7.2.1 Simple Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
7.2.2 Iteration with an Auxiliary Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
7.3 Double For-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
7.4 Computing the Maximum and Minimum in a Series of Numbers . . . . . . . . . . . . . . . . 193
7.5 A Betting Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
7.5.1 For-Loops with Skipped Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
7.5.2 The Statements continue and break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
7.6 Computing the Fibonacci Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
8 Formatted Printing Using printf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
8.1 General Rules for printf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
8.2 Formatted Printing of String Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
8.3 Formatted Printing of Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Contents xi
12 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
12.1 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
12.1.1 The Structure of an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
12.1.2 Computing the Number of Occurrences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
12.1.3 ArrayIndexOutOfBoundsException . . . . . . . . . . . . . . . . . . . . . . . . . 303
12.2 Relative Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
12.2.1 The Concept of Relative Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
12.2.2 Calculating the BMI for a Range of Weight Values . . . . . . . . . . . . . . . . . . . . 306
12.2.3 Counting the Occurrences of Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
12.3 Arrays of boolean Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
12.4 Using Multiple Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
12.5 String Methods That Return an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
xii Contents
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
List of Figures
xv
xvi List of Figures
Fig. 13.8 The concept of a array with capacity and size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
Fig. 19.1 The value passing that occurs during the computation of the factorial (part 1) . . 495
Fig. 19.2 The value passing that occurs during the computation of the factorial (part 2) . . 495
Fig. 19.3 The value passing that occurs during the computation of the factorial (part 3) . . 495
Fig. 19.4 The value passing that occurs during the computation of the factorial (part 4) . . 495
Fig. 19.5 The value passing that occurs during the computation of the factorial (part 5) . . 495
Fig. 19.6 The value passing that occurs during the computation of the factorial (part 6) . . 496
Fig. 19.7 The value passing that occurs during the computation of the factorial (part 7) . . 496
Fig. 19.8 The value passing that occurs during the computation of the factorial (part 8) . . 496
Fig. 19.9 The value passing that occurs during the computation of the factorial (part 9) . . 496
Fig. 19.10 The value passing that occurs during the computation of the factorial (part 10) . 496
Fig. 19.11 The value passing that occurs during the computation of the factorial (part 11) . 497
Fig. 19.12 An example of the tower of Hanoi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
Fig. 19.13 The solution to a small Tower of Hanoi problem . . . . . . . . . . . . . . . . . . . . . . . . . . 502
List of Tables
Table 10.1 The output generated by the three examples of switch . . . . . . . . . . . . . . . . . . . 246
xvii
Part I
Programming Basics
“Hello, World!”
1
Java is one of the most popular programming languages. It is a descendant of the programming
language C and is much related to C++. Java, like C++, embodies the concept of object-oriented
programming, which allows a programmer to define a type of data with its permissible set of
operations.
To execute a Java program on a machine, the machine needs an installation of the Java Running
Environment (JRE). A major part of JRE is the Java Virtual Machine (JVM). JVM creates an
environment where Java programs interact with the hardware.
A programmer creates a Java program by writing its source code. A source code is a text file that
describes the program according to the syntax of Java and has the file name extension .java. An
executable Java program generated from a source code is called Java bytecode, and has the file
name extension .class. To generate a Java program from a source code, the machine needs an
extension of JRE called the Java Development Kit (JDK) (see Fig. 1.1).
The Java language that comes with JDK consists of two parts. The first part, called java.lang,
is an essential component of Java. The second part is a collection of source codes that can be selected
and added to the Java program being written.
To write and edit a Java source code, a text editor is needed. Some editors understand the syntax of
Java and offer a variety of assistance. Popular text editors, which can be used for editing general text,
include: vim, emacs, and sublime.
The process of generating Java bytecode from a Java source code is called compilation. A primitive
way to compile a Java source code is to execute a compilation command in a command line interface.
Modern computers usually come with command line interfaces. For example, Mac OSX has Terminal
and Windows has cmd. There are other downloadable command line interfaces. A command line
interface is a program that interacts with the user on a text screen (see Fig. 1.2). The user types,
according to the syntax of the command line interface, a character sequence representing an action
he/she wishes to take. This sequence is called a command or a command line. On the interface screen,
the characters that the user types appear (or “echo”) as they are being typed. After completing the
command, the user hits the return key. The command line interface then attempts to parse the entered
Operating
System
Operating System
Layer
Hardware
Hardware Program
Programs Layer
Hardware
command according to its syntax. If the command is syntactically correct, the interface executes the
action represented by the command. When the action occurs, some characters may appear on the
screen after the command line. If there are many such characters, the text screen scrolls down to show
however many characters will fit on the screen, starting with the most recent. If the command is not
syntactically correct, the command line interface prints an error message. To inform the user that it is
ready to accept a new command, the command line interface prints a special sequence of characters,
called prompt, e.g., the “percent” symbol % followed by one white space, or the “greater than” symbol
>. Table 1.1 is a select list of commands.
An interactive development environment (IDE) is a program that combines a program editor and a
command line interface with many additional features that make it easy to write (in particular, large)
computer programs (see Fig. 1.3). The most famous IDEs for Java are Eclipse and Netbeans.
A command line interface (such as the program Finder for Mac and the program Folder for Windows)
works in one specific file folder. The specific folder is called the working folder (or the working
directory). In Finder and Folder, switching to a different folder is done by clicking icons. In a
1.1 The Programming Environment for Java 5
Table 1.1 A short list of commands available in the Terminal programs for Mac OSX and Linux, as well as their
counterparts in the Windows cmd
Terminal cmd Function
(Mac OSX/Linux) (Windows)
cd FOLDER cd FOLDER Change folder to FOLDER
cd cd Change to the home folder
cd .. cd .. Change to the parent folder
pwd chdir Print the working folder
ls dir Listing of all files in the folder
ls FILE ls FILE Listing of FILE in the folder
rm FILE del FILE Remove the file FILE
rmdir FOLDER del FOLDER Remove the folder FOLDER (must be empty)
mv FILE1 FILE2 move FILE1 FILE2 Rename FILE1 to FILE2
cp FILE1 FILE2 copy FILE1 FILE2 Copy FILE1 to FILE2
mkdir FOLDER mkdir FOLDER Create the folder FOLDER
cat FILE type FILE Show the contents of FILE
more FILE more FILE Show the contents of FILE in chunks
command line interface, this switch is made by typing a special command. The name of the command
is cd (which stands for “change directory”). The syntax of cd is:
cd FOLDER_PATH
6 1 “Hello, World!”
Here, FOLDER_PATH specifies how to get to the target folder from the working folder. In Chap. 15,
we study the general concept of file paths.
The folder moves are composed of two basic moves: moving to one of the folders that belong to
the present folder or moving to the parent (that is, the folder that the working folder belongs to as a
subfolder). To move to a child folder, the path that is specified is this child folder’s name. To move to
the parent, the path that is specified is .. (i.e., two periods).
It is possible to combine successive folder moves into one path. For a non-Windows system like
Mac OSX and Linux, this is done by inserting / between the individual moves. For Windows, \ is the
folder separator. For example, in Mac OSX,
cd ../foo/bar
changes the working folder to the parent, to a child of the parent named foo, and then to a child of
the child named bar. bar is thus a grandchild folder of the parent of the present working folder.
To check what the working folder directly is, the command pwd can be used for a non-Windows
system, and chdir for Windows. These commands print the path to the working folder, starting from
the “home” folder on the screen. It is also possible to take the inventory of the files in the working
folder using the command ls for a non-Windows system, and dir for Windows. This command
produces a list of all the files in the working folder.
As mentioned earlier, all Java source files must have the file name extension .java. We call them
Java files. To compile the source code Foo.java in a command line interface, one must type the
command:
javac Foo.java
If the source code compiles without error, a file named Foo.class is created. This is the bytecode
of the program. We call it a class file. If the class file already exists, then the file is overwritten
upon successful compilation. In the case of IDE, .class files are generated only during the
execution process. If Foo.java has compiled successfully, the program can be executed by using
the command:
java Foo
after the prompt.
Here is an example of a user interaction with a command line interface, where the user tries to
compile and then execute a program whose source code is HelloWorld.java (Fig. 1.4). The
prompt of the command line interface is the percent symbol followed by one white space. The first
line is the compilation command, the second line is the execution command, the third line is the result
of executing the code, and the fourth line is the command prompt after the execution.
Let us start writing Java programs. Our first program is the popular Hello, World! program.
Using this code, we shall learn some important ingredients of Java programs.
The three words in the first line:
public class HelloWorld
state that:
There are four kinds of program units: class, interface abstract class, and enum. This
book covers class and interface only.
The keyword public specifies that the unit is accessible from other program units. A keyword
that specifies the accessibility of program units and their components is called a visibility attribute.
There are three explicit visibility types: public, private, and protected. The default visibility
type, when there is no explicit visibility attribute, is the package visibility.
The order of appearance of the three components,
VISIBILITY_TYPE UNIT_TYPE NAME
applies to all Java source code files.
Every source file in Java has the file extension .java. In a single .java file, multiple classes
can be defined, simply by concatenating their source codes. In such a case, at most one class may be
public. In addition, if a source file contains a unit with the public visibility, the name of the unit
must match the file name. For example,
1 class Foo
2 {
3 ...
4 }
5 class Bar
6 {
7 ...
8 }
is okay, but
8 1 “Hello, World!”
is not.
attempting to compile the source code (that is, the command javac HelloWorld.java)
produces the following error message:
The first two lines of the error message state the nature of the error, which is that, to define a class by
the name of Hello, the file name must be Hello.java. The next three lines of the error message
specify the location of the error using the “caret” symbol ^. According to the marking, the error is
at the class declaration. The last line of the error message is the total number of errors found in the
source code.
If the source file name HelloWorld.java is retained but the public attribute is removed, like
this one:
1.2 The First Program, “Hello, World!” 9
1 class Hello
2 {
3 public static void main ( String [] args )
4 {
5 System . out . println ( " Hello , World ! " ) ;
6 }
7 }
the code compiles, but the .class generated is Hello.class, not HelloWorld.class.
In Java, curly brackets { } are used to enclose units, components, and code blocks. For example, the
declaration of each program unit (such as class and interface) should be followed by a matching pair
of curly bracket. Two matching pairs appear either one after the other or one inside the other; that is,
either { ... { ... } ... } or { ... } ... { ... }
For a source file to compile successfully, all of its curly brackets must have unique matching partners.
Thus, the depth of a text in a source code can be defined as the number of matching pairs enclosing
it. Multiple methods may appear in one source code.
In the source code of HelloWorld.java, the opening line public class HelloWorld
is at depth 0, public static void main( String[] args ) is at depth 1, and
System.out.println( ... ) is at depth 2. The component appearing between lines 3 and 6
is called a method.
A method has a name and defines a set of actions needs to be performed. Some methods process
information given to the in the form of parameters. Some methods report the results through the use
of return values. We cover this topic in Chap. 5.
A special kind of method is the method main. Each method main takes the form of:
public static void main( String[] args )
as its declaration. The term args appearing in the parentheses represents the sequence of characters
that the user types in the command line after the name of the program. We study args in Sect. 13.4.
Only Java classes with a method main can be executed.
The general method declaration consists of the following, where the parts in boxes are optional.
In the case of the method main, the attribute public states that the method is accessible from
outside, the attribute static states that the method is part of some executable program, the return
type void states that the method has no return value, and String[] args specifies that the
parameter is args and its data type is String[]. We study the meaning of square brackets in
Chap. 12. The last component is about handling errors that occur during the execution of the program.
We study this in Chap. 15.
10 1 “Hello, World!”
Note that the prompt % appears at the end line because of the use of System.out.print.
1.2 The First Program, “Hello, World!” 11
In Java source code, the white space, the tab-stop, and the newline all serve as spacing characters. The
following spacing rules must be followed in Java:
• There should be some spacing between two consecutive occurrences of any of the following: type,
attribute, and name.
• Some mathematical and logical symbols run together to mean special operations. In this situation,
there should not be spacing between symbols.
• There should not be any newlines appearing inside a String literal (a character sequence within
a pair of double quotation marks).
Proper spacing makes Java source codes easy to read. For example, it is possible to write:
Although the Java compiler finds no problem in understanding this line of code, a human may find it
to be a bit difficult to parse.
It is advisable to limit the number of characters per line and work within that limit, breaking up long
lines into multiple smaller ones. The spacing, indentation, and the line width are up to the programmer.
Furthermore, indenting from the left end proportionally to the depth of code is good practice (recall
the discussion in Sect. 1.2.1). In other words, using some fixed quantity M, the code at depth D
receives an indentation of M ·D white spaces. The code in this book utilizes this scheme with M = 2.1
Most code examples that appear in this book present each curly bracket as a stand-alone in one line.
1.2.4 Commenting
It is possible to insert texts that have no relevance to how the code runs. Such texts are called
comments. Comments are free-form texts. Java compilers ignore comments when producing class
files and so they exist only in the source file. A programmer can use comments to make notes to
him or herself. For example, comments can be about the expected behavior of the program and about
the underlying algorithms. To save space, the code examples presented in this book use comments
sparingly.
Java has three kinds of comment formats.
The first kind starts with two forward slashes // appearing outside String literals. If two side-by-
side forward slashes appear outside multiple-line comments (see below) and outside String literals,
the two characters and all the characters appearing after them are treated as comments.
1 Some people use M = 4 or M = 8. The latter is equivalent to the tab-stop; i.e., a tab-stop with a depth of 1.
12 1 “Hello, World!”
Because a programmer tends to limit the number of characters per line in the source code,
the comments that start with two forward slashes are naturally suitable for short comments. For
example, in
1 // / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
2 // This program receives two numbers from
3 // the user and prints the result of performing
4 // addition , subtraction , multiplication , and
5 // subtraction on the two .
6 // / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
1 /*
2 * This program receives two numbers from
3 * the user and prints the result of performing
4 * addition , subtraction , multiplication , and
5 * subtraction on the two .
6 */
The * appearing in the middle four lines are extraneous, but programmers tend to put that character
to make the vertical array of * look like the left border of the comments.
Be mindful of the following:
• /* appearing inside a matching pair of double quotation marks behaves as part of the String
literal. The same holds for */ and //.
• All characters appearing between /* and the matching */ are comments. Therefore, /* appearing
in a matching pair of /* and */ is part of the comment represented by the pair.
The last kind of comment is the Javadoc. The Javadoc is a variant of the aforementioned multiple-
line comment and uses a pair of /** and */ in place of /* and */. Javadocs are for publicizing
information about methods and classes and are written using a special syntax. IDEs such as Eclipse
are capable of presenting information available through Javadocs.
The following code shows some examples of commenting.
1 /*
2 * Class for showing comment examples
3 * Written by Mitsunori Ogihara
4 */
5 public class Comments
6 {
7 /* *
8 * main method
9 * @param args the arguments
10 */
11 public static void main ( String [] args )
12 {
13 // There are two lines in the program
14 System . out . println ( " A code needs comments ! " ) ;
15 }
16 }
Listing 1.4 Examples of comments. Lines 1–4 form a multiple-line comment. Lines 7–10 form a Javadoc comment.
Line 13 is a single-line comment
1.2.5 Errors
A syntax error is a part of source code that fails to conform to the Java syntax. If a source code
contains syntax errors, the Java compiler, instead of producing the bytecode, produces an error
message stating that there are syntax errors. If there is a bytecode generated from the prior successful
compilation, that code remains the same without being updated.
The syntax error that a compiler produces is a bit cryptic and takes some experience to comprehend.
Mainly because the compiler is not aware of the true intension of the programmer who wrote the
erroneous code, the stated number of syntax errors does not necessarily agree with the actual number
of syntax errors.
Consider the following code, which is intended to execute three println statements successively.
Listing 1.5 A buggy version of the HelloWorld program. The intended class name is BuggyHelloWorld
14 1 “Hello, World!”
Each error message consists of the source file name, the line number of the error, the nature of the
error, and the actual location of the error (indicated by the caret symbol). In the case of an IDE, instead
of presenting the errors in its command line interface screen, these errors are highlighted in the source
code editor screen.
As can be seen, the number of error messages is greater than the actual number of errors. Although
the number of error messages may exceed the number of true errors, it is always the case that the very
first error message corresponds to the very first syntax error. In the above example, “illegal start of
type” pointing to /--- is a true syntax error. Fixing the very first syntax error in the source code first
is a good strategy.
There are two other types of errors: run-time errors and logic errors. Runtime errors are those
that occur during the execution of code, interrupting the execution. They often result in a premature
termination of the program. Logic errors do not necessarily result in run-time errors, but occur due to
misconception or flaws in the logic of the programmer.
1.3 Using Multiple Statements 15
As mentioned earlier, a method can contain multiple statements. If multiple statements appear in a
method, they act in the order of appearance. Multiple statements can be used to write a program that
executes a complex task.
Consider the following program that prints the “ABC Song”:
The program executes the six System.out.println statements from top to bottom, and
produces the following six-line output.
1 A B C D E F G
2 H I J K L M N O P
3 Q R S and T U V
4 W X Y and Z
5 Now I know my A B C
6 Won’t you sing along with me
Listing 1.7 A source code with multiple print and println statements
16 1 “Hello, World!”
The use of System.out.print at three places has reduced the number of output lines from six to
three. In each of the three lines, two outputs appear side-by-side with no gaps in between. Thus, to
make the connections appear correct, some characters are needed in between. The next code example
fixes this spacing issue by appending the command and the space (i.e., ", ") to the first, third, and
fifth sequences.
Listing 1.8 A source code with multiple print and println statements with some punctuation
In a manner similar to the code for the ABC song, we can write a program that produces some
selected texts on the screen, for example, the poem “Autumn” by an American poet Henry Wadsworth
Longfellow (February 27, 1807 to March 24, 1882).
Thou comest, Autumn, heralded by the rain
With banners, by great gales incessant fanne
Brighter than brightest silks of Samarcand,
And stately oxen harnessed to thy wain!
Thou standest, like imperial Charlemagne,
Upon thy bridge of gold; thy royal hand
Outstretched with benedictions o’er the land,
Blessing the farms through all thy vast domain!
Thy shield is the red harvest moon, suspended
So ‘long’ beneath the heaven’s o’er-hanging eaves;
Thy steps are by the farmer’s prayers attended;
Like flames upon an altar shine the sheaves;
And, following thee, in thy ovation splendid,
Thine almoner, the wind, scatters the golden leaves!
The code Autumn.java that appears next produces this poem on the screen by combining
System.out.print and System.out.println statements, where each line of the poem is
split into two statements.
1.3 Using Multiple Statements 17
Listing 1.10 A code that attempts to use a quotation mark inside a character sequence
What happened during the compilation attempt? The Java compiler tried to pair the first double
quotation mark with another. It chose, however, to pair the second quotation mark with the first.
The compiler then tried to make sense of the remainder def", but it could not.
To correct this problem, we need to tell the compiler that the middle double quotation mark is not
the end marker. Attaching a backslash \ before the quotation mark accomplishes this.
"abc\"def"
With this modification, the code looks like:
1 public class TripleQuoteCorrect
2 {
3 public static void main( String[] args )
4 {
5 System.out.println( "abc\"def" );
6 }
7 }
Listing 1.11 A code that prints a quotation mark inside a character sequence
1.3 Using Multiple Statements 19
We call the action of attaching the backslash to relieve a symbol of its regular duties escaping.
With escaping, we can insert a newline character using the combination \n. To include a tab-stop
character, we can use \t instead of using of the actual tab-stop. The benefit of using the \t is that the
character is visible; if we use the tab-stop character as it is, it is difficult to tell later whether a gap we
see is indeed a tab-stop or just a series of the white space.
Finally, to escape the backslash character, we use the double backslash \\.
Assuming that the tab-stop positions of a terminal program are at every eighth position starting
from the left end, the statement:
System.out.println( "abcdefgh\n\"\\i\tj\nk" );
produces the following output:
1 abcdefgh
2 "\i j
3 k
We can use escaping to print texts with quotation marks and backward slashes. Listing 1.12 is a
program that prints a quotation from Mark Twain’s Adventures of Huckleberry Finn. In one line of
the quote, the addition of System.out.println and the indentation makes the line too long to
fit in the width of 72 characters. To solve this issue, we split the line into two: the first half with
System.out.print and the second half with System.out.println (Lines 17 and 18).
Listing 1.12 A program that prints a quotation from Mark Twain’s Adventures of Huckleberry Finn
Using \n as the newline, we can print multiple short lines into single statements, as shown in
List 1.13. Note that most of the lines contain \n in the character sequence that needs to be printed.
Listing 1.13 A program that uses squeezed print statements to produce the same quotation from Mark Twain’s
Adventures of Huckleberry Finn as before
Suppose we want to print the figure of a right-angled triangle like the one appears next:
1 /|
2 / |
3 / |
4 / |
5 / |
6 / |
7 /______|
In the drawing, we use the forward slash / for the left side of the triangle, the vertical | for the right
side of the triangle, and the underscore _ for the bottom side.
22 1 “Hello, World!”
1 // -- print a triangle
2 public class Triangle
3 {
4 public static void main ( String [] args )
5 {
6 System . out . println ( " /| " ) ;
7 System . out . println ( " / |" );
8 System . out . println ( " / |" );
9 System . out . println ( " / |" );
10 System . out . println ( " / |" );
11 System . out . println ( " / |" );
12 System . out . println ( " / ______ | " ) ;
13 }
14 }
Using the \ for the right edge, we come up with the following code:
1 // -- print an isosceles
2 public class Isosceles
3 {
4 // -- main method
5 public static void main ( String [] args )
6 {
7 System . out . println ( " /\\ " ) ; // line 1
8 System . out . println ( " / \\ " ) ; // line 2
9 System . out . println ( " / \\ " ) ; // line 3
10 System . out . println ( " / \\ " ) ; // line 4
11 System . out . println ( " / \\ " ) ; // line 5
12 System . out . println ( " / \\ " ) ; // line 6
13 System . out . println ( " / ____________ \\ " ) ; // line 7
14 }
15 }
The shape looks a bit unwieldy, since we are using the dash to draw the top line. The triangle will
look better if we draw the top line using an over-line bar character, but unfortunately, such a character
does not exist in our standard character set, so the dash is our only option.
Listing 1.16 The code for producing an upside-down isosceles triangle on the screen
Summary
A command line interface is an environment in which the user, through typing commands after a
prompt, interacts with the system.
In command line interfaces and programming environments, there exists a “working folder”.
The standard header of a Java class is public class CLASS_NAME. Its file name should be
CLASS_NAME.java.
An executable Java class has public static void main( String[] arg ).
To compile a Java program, use the command javac CLASS_NAME.java.
The Java compiler may produce compilation errors due to syntax errors.
The command to use when executing a Java bytecode by the name of CLASS_NAME is
java CLASS_NAME.
A code that compiles may produce terminating errors. Such terminating errors are called run-time
errors.
A code that compiles and is free of run-time errors may still not run correctly. Logical errors are
the culprits.
Java programs use pairs of curly braces to define code blocks.
Unless they are appearing in the source code for an object class, methods need to have the static
attribute.
Methods and classes may have a visibility attribute.
Method declarations must have both a return value specification and a parameter specification.
In a method, multiple statements may appear. Each statement ends with a semicolon.
System.out.println is a method that produces the value of its parameter on the screen and
then prints a newline.
System.out.print is a method that produces the value of its parameter on the screen.
24 1 “Hello, World!”
To print the double quotation mark, the escape sequence of \" is used.
To print the backslash as a character, the escape sequence of \\ is used.
There are three types of comments: single line comments, multiple-line comments, and Javadocs.
Exercises
4. Escaping Which of the following require a backslash when being included in a String literal
(i.e., a series of characters flanked by a pair of double quotation marks)?
• A
• /
(i.e., the forward slash)
• \
(i.e, the backslash)
• "
• %
(i.e., the percentage symbol)
• @
(i.e., the at sign)
Exercises 25
Programming Projects
5. Alma Mater Write a program named AlmaMater that upon execution prints the Alma Mater
of your school. For the University of Miami, the output of the program should look like:
1 UM ALMA MATER
2
3 Southern suns and sky blue water,
4 Smile upon you Alma mater;
5 Mistress of this fruitful land,
6 With all knowledge at your hand,
7 Always just to honor true,
8 All our love we pledge to you.
9 Alma Mater, stand forever
10 On Biscayne’s wondrous shore.
6. Printing a Diamond Write a program named Diamond.java that prints the shape of a
diamond of height 10 and width 10 as shown:
1 /\
2 / \
3 / \
4 / \
5 / \
6 \ /
7 \ /
8 \ /
9 \ /
10 \/
7. Printing a Filled Diamond Write a program named DiamondFilled.java that prints the
shape of a diamond of height 10 and width 10 with the white space filled with forward slashes on
the left-hand side and backward slashes on the right-hand side, as shown:
1 /\
2 //\\
3 ///\\\
4 ////\\\\
5 /////\\\\\
6 \\\\\/////
7 \\\\////
8 \\\///
9 \\//
10 \/
9. Cascaded printing Write a program, CascadedChildren, that prints the first two verses of
“Children” by Henry Wadsworth Longfellow with increasing indentations:
26 1 “Hello, World!”
10. Slashes Write a program, Slashes, that produces the following shape on the screen:
1 / / / / / / / / / / / /
2 / / / / / / / / / / /
3 / / / / / / / / / / / /
4 / / / / / / / / / / /
5 / / / / / / / / / / / /
6 / / / / / / / / / / /
7 / / / / / / / / / / / /
8 / / / / / / / / / / /
9 / / / / / / / / / / / /
10 / / / / / / / / / / /
11. Backlashes Write a program, BackSlashes, that produces the following shape on the screen:
1 \ \ \ \ \ \ \ \ \ \ \ \
2 \ \ \ \ \ \ \ \ \ \ \
3 \ \ \ \ \ \ \ \ \ \ \ \
4 \ \ \ \ \ \ \ \ \ \ \
5 \ \ \ \ \ \ \ \ \ \ \ \
6 \ \ \ \ \ \ \ \ \ \ \
7 \ \ \ \ \ \ \ \ \ \ \ \
8 \ \ \ \ \ \ \ \ \ \ \
9 \ \ \ \ \ \ \ \ \ \ \ \
10 \ \ \ \ \ \ \ \ \ \ \
12. Tabstop You can use the tab-stop character \t to line things up (to improve the readability of
the text output). Consider the following code:
1 public class TestTabStop
2 {
3 public static void main ( String [] args )
4 {
5 System . out . println ( " Abbie Zuckerman 23 yrs Soccer " ) ;
6 System . out . println ( " Brittany Ying 21 yrs Swimming " ) ;
7 System . out . println ( " Caty Xenakis 22 yrs Softball " ) ;
8 System . out . println ( " Dee Wick 20 yrs Basketball " ) ;
9 System . out . println ( " Eva Venera 19 yrs Polo " ) ;
10 }
11 }
Revise the program so that it uses the same code, but replaces the whitespace (inside each pair
of double quotation marks) with the tab-stop. Run the program to see how it changes the way the
information appears on the screen.
13. Self introduction Write a program named SelfIntro that introduces yourself as follows:
1 My name is NAME.
2 I was born in PLACE.
3 My favorite television program is PROGRAM.
4 I woke up at HOUR:MINUTE today.
5 I own NUMBER books.
6 My target grade point average is GPA.
The uppercase words NAME, PLACE, PROGRAM, HOUR, MINUTE, NUMBER, and GPA, are
placeholders, so you must substitute them with appropriate text. PROGRAM must appear with
double quotation marks. For example,
1 My name is Mitsu Ogihara.
2 I was born in Japan.
3 My favorite television program is "Parks and Recreation".
4 I woke up at 6:30 today.
5 I own 1000 books.
6 My target grade point average is 4.0.
Using Data for Computation
2
2.1 Data
The previous chapter presented how to write programs using only System.out.println and
System.out.print statements. This chapter introduces how to store, modify, and retrieve
information. The medium in which information is stored is called data.1
In Java, every data has its type, which specifies how the data encodes its information, as well as
what operations can be performed on the data. There are two broad classifications of data types in
Java: primitive data types and object data types.
A primitive data type is one that uses only a predetermined number of bits in representation, where
a bit is the fundamental unit of information and has two possible values (0 and 1). There are eight
primitive data types: boolean for the logical values, char for the characters, byte, short, int,
and long for whole numbers of various capacities, and float and double for real numbers of
various capacities.
On the other hand, an object data type is a custom-designed data type. A programmer designs a
new object data type by putting together existing data types and defining the permissible operations
for acting on the information stored. Some object data types require an indefinite number of bits for
representation.
In addition to the major difference between primitive and object data types, the following
distinctions can be made among data.
1. There are data with names referencing and data without these names.
(a) The former kind is a variable. A special variable is one whose value cannot be changed during
the course of program. Such a variable is called a constant
(b) The latter kind consists of literals and return values. A literal is a data whose value is exactly
specified. A return value is a value that a method returns.
1 The term data is used for both singular and plural forms. The original singular form of “data” is “datum”, but this is
rarely used nowadays.
2. Some variables and constants are accessible only inside the method in which they appear; others
are accessible from everywhere in the class. The former ones are local, and the latter ones are
global.
(a) Some global variables in an object class play the role of storing information for individual
objects of the class. Those variables are instance variables (or field variables).
(b) Each global constant, as well as each instance variable, has a specific visibility type (public,
private, protected, and package).
The sequence "Hello, World!" is a literal of the data type String. Literals are available not
only for String but also for all the primitive data types.
The following is an example of a code using literals:
In Lines 5, 7–9, and 12, String literals appear inside the parentheses. In Lines 6 and 11, literals
1 and 96.8 appear inside the parentheses. These are number literals (an int literal and a double
literal, to be precise).
When this program runs, System.out.print converts these two numbers to character
sequences, then prints those sequences on the screen.
By adding the same sequence of statements for two more quarterbacks, the following program is
obtained.
2.1 Data 31
Listing 2.2 A program that produces comments about three NFL quarterbacks (part 1). The program header and the
part that produces comments about the first player
For these additional two players, number literals appear in Lines 15, 20, 24 and 29.
Listing 2.3 A program that produces comments about three NFL quarterbacks (part 2). The part that produces
comments about the second and the third players
2 Jon Steven “Steve” Young (born October 11, 1961) is a former NFL quarterback and a sportscaster. He played 13
seasons with the San Francisco 49ers, and led the team to three Super Bowl wins. Peyton Williams Manning (born March
24, 1976) is a former NFL quarterback who played with the Indianapolis Colts and later with the Denver Broncos. He
led each team to one Super Bowl win. Thomas Edward Patrick Brady Jr. (born August 3, 1977) is an NFL quarterback
for the New England Patriots. He led the team to five Super Bowl wins.
32 2 Using Data for Computation
A variable is a type of data with a reference name. Simply by putting its name in the code, the value
of the data in that specific moment can be looked up.
Since each data has a unique type, a variable is specified with its name and its type. This is called
a declaration. A declaration takes the following form:
DATA_TYPE VARIABLE_NAME;
Remember that the tab-stop can be used in place of the white space, and adding more tab-stops or
white space after that is possible as well.
One example is the following:
1 public static ...
2 {
3 ...
4 int myInteger ;
5 ...
6 }
Here, int is the data type and myInteger is the name of the data. Notice the semicolon ;
appearing at the end. Each line of local/global variable/constant declarations requires a semicolon at
the end. The above is an instance in which the variable is a local variable. A local variable belongs to
a method and its declaration appears inside the method that it belongs to. The “locality” of variables
becomes important when multiple methods are written in a source code.
To declare a global variable, its declaration is placed outside the methods, at depth 1. For example,
the following declares a global variable named myInteger of data type int.
1 static int myInteger ;
2
3 public static ...
4 {
5 ...
6 }
Here, oneInteger, anotherInteger, and yetAnotherInteger are all of the int data
type. This single-line declaration is equivalent to:
1 int oneInteger ;
2 int anotherInteger ;
3 int yetAnotherInteger ;
To name a variable, a sequence of contiguous characters chosen from the alphabet, numerals, the
underscore _, and the dollar sign $ must be used. In addition, the first character of the sequence
must be a letter of the alphabet.3 Thus, according to this rule, 55 cannot be a variable name. The
3 Technically,
a variable name can start with the underscore or the dollar sign, but the convention is to start a variable
name with a lowercase letter.
2.1 Data 33
variable names, method names, and class names are all case-sensitive. The following conventions are
generally used:
As mentioned earlier, variables (or constants) are places where information is stored. The action of
giving a value to a variable/constant is called an assignment.
The syntax for an assignment is:
VARIABLE = VALUE;
Here, the equal sign = appearing in the middle symbolizes the assignment. The left-hand side of the
assignment, VARIABLE, is the name of the variable in which a value is to be stored. The right-hand
side of an assignment, VALUE, is the value being stored. JVM can interpret this as a data having the
same type as the variable. The value in an assignment can be:
1 int myInteger ;
2 myInteger = 55;
The first line here is a variable declaration. The type of the data is int and the name of the data is
myInteger. The second line is an assignment. The right-hand side of the assignment is an int
literal with the value of 55. This action stores the value of 55 into the variable myInteger.
It is possible to combine a declaration of a variable and an initial value assignment to the variable
all in a single statement, like this one:
It is also possible to combine multiple declarations and assignments of multiple variables in one line,
so long as they all have the same type. The following is an example of such combinations:
This single line of code declares int variables, oneInteger, anotherInteger, and
yetAnotherInteger, and assigns the value of 17 to oneInteger and the value of 23 to
yetAnotherInteger (note that 17 and 23 are literals).
Here, anotherInteger does not have an assignment. Does it have a value? Yes, the default
value of a variable of a primitive number type immediately after declaration is 0.
34 2 Using Data for Computation
as well as to:
For the code to compile, the value assigned to a variable must match the data type of the variable.
In the above code fragment, an attempt to assign numbers with a decimal point,
results in a syntax error, because neither 17.5 nor 23.0 are integers.
The first variable, YOUR_INTEGER, is a global constant and the second variable, MY_NUMBER, is
a local constant. Java requires that a value must be assigned to a constant using a combined declaration
and assignment. Therefore, in the above code example, splitting the declaration and assignment of
either constant into a standalone declaration and a standalone assignment is rejected as a syntax error.
A global constant may have an explicit visibility specification. As mentioned in Chap. 1, there are
three explicit visibility specifications: public, private, and protected. In the source code:
Reassignment
If a variable is not a constant, the value of the variable can be updated any number of times. Consider
the next code:
1 int myInteger ;
2 myInteger = 63;
3 ...
4 myInteger = 97;
5 ...
6 myInteger = 20;
The dotted parts represent some arbitrary code. Assuming that no assignments to myInteger appear
in the dotted part, the value of myInteger changes from 63 to 97 in Line 4 and from 97 to 20 in
Line 6.
Java has eight primitive data types. They are boolean, byte, short, int, long, float, double, and char.
Table 2.1 shows the range of possible values for each type.
boolean
The boolean is a data type for storing a logical value. There are only two possible values for a
boolean data type: true and false. Here is an example of declaring boolean variables and
assigning values to them.
There are three operators available for boolean: the negation !, the conjunction &&, and the
disjunction ||. The boolean data type will be discussed in Chap. 6.
byte
The data type byte consists of eight bits, so there are 28 = 256 possible values. The value range
of byte is between −27 = −128 and 27 − 1 = 127. The hexadecimal encoding is an encoding
that is often used for specifying a byte literal. This is the encoding that divides the bits into groups
of four and uses a unique character to represent each of the 16 possible values for each group. The
value range of four bits is between 0 and 15, so naturally the numerals 0 through 9 are used for
representing numbers 0 through 9. For the numbers 10 through 15, the letters a through f (or their
upper case letters A through F) are used. In hexadecimal encoding, a byte must be represented with
two characters. The combination YZ represents
short
The data type short consists of sixteen bits. It has 65,536 possible values. The value range is
between −215 = −32,768 and 215 − 1 = 32,767.
int
int is a data type that consists of 32 bits. It has 4,294,967,296 possible values. The value range is
between −231 = −2,147,483,648 and 231 − 1 = 2,147,483,647. The default data type of a whole
number literal is int.
long
The data type long consists of 64 bits. It has 18,446,744,073,709,551,616 possible values. The value
range is between −263 = −9,223,372,036,854,775,808 and 263 − 1 = 9,223,372,036,854,775,807.
When presenting a literal in long, if the value that the literal represents goes beyond the range of
int, the letter L must be attached as a suffix at the end of the number sequence, like this one:
encoding system uses a fixed “base” for exponentiation, which is either 2 or 10. Let B be this base. If
there are n bits in the exponent, that part encodes a number between −2n−1 and 2n−1 − 1 (for whole
number types). Let E be this number. Now, the bits of the floating number altogether represent
S · (1 + C) · B E .
To designate that a floating point number literal is a float, the letter F must be attached as a suffix.
Here is an example of declaring and assigning a literal value to one variable for each primitive
number type:
1 byte myByte ;
2 short myShort ;
3 int myInt ;
4 long myLong ;
5 float myFloat ;
6 double myDouble ;
7 myByte = 0 x3d ;
8 myShort = 1345;
9 myInt = 90909;
10 myLong = 1234567890123456789 L ;
11 myFloat = -3.145 F ;
12 myDouble = 1.7320504;
The numbers appearing after ’=’ in lines 7–12 are all literals.
char
The last primitive data type is char. The representation of char requires sixteen bits. By attaching
the apostrophe before and after of a character, a char literal is specified, as in ’A’ and ’x’.
1 char myChar1 = ’A ’;
2 char myChar2 = ’x ’;
The default value of a char type variable is \0. This is the character corresponding to the number
0. This must not be confused this with the numeral 0. There is no direct arithmetic operation that can
be applied to char data for producing another char, but if a char data appears in a mathematical
formula, it acts as if it were an int. Since the single quotation mark is used for a char literal, to
specify the single quotation mark itself as a char literal, attaching a backslash as is must be done to
represent the double quotation mark in String literals; that is, ’\” represents the single quotation
mark. Because of this special use of backslash, two backslashes are used to mean the backslash itself
as a literal, as in ’\\’. The other escape sequences, ’\t’ and ’\n’, are valid for char literals too.
Using the fact that reassignments of values can be made to non-final variables, the previous three-
favorite-quarterback program can be rewritten using three variables:
• an int variable, rank, for specifying the rank in the list
• a String variable, name, for the name of the quarterback, and
• a double variable, qbr, for the quarterback rating.
38 2 Using Data for Computation
Listing 2.4 A program that produces comments about three NFL quarterbacks using variables (part 1). The variable
declarations and the part that produced the comments about the first player
Note that the variable declarations appear in Lines 4, 5, and 7. The variable declarations are
followed by three blocks of the same format, each consisting of eleven lines. The first lines of each
block assign values to the variables. For example, the first lines of the first block are:
1 rank = 1;
2 name = " Steve Young " ;
3 qbr = 96.8;
The next eight lines of code make the presentation, with the three literals for rank, name, and rating
substituted with their respective names.
1 ...
2 System.out.print( rank );
3 ...
4 System.out.print( name );
5 ...
6 ...
7 System.out.print( qbr );
8 ...
In these three lines, the values of these variables substitute their respective locations into the print
statements. Note that the action order is:
declaration → assignment → reference
Since assignments can be made multiple times to non-final variables, a variable declaration is
effective until the end of the innermost pair of curly brackets that contains it. This means that two
declarations of the same variables cannot intersect. In the above program, the innermost matching
pair containing a variable declaration appears at Lines 4 and 44. Thus, the declarations are valid until
Line 44. Formally, the range of lines in which a variable declaration is valid is called the scope of the
variable.
Exploring the Variety of Random
Documents with Different Content
trusted helper of the Apostle. He was with Paul in the latter part of
the third missionary tour—so we learn from the Corinthian letters—
and therefore probably in the earlier part of the same journey, when
the Apostle paid his second visit to Galatia. He belonged to the
heathen mission, and was Paul's "true child after a common faith"
(Tit. i. 4), an uncircumcised man, of Gentile birth equally with the
Galatians. And now they read of his "going up to Jerusalem with
Paul," to the mother-city of believers, where are the pillars of the
Church—the Jewish teachers would say—the true Apostles of Jesus,
where His doctrine is preached in its purity, and where every
Christian is circumcised and keeps the Law. Titus, the unclean
Gentile, at Jerusalem! How could he be admitted or tolerated there,
in the fellowship of the first disciples of the Lord? This question
Paul's readers, after what they had heard from the Circumcisionists,
would be sure to ask. He will answer it directly.
But the Apostle goes on to say, that he "went up in accordance with
a revelation." For this was one of those supreme moments in his life
when he looked for and received the direct guidance of heaven. It
was a most critical step to carry this question of Gentile circumcision
up to Jerusalem, and to take Titus with him there, into the enemies'
stronghold. Moreover, on the settlement of this matter Paul knew
that his Apostolic status depended, so far as human recognition was
concerned. It would be seen whether the Jewish Church would
acknowledge the converts of the Gentile mission as brethren in
Christ; and whether the first Apostles would receive him, "the
untimely one," as a colleague of their own. Never had he more
urgently needed or more implicitly relied upon Divine direction than
at this hour.
"And I put before them (the Church at Jerusalem) the gospel which I
preach among the Gentiles—but privately to those of repute: am I
running (said I), or have I run, in vain?" The latter clause we read
interrogatively, along with such excellent grammatical interpreters as
Meyer, Wieseler, and Hofmann. Paul had not come to Jerusalem in
order to solve any doubt in his own mind; but he wished the Church
of Jerusalem to declare its mind respecting the character of his
ministry. He was not "running as uncertainly;" nor in view of the
"revelation" just given him could he have any fear for the result of
his appeal. But it was in every way necessary that the appeal should
be made.
The interjected words, "but privately," etc., indicate that there were
two meetings during the conference, such as those which seem to
be distinguished in Acts xv. 4 and 6; and that the Apostle's
statement and the question arising out of it were addressed more
pointedly to "those of repute." By this term we understand, here and
in ver. 6, "the apostles and elders" (Acts xv.), headed by Peter and
James, amongst whom "those reputed to be pillars" are
distinguished in ver. 9. Paul dwells upon the phrase οἱ δοκοῦντες,
because, to be sure, it was so often on the lips of the Judaizers, who
were in the habit of speaking with an imposing air, and by way of
contrast with Paul, of "the authorities" (at Jerusalem)—as the
designation might appropriately be rendered. These very men whom
the Legalists were exalting at Paul's expense, the venerated chiefs of
the mother Church, had on this occasion, Paul is going to say, given
their approval to his doctrine; they declined to impose circumcision
on Gentile believers. The Twelve were not stationary at Jerusalem,
and therefore could not form a fixed court of reference there; hence
a greater importance accrued to the Elders of the city Church, with
the revered James at their head, the brother of the Lord.
The Apostle, in bringing Titus, had brought up the subject-matter of
the controversy. The "gospel of the uncircumcision" stood before the
Jewish authorities, an accomplished fact. Titus was there, by the
side of Paul, a sample—and a noble specimen, we can well believe—
of the Gentile Christendom which the Jewish Church must either
acknowledge or repudiate. How will they treat him? Will they admit
this foreign protege of Paul to their communion? Or will they require
him first to be circumcised? The question at issue could not take a
form more crucial for the prejudices of the mother Church. It was
one thing to acknowledge uncircumcised fellow-believers in the
abstract, away yonder at Antioch or Iconium, or even at Cæsarea;
and another thing to see Titus standing amongst them in his
heathen uncleanness, on the sacred soil of Jerusalem, under the
shadow of the Temple, and to hear Paul claiming for him—for this
"dog" of a Gentile—equally with himself the rights of Christian
brotherhood! The demand was most offensive to the pride of
Judaism, as no one knew better than Paul; and we cannot wonder
that a revelation was required to justify the Apostle in making it. The
case of Trophimus, whose presence with the Apostle at Jerusalem
many years afterwards proved so nearly fatal (Acts xxi. 27-30),
shows how exasperating to the legalist party his action in this
instance must have been. Had not Peter and the better spirits of the
Church in Jerusalem laid to heart the lesson of the vision of Joppa,
that "no man must be called common or unclean," and had not the
wisdom of the Holy Spirit eminently guided this first Council of the
Church,[37] Paul's challenge would have received a negative answer;
and Jewish and Gentile Christianity must have been driven asunder.
The answer, the triumphant answer, to Paul's appeal comes in the
next verse: "Nay, not even[38] Titus who was with me, being a Greek,
was compelled to be circumcised." Titus was not circumcised, in
point of fact—how can we doubt this in view of the language of ver.
5: "Not even for an hour did we yield in subjection?" And he "was
not compelled to be circumcised"—a mode of putting the denial
which implies that in refusing his circumcision urgent solicitation had
to be withstood, solicitation addressed to Titus himself, as well as to
the leaders of his party. The kind of pressure brought to bear in the
case and the quarter from which it proceeded, the Galatians would
understand from their own experience (ch. vi. 12; comp. ii. 14).
The attempt made to bring about Titus' circumcision signally failed.
Its failure was the practical reply to the question which Paul tells us
(ver. 2) he had put to the authorities in Jerusalem; or, according to
the more common rendering of ver. 2b, it was the answer to the
apprehension under which he addressed himself to them. On the
former of these views of the connection, which we decidedly prefer,
the authorities are clear of any share in the "compulsion" of Titus.
When the Apostle gives the statement that his Gentile companion
"was not compelled to be circumcised" as the reply to his appeal to
"those of repute," it is as much as to say: "The chiefs at Jerusalem
did not require Titus' circumcision. They repudiated the attempt of
certain parties to force this rite upon him." This testimony precisely
accords with the terms of the rescript of the Council, and with the
speeches of Peter and James, given in Acts xv. But it was a great
point gained to have the liberality of the Jewish Christian leaders put
to the proof in this way, to have the generous sentiments of speech
and letter made good in this example of uncircumcised Christianity
brought to their doors.
To the authorities at Jerusalem the question put by the delegates
from Antioch on the one side, and by the Circumcisionists on the
other, was perfectly clear. If they insist on Titus' circumcision, they
disown Paul and the Gentile mission: if they accept Paul's gospel,
they must leave Titus alone. Paul and Barnabas stated the case in a
manner that left no room for doubt or compromise. Their action was
marked, as ver. 5 declares, with the utmost decision. And the
response of the Jewish leaders was equally frank and definite. We
have no business, says James (Acts xv. 19), "to trouble those from
the Gentiles that turn to God." Their judgement is virtually affirmed
in ver. 3, in reference to Titus, in whose person the Galatians could
not fail to see that their own case had been settled by anticipation.
"Those of repute" disowned the Circumcisionists; the demand that
the yoke of circumcision should be imposed on the Gentiles had no
sanction from them. If the Judaizers claimed their sanction, the
claim was false.
Here the Apostle pauses, as his Gentile readers must have paused
and drawn a long breath of relief or of astonishment at what he has
just alleged. If Titus was not compelled to be circumcised, even at
Jerusalem, who, they might ask, was going to compel them?—The
full stop should therefore be placed at the end of ver. 3, not ver. 2.
Vv. 1-3 form a paragraph complete in itself. Its last sentence
resolves the decisive question raised in this visit of Paul's to
Jerusalem, when he "took with him also Titus."
II. The opening words of ver. 4 have all the appearance of
commencing a new sentence. This sentence, concluded in ver. 5, is
grammatically incomplete; but that is no reason for throwing it upon
the previous sentence, to the confusion of both. There is a transition
of thought, marked by the introductory But,[39] from the issue of
Paul's second critical visit to Jerusalem (vv. 1-3) to the cause which
made it necessary. This was the action of "false brethren," to whom
the Apostle made a determined and successful resistance (vv. 4, 5).
The opening "But" does not refer to ver. 3 in particular, rather to the
entire foregoing paragraph. The ellipsis (after "But") is suitably
supplied in the marginal rendering of the Revisers, where we take it
was to mean, not "Because of the false brethren Titus was not (or
was not compelled to be) circumcised," but "Because of the false
brethren this meeting came about, or, I took the course aforesaid."
To know what Paul means by "false brethren," we must turn to ch. i.
6-9, iii. 1, iv. 17, v. 7-12, vi. 12-14, in this Epistle; and again to 2 Cor.
ii. 17-iii. 1, iv. 2, xi. 3, 4, 12-22, 26; Rom. xvi. 17, 18; Phil. iii. 2.
They were men bearing the name of Christ and professing faith in
Him, but Pharisees at heart, self-seeking, rancorous, unscrupulous
men, bent on exploiting the Pauline Churches for their own
advantage, and regarding Gentile converts to Christ as so many
possible recruits for the ranks of the Circumcision.
But where, and how, were these traitors "privily brought in?"
Brought in, we answer, to the field of the Gentile mission; and
doubtless by local Jewish sympathisers, who introduced them
without the concurrence of the officers of the Church. They "came in
privily"—slipped in by stealth—"to spy out our liberty which we have
in Christ Jesus." Now it was at Antioch and in the pagan Churches
that this liberty existed in its normal exercise—the liberty for which
our Epistle contends, the enjoyment of Christian privileges
independently of Jewish law—in which Paul and his brother
missionaries had identified themselves with their Gentile followers.
The "false brethren" were Jewish spies in the Gentile Christian camp.
We do not see how the Galatians could have read the Apostle's
words otherwise; nor how it could have occurred to them that he
was referring to the way in which these men had been originally
"brought into" the Jewish Church. That concerned neither him nor
them. But their getting into the Gentile fold was the serious thing.
They are the "certain who came down from Judæa, and taught the
(Gentile) brethren, saying, Except ye be circumcised after the
custom of Moses, ye cannot be saved;" and whom their own Church
afterwards repudiated (Acts xv. 24). With Antioch for the centre of
their operations, these mischief-makers disturbed the whole field of
Paul and Barnabas' labours in Syria and Cilicia (Acts xv. 23; comp.
Gal. i. 21). For the Galatian readers, the terms of this sentence,
coming after the anathema of ch. i. 6-9, threw a startling light on
the character of the Judean emissaries busy in their midst. This
description of the former "troublers" strikes at the Judaic opposition
in Galatia. It is as if the Apostle said: "These false brethren,
smuggled in amongst us, to filch away our liberties in Christ, wolves
in sheep's clothing—I know them well; I have encountered them
before this. I never yielded to their demands a single inch. I carried
the struggle with them to Jerusalem. There, in the citadel of
Judaism, and before the assembled chiefs of the Judean Church, I
vindicated once and for all, under the person of Titus, your
imperilled Christian rights."
But as the Apostle dilates on the conduct of these Jewish intriguers,
the precursors of such an army of troublers, his heart takes fire; in
the rush of his emotion he is carried away from the original purport
of his sentence, and breaks it off with a burst of indignation: "To
whom," he cries, "not even for an hour did we yield by subjection,
that the truth of the gospel might abide with you." A breakdown like
this—an anacoluthon, as the grammarians call it—is nothing strange
in Paul's style. Despite the shipwrecked grammar, the sense comes
off safely enough. The clause, "we did not yield," etc., describes in a
negative form, and with heightened effect, the course the Apostle
had pursued from the first in dealing with the false brethren. In this
unyielding spirit he had acted, without a moment's wavering, from
the hour when, guided by the Holy Spirit, he set out for Jerusalem
with the uncircumcised Titus by his side, until he heard his Gentile
gospel vindicated by the lips of Peter and James, and received from
them the clasp of fellowship as Christ's acknowledged Apostle to the
heathen.
It was therefore the action of Jewish interlopers, men of the same
stamp as those infesting the Galatian Churches, which occasioned
Paul's second, public visit to Jerusalem, and his consultation with the
heads of the Judean Church. This decisive course he was himself
inspired to take; while at the same time it was taken on behalf and
under the direction of the Church of Antioch, the metropolis of
Gentile Christianity. He had gone up with Barnabas and "certain
others"—including the Greek Titus chosen by himself—the company
forming a representative deputation, of which Paul was the leader
and spokesman. This measure was the boldest and the only
effectual means of combatting the Judaistic propaganda. It drew
from the authorities at Jerusalem the admission that "Circumcision is
nothing," and that Gentile Christians are free from the ritual law.
This was a victory gained over Jewish prejudice of immense
significance for the future of Christianity. The ground was already cut
from under the feet of the Judaic teachers in Galatia, and of all who
should at any time seek to impose external rites as things essential
to salvation in Christ. To all his readers Paul can now say, so far as
his part is concerned: The truth of the gospel abides with you.
CHAPTER VIII.
PAUL AND THE THREE PILLARS.
"But from those who were reputed to be somewhat (what they
once were, it maketh no matter to me: God accepteth not man's
person)—they, I say, who were of repute imparted nothing to
me: but contrariwise, when they saw that I had been intrusted
with the gospel of the uncircumcision, even as Peter with the
gospel of the circumcision (for he that wrought for Peter unto
the apostleship of the circumcision wrought for me also unto the
Gentiles); and when they perceived the grace that was given
unto me, James and Cephas and John, they who were reputed
to be pillars, gave to me and Barnabas the right hands of
fellowship, that we should go unto the Gentiles, and they unto
the circumcision; only they would that we should remember the
poor; which very thing I was also zealous to do."—Gal. ii. 6-10.
James, Peter, John, and Paul—it was a memorable day when these
four men met face to face. What a mighty quaternion! Amongst
them they have virtually made the New Testament and the Christian
Church. They represent the four sides of the one foundation of the
City of God. Of the Evangelists, Matthew holds affinity with James;
Mark with Peter; and Luke with Paul. James clings to the past and
embodies the transition from Mosaism to Christianity. Peter is the
man of the present, quick in thought and action, eager, buoyant,
susceptible. Paul holds the future in his grasp, and schools the
unborn nations. John gathers present, past, and future into one,
lifting us into the region of eternal life and love.
With Peter and James Paul had met before, and was to meet again.
But so far as we can learn, this was the only occasion on which his
path crossed that of John. Nor is this Apostle mentioned again in
Paul's letters. In the Acts he appears but once or twice, standing
silent in Peter's shadow. A holy reserve surrounds John's person in
the earlier Apostolic history. His hour was not yet come. But his
name ranked in public estimation amongst the three foremost of the
Jewish Church; and he exercised, doubtless, a powerful, though
quiet, conciliatory influence in the settlement of the Gentile question.
The personality of Paul excited, we may be sure, the profoundest
interest in such a mind as that of John. He absorbed, and yet in a
sense transcended, the Pauline theology. The Apocalypse, although
the most Judaic book of the New Testament, is penetrated with the
influence of Paulinism. The detection in it of a covert attack on the
Gentile Apostle is simply one of the mare's nests of a super-subtle
and suspicious criticism. John was to be the heir of Paul's labours at
Ephesus and in Asia Minor. And John's long life, touching the verge
of the second century, his catholic position, his serene and lofty
spirit, blending in itself and resolving into a higher unity the
tendencies of James and Peter and Paul, give us the best assurance
that in the Apostolic age there was indeed "One, holy, catholic,
Apostolic Church."
Paul's fellowship with Peter and with James was cordial and
endeared. But to hold the hand of John, "the disciple whom Jesus
loved," was a yet higher satisfaction. That clasp symbolized a union
between men most opposite in temperament and training, and
brought to the knowledge of Christ in very different ways, but whose
communion in Him was deep as the life eternal. Paul and John are
the two master minds of the New Testament. Of all men that ever
lived, these two best understood Jesus Christ.
CHAPTER IX.
PAUL AND PETER AT ANTIOCH
"But when Cephas came to Antioch, I resisted him to the face,
because he stood condemned. For before that certain came
from James, he did eat with the Gentiles; but when they came,
he drew back and separated himself, fearing them that were of
the circumcision. And the rest of the Jews dissembled likewise
with him; insomuch that even Barnabas was carried away with
their dissimulation. But when I saw that they walked not
uprightly according to the truth of the gospel, I said unto
Cephas before them all, If thou, being a Jew, livest as do the
Gentiles, and not as do the Jews, how compellest thou the
Gentiles to live as do the Jews? We being Jews by nature, and
not sinners of the Gentiles, yet knowing that a man is not
justified by works of law, but only through faith in Jesus Christ,
even we believed on Christ Jesus, that we might be justified by
faith in Christ, and not by the works of the law: because by the
works of the law shall no flesh be justified. But if, while we
sought to be justified in Christ, we ourselves also were found
sinners, is Christ a minister of sin? God forbid. For if I build up
again those things which I destroyed, I prove myself a
transgressor."—Gal. ii. 11-18.
ebookbell.com