Building Java Programs A Back to Basics Approach 60593rd Edition Stuart Reges instant download
Building Java Programs A Back to Basics Approach 60593rd Edition Stuart Reges instant download
https://ebookfinal.com/download/building-java-programs-a-back-to-
basics-approach-60593rd-edition-stuart-reges/
https://ebookfinal.com/download/back-to-basics-tactics-dan-heisman/
https://ebookfinal.com/download/the-everything-guide-to-living-off-
the-grid-a-back-to-basics-manual-for-independent-living-terri-reid/
https://ebookfinal.com/download/the-essentials-of-trading-from-the-
basics-to-building-a-winning-strategy-1st-edition-john-forman/
https://ebookfinal.com/download/building-strategic-language-ability-
programs-1st-edition-joshua-r-weston/
Nursing Assistant A Nursing Process Approach Basics 1st
Edition Barbara Hegner
https://ebookfinal.com/download/nursing-assistant-a-nursing-process-
approach-basics-1st-edition-barbara-hegner/
https://ebookfinal.com/download/low-back-disorders-evidence-based-
prevention-and-rehabilitation-1st-edition-stuart-mcgill/
https://ebookfinal.com/download/low-back-disorders-evidence-based-
prevention-and-rehabilitation-3rd-edition-stuart-mcgill/
https://ebookfinal.com/download/java-ee-7-recipes-a-problem-solution-
approach-1st-edition-josh-juneau-auth/
Building Java Programs A Back to Basics Approach
60593rd Edition Stuart Reges Digital Instant Download
Author(s): Stuart Reges, Marty Stepp
ISBN(s): 9780321382832, 0321382838
Edition: 60593rd
File Details: PDF, 6.68 MB
Year: 2007
Language: english
Building Java Programs
Stuart Reges and Marty Stepp
1
2
Table of Contents
Chapter 1: Introduction to Java Programming
1.1 Basic Computing Concepts
Why Programming?
Hardware and Software
The Digital Realm
Why Java?
The Process of Programming
The Java Programming Environment
1.2 And Now--Java
String Literals (Strings)
System.out.println
Escape Sequences
Identifiers and Keywords
Comments and Readability
A Complex Example: DrawFigures1
1.3 Program Errors
Syntax Errors
Logic Errors (bugs)
1.4 Procedural Decomposition
Static Methods
Flow of Control
Methods That Call Other Methods
An Example Runtime Error
1.5 Case Study: DrawFigures
Structured Version
Final Version without Redundancy
Analysis of Flow of Execution
Chapter 7: Arrays
7.1 Array Basics
Constructing and Accessing an Array
A Useful Application of Arrays
Random Access
Arrays and Methods
The For-Each Loop
Limitations of Arrays
7.2 Advanced Arrays
Shifting Values in an Array
Initializing Arrays
Arrays in the Java Class Libraries
Arrays of Objects
Command Line Arguments
7.3 Multidimensional Arrays (optional)
Rectangular Two-Dimensional Arrays
Jagged Arrays
7.4 Case Study: Hours Worked
The transferFrom Method
6
The sum Method
The addTo Method
The print Method
The Complete Program
8
A Nonprogramming Example
An Iterative Solution Converted to Recursion
Structure of Recursive Solutions
12.2 A Better Example of Recursion
Mechanics of Recursion
12.3 Recursive Functions
Integer Exponentiation
Greatest Common Divisor
12.4 Recursive Graphics (optional)
12.5 Case Study: Prefix Evaluator
Infix, Prefix and Postfix Notation
Prefix Evaluator
Complete Program
10
Chapter 1
Introduction to Java Programming
Copyright © 2006 by Stuart Reges and Marty Stepp
Introduction
In this chapter, we introduce some basic terminology about computers and programming. We
discuss the Java language and its programming environment. We take a brief look at writing simple
but structured Java programs that produce output.
11
1.1 Basic Computing Concepts
Computers are pervasive in our daily lives, giving us access to nearly limitless information. Some
of this information is essential news, like the headlines at cnn.com. Some of it is more frivolous: If
you're concerned about whether the guy you met last night cheats on his girlfriends, perhaps
you've visited dontdatehimgirl.com. Computers let us share photos with our families and map
directions to the nearest pizza place for dinner.
Lots of real-world problems are being solved by computers, some of which don't much resemble
the one on your desk or lap. The human genome is sequenced and searched for DNA patterns using
powerful computers. There are computers in recently manufactured cars, monitoring each vehicle's
status and motion. Digital music players such as Apple's iPod are actually computers underneath
their small casing. Even the Roomba vacuum cleaning robot houses a computer with complex
instructions about how to dodge furniture while cleaning your floors.
But what makes a computer a computer? Is a calculator a computer? Is a human being with a paper
and pencil a computer? The next several sections attempt to address this question while leading us
toward putting computers in our command through programming.
Program
One key feature that differentiates a computer from a simpler machine like a calculator is its
versatility. The same computer can perform many different tasks (playing games, computing
income taxes, connecting to other computers around the world) depending on what program it is
running at a given moment. A computer can run not only the programs that exist on it currently but
also new programs that haven't even been written yet.
12
Computer programs are collectively called software. The primary piece of software running on a
computer is its operating system. An operating system provides an environment where many
application programs may be run at the same time, as well as providing a bridge between those
programs and the hardware and user. The programs that run inside the operating system are often
called applications.
When the user selects a program to be run by the operating system (such as by double-clicking the
icon of that program on the desktop), several things happen. The instructions for that program are
loaded into the computer's memory from the hard disk. The operating system allocates memory for
that program to use. The instructions of the program are fed from the memory to the CPU and
executed sequentially.
Digital
Based on numbers that increase in discrete increments such as the integers (0, 1, 2, 3, etc).
Because computers are digital, everything that is stored on a computer is stored as a sequence of
integers. This includes every program and every piece of data. The idea of representing everything
as an integer was fairly unusual in the 1940's when the first computers were built. This idea seems
less unusual today now that we have digital music, digital pictures and digital movies. An mp3 file,
for example, is simply a long sequence of integers that stores audio information.
Not only are computers digital, storing all information as integers, they are also binary, which
means that those integers are stored as binary numbers.
Binary Number
A number composed of just 0's and 1's, also known as a base-2 number.
Humans generally work with decimal or base-10 numbers. It might seem odd that computers use
binary numbers when people are so used to base-10 numbers, but we use base-10 because it
matches our physiology (10 fingers and 10 toes). In the case of computers, we want a system that
will be easy to create and that will be very reliable. It turns out to be simpler to build a system on
top of binary phenomena (e.g., a circuit being open or closed) than to build it on a system with ten
different states to distinguish (e.g., 10 different voltage levels).
From a mathematical point of view, you can store things just as easily using binary numbers as you
can using base-10 numbers. Since it is easier to construct the physical device using binary numbers,
that's what computers use.
13
It does mean, however, that people who aren't used to computers often encounter unfamiliar
conventions. As a result, it is worth spending a little time reviewing how binary numbers work. In
binary you start with 0 and you can count up, just like you do in base-10, but you run out of digits
much faster. So counting in binary you say:
0
1
And already you've run out of digits. This is like reaching 9 when you count in base 10. After you
run out of digits, you carry over to the next digit. So the next two numbers are:
10
11
And again we have run out of digits. This is like reaching 99 in base 10. So again we carry into the
next digit to form the 3-digit number 100. In binary, whenever you see a series of ones as in 111111,
you know you're just one away from the digits all flipping to 0 with a 1 in front, in the same way
that in base-10 when you see a number like 999999, you know that you are one away from those
digits turning to 0 with a 1 in front. The following table shows how we would count up to the base-
10 number 16 using binary.
decimal binary decimal binary
----------------- -----------------
0 0
1 1 9 1001
2 10 10 1010
3 11 11 1011
4 100 12 1100
5 101 13 1101
6 110 14 1110
7 111 15 1111
8 1000 16 10000
There are several useful observations to make about binary numbers. Notice in the table above that
the binary numbers 1, 10, 100, 1000, 10000 are all perfect powers of 2 (20 , 21, 22, 23, 24 ). In the same
way that in base-10 we talk about a one's digit, ten's digit, hundred's digit and so on, we can think
in binary of a one's digit, two's digit, four's digit, eight's digit, sixteen's digit and so on.
Computer scientists quickly found themselves needing to refer to the sizes of different binary
quantities so we invented the term bit to refer to a single binary digit and the term byte to refer to 8
bits. To talk about large amounts of memory, we talk about kilobytes (KB), megabytes (MB),
gigabytes (GB) and so on. Many people think that these correspond to the metric system where
"kilo" means 1000, but that is only approximately true. We use the fact that 210 is appromixately
equal to 1000 (it actually equals 1024). So a kilobyte is 210 bytes (1024 bytes), a megabyte is 220 bytes
(1,048,576 bytes), a gigabyte is 230 bytes (1,073,741,824 bytes) and so on.
14
Why Programming?
At most universities the first course in computer science is predominantly a programming course.
Many computer scientists are bothered by this because it leaves people with the impression that
computer science = programming. While it is true that many trained computer scientists spend time
programming, there is a lot more to the discipline than just programming. So why do we study
programming first?
A Stanford computer scientist named Don Knuth answers this question by saying that the common
thread to most of computer science is that we all in some way work with algorithms.
Algorithm
Knuth is an expert in algorithms, so he would naturally be biased to think of them as the center of
computer science. He claims that what is most important is not the algorithms themselves, but
rather the thought process that computer scientists employ. Knuth has said:
It has often been said that a person does not really understand something until after teaching
it to someone else. Actually a person does not really understand something until after
teaching it to a computer, i.e., expressing it as an algorithm.
Knuth is describing a thought process that is common to most of computer science which he refers
to as algorithmic thinking. So we study programming not because it is the most important aspect of
computer science, but because it is the best way to explain the approach computer scientists take to
solving problems.
Program Execution
The process of execution is often called running. It can be used as a verb, "When my program runs it
does something strange. . .," or as a noun, "The last run of my program produced these results. . ."
Computer programs are stored internally as a series of binary numbers known as the machine
language of the computer. In the early days programmers entered numbers like these directly into
the computer. Obviously this is a tedious and confusing way to program a computer and we have
invented all sorts of mechanisms to simplify this process.
15
Modern programmers write in what are known as high-level programming languages like Java.
Such programs cannot be run directly on a computer. They first have to be translated into a
different form by a special program known as a compiler.
Compiler
A program that translates a computer program written in one language into an equivalent
program in another language (often, but not always, translating into machine language).
A compiler that translates directly into machine language creates a program that can be executed
directly on the computer. We refer to such a program as an executable and we refer to such
compilers as native compilers because they compile code to the lowest possible level (the native
machine language of the computer).
This approach works well when you know exactly what computer you want your program to
execute on. But what if you want to execute a program on many different computers? Using this
approach you'd need a compiler that generates different machine language output for each
different computer. The designers of Java decided to use a different approach. They cared a lot
about being able to run on many different computers because they wanted to have a language that
worked well for the web. People who write applets (Java programs that live inside web pages) want
those programs to run on many different computers.
Instead of compiling into machine language, Java programs are compiled into what are known as
Java bytecodes. These bytecodes represent an intermediate level. They aren't quite as high-level as
Java but they also aren't quite as low-level as machine language. The key thing is that one set of
bytecodes can execute on many different machines. Java bytecodes are similar to machine language.
In fact, they are the machine language of a theoretical computer known as the Java Virtual Machine
or JVM.
This isn't an actual machine but it's similar to actual machines. By compiling down to this level,
there isn't as much work left to turn the Java bytecodes into actual machine instructions.
In the Java programming language, nothing can exist outside of what is called a class.
Class
The notion of a class is much richer than this as we'll see when we get to Chapter 8, but for now all
we need to know is that each of our Java programs will be stored in a class.
To actually execute a Java class file, you need another program that will execute the Java bytecodes.
Such programs are known generically as Java runtimes and the standard environment distributed
by Sun is known as the Java Runtime Environment.
16
Java Runtime Environment (JRE)
Most people have a Java runtime on their computer even if they don't know about it. For example,
Apple's OS X includes a Java runtime and the standard Windows installer from Microsoft installs a
Java runtime.
Why Java?
When Sun Microsystems released Java in 1995, they published a document called a "white paper"
describing their new programming language. Perhaps the key sentence from that paper is the
following:
This sentence covers many of the reasons we'll be using Java as our programming
language in this textbook. Java is reasonably simple for beginners to learn. Java
embraces object-oriented programming, a style of writing programs that has been
shown to be very successful for creating large and complex software.
Java also includes a large amount of pre-written software that programmers can
utilize to enhance their programs. Such off-the-shelf software components are often
called libraries. For example, if you wish to write a program that connects to a site on
the internet, Java contains a library to simplify the connection for you. Java contains libraries to
draw graphical user interfaces, retrieve data from databases, and perform complex mathematical
computations, among many other things. These libraries collectively are called the Java class
libraries.
Java's collection of pre-existing code that provides solutions to common programming problems.
The richness of Java's class libraries are an extremely important factor in the rise of Java as a
popular language. As of version 1.5, the class libraries include over 3200 entries.
Another reason to use Java is that it has a vibrant programmer community. There is a large amount
of online documentation and tutorials available to help programmers learn new skills. Many of
these documents are written by Sun themselves, such as an extensive reference to Java's class
libraries called the API Specification (where "API" stands for Application Programming Interface).
Java is extremely platform-independent; unlike programs written in many other languages, the
same Java program can be executed on many different operating systems such as Windows, Linux,
and Macintosh.
17
Java is used extensively by programmers for both research and business applications. This means
that a large number of programming jobs exist in the marketplace today for skilled Java
programmers. A sample Google search for the phrase "Java jobs" returns 124,000,000 hits.
The basic unit of storage on most computers is a file. Every file has a name. A file name ends with
an extension, which is the part of a file's name that follows the period. A file's extension indicates the
type of data contained in the file. For example, files with extension .doc are Microsoft Word
documents, and files with extension .mp3 are MP3 audio files.
You will create files whose contents are Java programs. Java program files must use the
extension .java. When you compile a Java program, the resulting Java bytecodes are stored in a file
with the same name and the extension .class.
Most Java programmers use what are known as Integrated Development Environments or IDEs
that provide an all-in-one environment for creating, editing, compiling and executing program files.
Some of the more popular choices for introductory computer science classes are Eclipse, DrJava,
BlueJ and TextPad. Your instructor will tell you what environment you should use.
Don't worry about the details of this program right now. We will explore that in the next section.
Once you have typed in a program file, you move to step 2 and compile it. The command to
compile will be different in each different development environment, but the process is the same.
You have to submit your class file to the compiler for translation (typical commands are "compile"
or "build"). There might be errors, in which case you'd have to go back to the editor and fix the
errors and try to compile again. We'll discuss errors in more detail later in this chapter.
Once you have successfully compiled your program, you are ready to move to step 3 by running
the program. Again, the command to do this will differ from one environment to the next, but the
process is similar (the typical command is "run").
18
The following diagram summarizes the steps we would follow in creating a program named
Hello.java:
Console Window
A special text-only window in which Java programs interact with the user.
The console window is a classic way to interact with computers where the computer displays text
on the screen and sometimes waits for the user to type responses. This is known as console or
terminal interaction. The text typed by the computer in the console window is known as the output
of the program. Anything typed by the user is known as the console input.
To keep things simple, most of the sample programs in this book involve console interaction.
Keeping the interaction simple will allow us to focus our attention and effort on other aspects of
programming. For those who are interested, Chapter 10 describes how to write programs that use a
more modern kind of interface known as a Graphical User Interface or GUI.
19
1.2 And Now--Java
It's time to look at a complete Java program. It is a tradition in computer science that when you
describe a new programming language, you should start with a program that produces a single line
of output with the words, "Hello, world!" The hello world tradition has been broken by many
authors of Java books because the program turns out not to be as short and simple when written in
Java.
This defines a class called Hello. Sun has established the convention that class names always begin
with a capital letter, which makes it easy to recognize that something is the name of a class. Java
requires that the class name and the file name match, so this would have to be stored in a file called
Hello.java. Fortunately, you don't have to understand all of the details of this program just yet. But
you do need to understand the basic structure.
Remember that the basic unit of code in Java is the class. Every program must be contained within a
Java class. The basic form of a Java class is as follows.
The description above is known as a syntax template because it describes the basic form of a Java
construct. Java has rules that determine its legal syntax or grammar. Each time we see a new
element of Java, we'll begin by looking at its syntax template. By convention, we use the characters
less-than ("<") and greater-than (">") in a syntax template to indicate items that need to be filled in.
In this case the name of the class and the methods both need to be filled in. When we write "..." in a
list of elements, we're indicating that any number of those elements may be included.
The first line of the class is known as the class header. The word public in the header indicates that
this class is available to anyone to use. Notice that the program code in a class is enclosed in curly
brace characters. The curly brace characters are used in Java to group together related bits of code.
Grouping Characters
The curly brace characters { and } used in Java to group together related lines of code.
In this case, the curly braces are indicating that everything defined inside these braces is part of this
public class.
20
Discovering Diverse Content Through
Random Scribd Documents
cords and let the victim down.
“He fell in a helpless heap on the floor, all hope and courage
crushed out of him, and wept and sobbed like a child. If it had been
wife and child for whom he had suffered any one must have wept
with him.”
“It was wife and child and country to him,” Ethne murmured; “it
was the double glamour which bewildered him—the hideous curse of
Mammon and the fond dream of affection. But what of Miriam?”
“She knelt down beside him,” Marius said, “the noble Jewish
woman. She threw her arms around him and sustained him; she
took his poor wounded hands and held them to her heart; she
sobbed out every tender name she could; I understood them by the
tones, though the words were in their own Hebrew. There was
tender reverence in her every gesture, even more than affection;
and turning to me, she said, in a tone almost of triumph, ‘It is not
himself, it is his deadliest enemy they have slain. And now he will be
himself again.’ And she added, ‘Thy wife will understand!’”
“I do understand,” Ethne said, with a victorious radiance like a
halo on her face; “and I have found him his true gold! I have found
his child! The idol is broken, but the dream of love shall prove true.”
The next morning she crept quietly into the chamber where they
had left Eleazar and Miriam. The old man had fallen at last into a
heavy sleep. Miriam was sitting on the floor beside him, holding one
of his hands. Ethne sat down beside her, and for some minutes said
nothing.
“The evil spirit has gone out of him,” Miriam said. “You see, he
sleeps as sweetly as a child.”
“And the lost child is coming to him,” Ethne answered. “Coming to
you both, mother and father! Your Rachel is found.”
Miriam started as if she had seen a spirit, fixing her dark eyes with
passionate intensity on the sweet grey eyes of Ethne. Her whole
frame quivered.
“Lady! child!” she said. “To thee, I know, it would be impossible to
lie, even in the fond hope of binding up a broken heart. You would
always know that nothing but truth could heal the wounded spirit, or
bind up the broken heart. Nothing but the love which is true—
nothing but God.”
“Nothing but God, Who is Truth and Love,” Ethne said, with her
infectious smile; “Who has heard thy prayers and seen thy tears all
through these weary years; Who gave thee compassion which made
thee good as an angel to me. He has led me to thy child.”
And then she told Miriam the story of Rachel.
As early as possible on the morrow Ethne and Marius went to the
farm on the mountains, and there they found Rachel amongst her
children; the dark-eyed boys, and one fair, golden-haired baby girl.
Father, mother, and children at once came down the hills to the villa
of Fabricius. There, by many tokens, the mother recognized her
child, whilst by an instinctive sympathy their hearts drew together.
When Eleazar awoke, the little group around him, Rachel and her
sons, and the golden-haired babe on Miriam the grandmother’s
knee, were beside him.
“Who are these?” he said, starting up, with eyes wide open and
bewildered, yet with a dawning consciousness in them, like one
waking out of a dream.
“It is only thy Rachel, our Rachel, and her children,” Miriam said,
in tender, quiet tones, caressing the little one on her knee. “Thou
hast always known they would come, and now, see, they are here!”
“Is it Paradise?” he said. “Are we in the garden of God?”
“Nay, beloved,” Miriam replied, very quietly, “except as every true
marriage brings us back to Eden.”
Then he began gradually to return to full, quiet consciousness,
and rising on the couch, he said—
“My Rachel! And all the dowry, all the treasure I had saved for
thee is gone.” Then burying his face in his hands, the old man wept,
quiet, natural tears.
But his daughter knelt beside him, and gently drawing down his
hands, laid her babe in his arms.
“Father,” she said, “see, the God of our fathers has given us the
gift and inheritance that cometh of the Lord.”
And her husband, standing behind her, laid his hand on her head
and said—
“See, here is thy hid treasure. Truly thou hast given the best jewel
in the world to me.”
“What to us were gold and silver?” Rachel pleaded. “God has
given us the babes, and also the old riches of our race, the riches of
Abraham our father. We are rich in flocks and herds. Wilt thou not
come and see?”
And the old man laid his trembling hands on her head, and said—
“The Lord hath taken away, and the Lord hath given; blessed be
the name of the Lord.”
CHAPTER XXIX.
ENDINGS AND BEGINNINGS.
“débordante, frénétique,
Inconvenante; ici le nain, là le géant,
Tout à la fois.”
But
“The fountain indeed rises and rises in thy Ireland,” Marius would
say; “it is becoming a lake, a sea, the source of how many fountains
who can say?”
And Ethne—“How can we ever foresee where the new fountains
will spring up?”
“No more,” he replied, “than I could foresee thee.”
They did not indeed live to see how high the fountains would rise,
or how far they would flow. They did not live to hear the great
proclamation of freedom go forth from the lips of the great Leo’s
successor, the great Gregory, at the manumission of his own slaves,
basing the freedom of all men on the creation of man in the image
of God, and the Incarnation of the Son in the form of man. They did
not indeed live to see the living waters from the two fountains flow
forth throughout Western Christendom till they met in our English
land, from the great missions of the Benedictines and of the monks
of Iona; the era of the great monks and abbots succeeding the era
of the great bishops. But they saw their Paul enter the white-robed
company of their young kinsman Benedict on Monte Cassino; and
they gave their John to join the first-born of Baithene in the great
Irish monastery, which nurtured and sent forth Columba. And day by
day they and their children pressed onward, in the city, in the
solitude, in the home, armed with the breastplate of Patrick’s hymn
—
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookfinal.com