Java 1 Basic syntax and semantics Software Development Poul Klausen - The ebook in PDF and DOCX formats is ready for download
Java 1 Basic syntax and semantics Software Development Poul Klausen - The ebook in PDF and DOCX formats is ready for download
com
https://ebookmeta.com/product/java-1-basic-syntax-and-
semantics-software-development-poul-klausen/
OR CLICK HERE
DOWLOAD EBOOK
https://ebookmeta.com/product/exploring-the-syntax-and-semantics-of-
south-asian-languages-1st-edition-reena-ashem/
ebookmeta.com
https://ebookmeta.com/product/java-17-quick-syntax-reference-3rd-
edition-mikael-olsson/
ebookmeta.com
https://ebookmeta.com/product/nosql-and-sql-data-modeling-bringing-
together-data-semantics-and-software-first-edition-hills/
ebookmeta.com
https://ebookmeta.com/product/religion-in-america-the-basics-2nd-
edition-michael-pasquier/
ebookmeta.com
The Sun Dragon First Edition,New Edition Jay Annabelle
https://ebookmeta.com/product/the-sun-dragon-first-editionnew-edition-
jay-annabelle/
ebookmeta.com
https://ebookmeta.com/product/candlelight-promise-a-kwanzaa-kisses-
holiday-romance-1st-edition-lia-violet/
ebookmeta.com
https://ebookmeta.com/product/selling-and-sales-management-11e-11th-
edition-david-jobber/
ebookmeta.com
https://ebookmeta.com/product/trauma-and-motherhood-in-contemporary-
literature-and-culture/
ebookmeta.com
https://ebookmeta.com/product/modified-posterior-approach-to-the-hip-
joint-2nd-edition-k-mohan-iyer/
ebookmeta.com
Resurrected as a Drow 2 1st Edition Logan Jacobs
https://ebookmeta.com/product/resurrected-as-a-drow-2-1st-edition-
logan-jacobs/
ebookmeta.com
Poul Klausen
1st edition
ISBN 978-87-403-1689-6
Contents
Foreword 6
1 Introduction 8
2 Hello World 11
2.1 NetBeans 11
2.5 Gedit 19
Exercise 1 23
Exercise 2 23
3.1 Commands 24
Problem 1 28
Problem 2 32
Exercise 3 38
4.1 Operators 38
Exercise 4 44
Exercise 5 45
4.2 Literals 46
4.3 Objects 49
Exercise 6 59
Problem 3 59
Exercise 7 65
4.5 Arrays 67
Exercise 8 71
Exercise 9 78
5 Program control 79
Exercise 10 81
Problem 4 82
Problem 5 83
5.2 do and while statements 84
Exercise 11 85
Problem 6 87
Exercise 12 92
Exercise 13 92
Problem 7 94
Exercise 14 96
Problem 8 101
Problem 9 102
6 ArrayList 104
7 Comparison and sorting 107
8 Files 114
Exercise 16 121
Appendix A 131
Foreword
This book is the first in a series of books on software development.
The programming language is Java, and the language and its syntax
and semantics fills obviously much, but the books have also largely
focus on the process and how to develop good and robust
applications. The subject of the current book is an introduction to
the programming language Java with an emphasis on basic language
syntax and semantics, but it is also a book about what programming
in general is and how to practically write and test simple programs.
The book requires no knowledge about programming or the
language Java, and the goal is to show how to get started writing
computer programs. After reading the book and worked through the
book’s exercises and problems, the reader should be able to write
simple console applications in the language Java.
All books ends with one or two larger sample programs, which focus
primarily is on process and an explanation of how the program is
written. On the other hand appears the code only to a limited extent
– if at all – and the reader should instead study the finished program
code perhaps while testing the program. In addition to show the
development of programs that are larger than the examples, which
otherwise is presented, the aim of the concluding examples also is to
show program examples from varying fields of application.
Most books also ends with an appendix dealing with a subject that
would not be treated in the books. It may be issues on the
installation of software or other topics in computer technology, which
are not about software development, but where it is necessary to
have an introductory knowledge. If the reader already is familiar
with the subject, the current appendix can be skipped.
The programming language is, as mentioned Java, and besides the
books use the following products:
It is products that are free of charge and free to install, and there is
even talk about products, where the installation is progressing all by
itself and without major efforts and challenges. In addition, there
are on the web detailed installation instructions for all the three
products. The products are available on Windows and Linux, and it
therefore plays no special role if you use Linux or Windows.
When you have to write software, you need a tool that can be used
to enter the program code, and in principle you could use a simple
input program (a text editor) and then the compiler, but in practice
you will always use a specific development tool, as it makes the job
much easier. In the following I will everywhere use NetBeans, a
development tool for a wide variety of tasks, including writing code
in Java. It is an integrated software package, which includes all the
tools necessary for the development of a number of different types
of programs.
it is a simple language
it is an object-oriented language
All Java code are as mentioned written as plain text files – which
filename must have the extension .java – and then these files are
translates to .class files. The translation is performed by the Java
compiler called javac. Java class files do not contain machine code
for a particular platform, but rather so-called bytecode, which is the
machine code for the Java Virtual Machine, which is a virtual
computer, commonly referred to as VM or JVM. The program
(consisting of a set of class files) can then be carried out by the
virtual machine, which is a program that is running on a particular
machine. Since Java and thus the virtual machine is available for
many different operating systems, the same class files can run on
many machines for example Windows, Solaris, Linux, etc.
I’ll start with the classic Hello World program, a program that prints a
text on the screen. It is an example of a command, but it is also an
example of a program that has absolutely no practical interest. Although
it is a simple program, it will nevertheless treat a number of basic
principles that apply to all Java programs.
2.1 NetBeans
As mentioned a Java program is written as text files, which will then be
translated. When the files are translated without errors the program can
be executed by the virtual machine. In practice is always used a
development tool, which is a program or software package that
integrates all the functions that a developer needs. Such a tool is usually
called an IDE (Integrated Development Environment), and there are
several, but I will everywhere use NetBeans, which contains everything
that is needed, and the following requires that both Java and NetBeans
are installed on the machine. Do not have it, you can start by reading
Appendix A which explains how to download and install both Java and
NetBeans.
To write the first Java program, open NetBeans and create a new
project. In the menu, choose
Here I:
Entered HelloWorld as Protect Name
Regarding the latter, it is just a question that I have decided that the
project should be created in the /home/pa/doc/notes/note01 direcory. I
have also decided that the project should be called HelloWorld. NetBeans
will then create a folder
/home/pa/doc/noter/note01/HelloWorld
and all project files are placed by NetBeans in this folder. You should
note that there is a checkmark in the Create Main Class, which is
important.
When you then click Finish, the project is created and NetBeans displays
multiple windows:
Projects window, where all the project’s components are organized in
a hierarchy
Source Editor contains the program’s code, and as you can see,
NetBeans automatically creates a skeleton for a program. Actually, it’s a
full-fledged program – it performs nothing not yet. The program code
consists of Java statements and comments. Comments are removed by
the compiler and does not affect the finished program. They are inserted
solely for the sake of us people who should read and understand the
program code.
There is only one comment back, which is at the top and says something
about what the program does. The rest of the code is Java statements. A
Java program consists of classes, and in this case there is one class
called HelloWorld and thus has the name that I chose as project name.
The class consists of a method called main(), which has a single
statement – not created by NetBeans, but as I entered. It is a statement
that prints a text on the screen.
The code is simple, and so far you just accept that it should be written,
as shown above, but there is however a few things that you should note.
Note that in Java, each statement ends with a semicolon – above there
is a semicolon after System.out.println(). It tells the compiler where a
statement ends.
The program then is not performed, and the translator instead offers an
error message, and the error must then be corrected before trying to run
the program again.
and the program is translated again, and if you opens Files you will
discover that that there is created another folder called dist, which
contains two files (see below). Here is HelloWorld.jar a package (actually
a compressed zip file) containing the program files – only the translated
class files and other ancillary files that are necessary for the program to
run. In this case, there are actually only two.
If you copy the file HelloWorld.jar to a folder – for example temp – and if
you open a Terminal, stand in this folder and perform the following
command:
Here the command java is a message to Linux to start the Java runtime
system and execute the program HelloWorld.
2.5 gedit
Above I have written and performed a Java program using NetBeans,
and in the following, all programs will be developed in this way.
NetBeans is a large and complex program, and until this place, you have
seen only a very small fraction of what the program can. The program is
relatively user-friendly, and I will not give any general description of the
program and its possibilities, but I will mention important features as I
need them in the individual examples. NetBeans is similar to all other
IDEs for software development, so the forces you use to learn more
about the program, is definitely not wasted. Using an IDE for developing
applications provides in practice such large benefits that it makes no
sense to develop programs in other ways, but in principle you can, and I
will in this section show how to write the program Hello World without
NetBeans.
When the program is written, I save it in the folder Hello and call it
HelloWorld.java. Again, please note upper and lower case and the
filename must have the extension java written in lower case. Then I
open a Terminal and set the current directory to the folder Hello. Here I
performs the following command:
javac is the name of the compiler, and the result is that the program is
being translated, and creates a file with the translated program called
HelloWorld.class:
There are three types of comments. The first starts with /* and ends
with */ and everything in between these character combinations is
considered as a comment, for example
This is the syntax for inserting comments in the code, but a whole other
thing is what you should write. Also I come back to that later, but
generally you have to write what you think might be valuable at a later
reading of the code. What it is, is certainly not unique, and it can be
good inspiration to examine what comments others have inserted into
programs.
Exercise 1
Write a program, as you can call Digits, that on the screen prints the
following table:
Exercise 2
Write a program that you can call Label, that prints your name, your
address and your email address, for example
3 Commands and console
programs
In the previous section I divided the programs into three categories,
and in this chapter I will look at commands and console programs. In
principle there is no big difference, and the division alone has to do
with how the user is transferring data to the program. Both
HelloWorld and the example Kings from the previous chapter are
examples of commands.
3.1 Commands
Every Java program must have a main() method that has the
following signature:
For the moment you should ignore the meaning of the words public,
static and void and just accept that they should be there, but the
main() method is the place where the program starts. After the
method name is a parameter in parentheses, indicating arguments
from the command line that can be transferred to the program.
Consider the following program:
args is an array, as I explains later, but the arguments that are
transferred on the command line, are in the program referred to as
There are two arguments, called respectively Svend and Knud, and
the program prints the two arguments of the screen. If you execute
the program in the following way:
the result is the same. This time there is three arguments, but only
the first two are used in the program. If, however, the application
performs without having two arguments, you get an error:
The reason is that the second argument does not exist, and therefore
fails the statement:
Here you must select the category Run, where you will be able to
enter the arguments:
Note that contains the argument spaces, it is necessary to specify
them in quotes.
A program like the above are not robust, as it will fail if not
transferred the right number of arguments. You should also note that
the program does not test the arguments (which incidentally is also
not so easy), but simply prints the arguments as they are.
Problem 1
You should write a program for a library that can print a recall of a
book. When the program is executed, you must on the command line
transfer five arguments:
borrower’s name
borrower’s address
Above I have shown a program that prints the name and address of a
person when the values are passed as arguments on the command
line. Below is the same program, but this time the user must enter
the values during running the program. There is thus a dialogue with
the user.
As you can see, the code has been substantially larger, and there is
also new things that has to be explained.
To enter text, you must have an object that represents the keyboard
and provides a service available for entering text. In addition I apply
a Scanner that use the objekt System.in that just represents the
keyboard. Scanner is a class that is not readily available, and
therefore there is added an import statement that refers to the
package containing the class Scanner. in is then an object that can
be used to enter a text. The next line prints a text on the screen,
telling the user to enter the name. It happens with
The text that the user enters, must be stored somewhere, and for
that purpose a variable is used. Variables are considered in the next
chapter, but a variable is a place where you can store a value. An
example could be the statement
Here, the text that the user enters is stored in the variable name. The
next statements are identical in principle and are used for entering
other values. The last statements are used to print the result and is
similar in principle to the previous version of the program, but the
arguments args[0], args[1], … are replaced with variables. If you run
the program (from NetBeans), the result could be as shown below:
borrower’s name
borrower’s address
when then the program is running in a dialogue with the user. The
program should print the same recall as in problem 1.
4 Variables and data types
Programs has to deal with data, and for that they need a way where
to save or store data. To that purpose programs use variables that
are items, where the program may store a value. You must note that
I have already used variables associated with data entry. A variable is
characterized by
a name
a type
operators
Yet it is difficult not to believe that the ideal in which our author’s spirit
might most gratefully have rested would have been the character of the
paterfamilias, when the eye falls on such a charming piece of observation as
these lines about children in the admirable paper on Child’s Play:
“If it were not for this perpetual imitation we should be tempted to fancy they despised
us outright, or only considered us in the light of creatures brutally strong and brutally silly,
among whom they condescended to dwell in obedience, like a philosopher at a barbarous
court.”
II
We know very little about a talent till we know where it grew up, and it
would halt terribly at the start, any account of the author of Kidnapped
which should omit to insist promptly that he is a Scot of the Scots. Two
facts, to my perception, go a great way to explain his composition: the first
of which is that his boyhood was passed in the shadow of Edinburgh Castle,
and the second that he came of a family that had set up great lights on the
coast. His grandfather, his uncle, were famous constructors of lighthouses,
and the name of the race is associated above all with the beautiful and
beneficent tower of Skerryvore. We may exaggerate the way in which, in an
imaginative youth, the sense of the “story” of things would feed upon the
impressions of Edinburgh—though I suspect it would be difficult really to
do so. The streets are so full of history and poetry, of picture and song, of
associations springing from strong passions and strange characters, that, for
our own part, we find ourselves thinking of an urchin going and coming
there as we used to think (wonderingly, enviously), of the small boys who
figured as supernumeraries, pages or imps, in showy scenes at the theatre:
the place seems the background, the complicated “set” of a drama, and the
children the mysterious little beings who are made free of the magic world.
How must it not have beckoned on the imagination to pass and repass, on
the way to school, under the Castle rock, conscious, acutely yet familiarly,
of the gray citadel on the summit, lighted up with the tartans and bagpipes
of Highland regiments? Mr. Stevenson’s mind, from an early age, was
furnished with the concrete Highlander, who must have had much of the
effect that we nowadays call decorative. We have encountered somewhere a
fanciful paper[3] of our author’s, in which there is a reflection of half-
holiday afternoons and, unless our own fancy plays us a trick, of lights red,
in the winter dusk, in the high-placed windows of the old town—a
delightful rhapsody on the penny sheets of figures for the puppet-shows of
infancy, in life-like position and awaiting the impatient yet careful scissors.
“If landscapes were sold,” he says in Travels with a Donkey, “like the sheets
of characters of my boyhood, one penny plain and twopence coloured, I
should go the length of twopence every day of my life.”
Indeed the colour of Scotland has entered into him altogether, and
though, oddly enough, he has written but little about his native country, his
happiest work shows, I think, that she has the best of his ability, the best of
his ambition. Kidnapped (whose inadequate title I may deplore in passing)
breathes in every line the feeling of moor and loch, and is the finest of his
longer stories, and Thrawn Janet, a masterpiece in thirteen pages (lately
republished in the volume of The Merry Men), is, among the shorter, the
strongest in execution. The latter consists of a gruesome anecdote of the
supernatural, related in the Scotch dialect, and the genuineness which this
medium (at the sight of which, in general, the face of the reader grows long)
wears in Mr. Stevenson’s hands is a proof of how living the question of
form always is to him, and what a variety of answers he has for it. It would
never have occurred to us that the style of Travels with a Donkey or
Virginibus Puerisque and the idiom of the parish of Balweary could be a
conception of the same mind. If it be a good fortune for a genius to have
had such a country as Scotland for its primary stuff, this is doubly the case
when there has been a certain process of detachment, of extreme
secularisation. Mr. Stevenson has been emancipated: he is, as we may say, a
Scotchman of the world. None other, I think, could have drawn with such a
mixture of sympathetic and ironical observation the character of the canny
young Lowlander, David Balfour, a good boy but an exasperating. Treasure
Island, The New Arabian Nights, Prince Otto, Doctor Jekyll and Mr. Hyde,
are not very directly founded on observation; but that quality comes in with
extreme fineness as soon as the subject involves consideration of race.
I have been wondering whether there is something more than this that
our author’s pages would tell us about him, or whether that particular
something is in the mind of an admirer because he happens to have had
other lights on it. It has been possible for so acute a critic as Mr. William
Archer to read pure high spirits and the gospel of the young man rejoicing
in his strength and his matutinal cold bath between the lines of Mr.
Stevenson’s prose. And it is a fact that the note of a morbid sensibility is so
absent from his pages, they contain so little reference to infirmity and
suffering, that we feel a trick has really been played upon us on discovering
by accident the actual state of the case with the writer who has indulged in
the most enthusiastic allusion to the joy of existence. We must permit
ourselves another mention of his personal situation, for it adds immensely
to the interest of volumes through which there draws so strong a current of
life, to know that they are not only the work of an invalid, but that they
have largely been written in bed, in dreary “health-resorts,” in the intervals
of sharp attacks. There is almost nothing in them to lead us to guess this: the
direct evidence indeed is almost all contained in the limited compass of The
Silverado Squatters. In such a case, however, it is the indirect that is the
most eloquent, and I know not where to look for that, unless in the paper
called “Ordered South,” and its companion “Aes Triplex,” in Virginibus
Puerisque. It is impossible to read “Ordered South” attentively without
feeling that it is personal: the reflections it contains are from experience, not
from fancy. The places and climates to which the invalid is carried to
recover or to die are mainly beautiful, but
“In his heart of hearts he has to confess that [they are] not beautiful for him.... He is
like an enthusiast leading about with him a stolid, indifferent tourist. There is some one by
who is out of sympathy with the scene, and is not moved up to the measure of the occasion;
and that some one is himself.... He seems to himself to touch things with muffled hands
and to see them through a veil.... Many a white town that sits far out on the promontory,
many a comely fold of wood on the mountain side, beckons and allures his imagination
day after day, and is yet as inaccessible to his feet as the clefts and gorges of the clouds.
The sense of distance grows upon him wonderfully; and after some feverish efforts and the
fretful uneasiness of the first few days he falls contentedly in with the restrictions of his
weakness.... He feels, if he is to be thus tenderly weaned from the passion of life, thus
gradually inducted into the slumber of death, that when at last the end comes it will come
quietly and fitly.... He will pray for Medea: when she comes let her either rejuvenate or
slay.”
The second of the short essays I have mentioned has a taste of mortality
only because the purpose of it is to insist that the only sane behaviour is to
leave death and the accidents that lead to it out of our calculations. Life “is
a honeymoon with us all through, and none of the longest. Small blame to
us if we give our whole hearts to this glowing bride of ours.” The person
who does so “makes a very different acquaintance with the world, keeps all
his pulses going true and fast, and gathers impetus as he runs, until if he be
running towards anything better than wildfire, he may shoot up and become
a constellation in the end.” Nothing can be more deplorable than to “forego
all the issues of living in a parlour with a regulated temperature.” Mr.
Stevenson adds that as for those whom the gods love dying young, a man
dies too young at whatever age he parts with life. The testimony of “Aes
Triplex” to the author’s own disabilities is after all very indirect. It consists
mainly in the general protest not so much against the fact of extinction as
against the theory of it. The reader only asks himself why the hero of
Travels with a Donkey, the historian of Alan Breck, should think of these
things. His appreciation of the active side of life has such a note of its own
that we are surprised to find that it proceeds in a considerable measure from
an intimate acquaintance with the passive. It seems too anomalous that the
writer who has most cherished the idea of a certain free exposure should
also be the one who has been reduced most to looking for it within, and that
the figures of adventurers who, at least in our literature of to-day, are the
most vivid, should be the most vicarious. The truth is, of course, that as the
Travels with a Donkey and An Inland Voyage abundantly show, the author
has a fund of reminiscences. He did not spend his younger years “in a
parlour with a regulated temperature.” A reader who happens to be aware of
how much it has been his later fate to do so may be excused for finding an
added source of interest—something indeed deeply and constantly touching
—in this association of peculiarly restrictive conditions with the vision of
high spirits and romantic accidents, of a kind of honourably picaresque
career. Mr. Stevenson is, however, distinctly, in spite of his occasional
practice of the gruesome, a frank optimist—an observer who not only loves
life but does not shrink from the responsibility of recommending it. There is
a systematic brightness in him which testifies to this and which is after all
but one of the innumerable ingenuities of patience. What is remarkable in
his case is that his productions should constitute an exquisite expression, a
sort of whimsical gospel of enjoyment. The only difference between An
Inland Voyage or Travels with a Donkey and The New Arabian Nights or
Treasure Island or Kidnapped, is that in the later books the enjoyment is
reflective (though it simulates spontaneity with singular art), whereas in the
first two it is natural and, as it were, historical.
These little histories—the first volumes, if I mistake not, that introduced
Mr. Stevenson to lovers of good writing—abound in charming illustrations
of his disposition to look at the world as a not exactly refined but glorified,
pacified Bohemia. They narrate the quest of personal adventure, on one
occasion in a canoe on the Sambre and the Oise and on another at a
donkey’s tail over the hills and valleys of the Cévennes. I well remember
that when I read them in their novelty, upwards of ten years ago, I seemed
to see the author, unknown as yet to fame, jump before my eyes into a style.
His steps in literature presumably had not been many; yet he had mastered
his form—it had in these cases perhaps more substance than his matter—
and a singular air of literary experience. It partly, though not completely,
explains the phenomenon, that he had already been able to write the
exquisite little story of Will of the Mill, published previously to An Inland
Voyage, and republished to-day in the volume of The Merry Men, for in Will
of the Mill there is something exceedingly rare, poetical and unexpected,
with that most fascinating quality a work of imagination can have—a dash
of alternative mystery as to its meaning, an air (the air of life itself), of half
inviting, half defying you to interpret. This brief but finished composition
stood in the same relation to the usual “magazine story” that a glass of
Johannisberg occupies to a draught of table d’hôte vin ordinaire.
“One evening he asked the miller where the river went.... ‘It goes out into the lowlands,
and waters the great corn country, and runs through a sight of fine cities (so they say)
where kings live all alone in great palaces, with a sentry walking up and down before the
door. And it goes under bridges, with stone men upon them, looking down and smiling so
curious at the water, and living folks leaning on their elbows on the wall and looking over
too. And then it goes on and on, and down through marshes and sands, until at last it falls
into the sea, where the ships are that bring tobacco and parrots from the Indies.’ ”
MISS WOOLSON