Академический Документы
Профессиональный Документы
Культура Документы
(Download PDF) Java Quick Syntax Reference Second Edition Olsson Online Ebook All Chapter PDF
(Download PDF) Java Quick Syntax Reference Second Edition Olsson Online Ebook All Chapter PDF
Edition Olsson
Visit to download the full and correct content document:
https://textbookfull.com/product/java-quick-syntax-reference-second-edition-olsson/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...
https://textbookfull.com/product/c-7-quick-syntax-reference-a-
pocket-guide-to-the-language-apis-and-library-mikael-olsson/
https://textbookfull.com/product/c17-quick-syntax-reference-
apocket-guide-to-the-language-apis-and-library-2-edition-edition-
olsson/
https://textbookfull.com/product/c17-quick-syntax-reference-a-
pocket-guide-to-the-language-apis-and-library-third-edition-
olsson/
https://textbookfull.com/product/c-7-quick-syntax-reference-a-
pocket-guide-to-the-language-apis-and-library-2nd-edition-mikael-
olsson/
C++20 Quick Syntax Reference : a pocket guide to the
language, APIs, and library 4th Edition Mikael Olsson
https://textbookfull.com/product/c20-quick-syntax-reference-a-
pocket-guide-to-the-language-apis-and-library-4th-edition-mikael-
olsson/
https://textbookfull.com/product/c20-quick-syntax-reference-a-
pocket-guide-to-the-language-apis-and-library-4th-edition-mikael-
olsson-2/
https://textbookfull.com/product/php-8-quick-scripting-
reference-3rd-edition-mikael-olsson/
https://textbookfull.com/product/php-8-quick-scripting-reference-
a-pocket-guide-to-php-web-scripting-third-edition-mikael-olsson/
https://textbookfull.com/product/julia-quick-syntax-reference-a-
pocket-guide-for-data-science-programming-1st-edition-antonello-
lobianco/
For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.
Contents at a Glance
iii
■ Contents at a Glance
Index������������������������������������������������������������������������������������������������ 73
iv
Introduction
xiii
Chapter 1
Hello World
Installing
Before you can program in Java you need to download and install the Java Development
Kit (JDK) Standard Edition (SE) from Oracle’s website.1 Among other things, the JDK
includes the Java compiler, the class libraries and the virtual machine needed to run
Java applications. Oracle’s download page also has a link to obtain Netbeans2 bundled
with the JDK. Netbeans is an Integrated Development Environment (IDE) that will make
development in Java much easier. Alternatively, another free IDE you can use is Eclipse,3
or if you do not want to use any IDE at all a regular text editor will work just fine.
Creating a project
If you decide to use an IDE (recommended) you need to create a project, which will
manage the Java source files and other resources. Alternatively, if you prefer not to use an
IDE you can create an empty file with the .java extension, for example MyApp.java, and
open it in your text editor of choice.
To create a project in Netbeans, go to the File menu and select New Project. From the
dialog box select the Java Application project type under the Java category and click next.
On this dialog box set the project name to “MyProject” and the name of the main class to
“myproject.MyApp”. Change the project’s location if you want to, and then hit the Finish
button to generate the project. The project’s only file, MyApp.java, will then open up,
containing some default code. You can go ahead and remove all of that code so that you
start with an empty source file.
Hello world
When you have your project and programming environment set up the first application
you will create is the Hello World program. This program will teach you how to compile
and run Java applications, as well as how to output a string to a command window.
1
http://www.oracle.com/technetwork/java/javase/downloads/index.html
2
http://www.netbeans.org
3
http://www.eclipse.org
1
CHAPTER 1 ■ Hello World
The first step in creating this program is to add a public class to your MyApp.java
source file. The class must have the same name as the physical source file without the file
extension, in this case “MyApp”. It is legal to have more than one class per file in Java, but
only one public class is allowed, and that name must match the filename. Keep in mind that
Java is case sensitive. The curly brackets following the class name delimits what belongs to
the class and must be included. The brackets, along with their content, is referred to as a code
block, or just a block.
Next, add the main method inside the class. This is the starting point of the application
and must always be included in the same form as is shown below. The keywords themselves
will be looked at in later chapters.
The last step in completing the Hello World program is to output the text by calling
the print method. This method is located inside the built-in System class, and then
another level down inside the out class. The method takes a single argument – the string
to be printed – and it ends with a semicolon, as do all statements in Java.
Note that the dot operator (.) is used to access members of a class.
Code hints
If you are unsure of what a specific class contains, or what arguments a method takes,
you can take advantage of code hints in some IDEs, such as Netbeans. The code hint
window appears anytime you are typing code and there are multiple predetermined
alternatives. It can also be brought up manually by pressing Ctrl + Space. This is a very
powerful feature that gives you quick access to the whole class library and their members,
along with descriptions.
2
Chapter 2
By doing this the console will be able to find the Java compiler from any folder for the
duration of this console session. The PATH variable can also be permanently changed.1
Next, navigate to the folder where the source file is located and run the compiler by typing
“javac” followed by the complete filename.
javac MyApp.java
The program will be compiled into a class file called MyApp.class. This class file
contains bytecode instead of machine code, so to execute it you need to call the Java
Virtual Machine by typing “java” followed by the filename.
java MyApp
Notice that the .java extension is used when compiling a file, but the .class extension
is not used when running it.
1
http://www.java.com/en/download/help/path.xml
3
CHAPTER 2 ■ Compile and Run
Comments
Comments are used to insert notes into the source code and will have no effect on the
end program. Java has the standard C++ comment notation, with both single-line and
multi-line comments.
// single-line comment
/* multi-line
comment */
In addition to these, there is the Javadoc comment. This comment is used to generate
documentation by using a utility included in the JDK bin folder which is also called
Javadoc.
/** javadoc
comment */
4
Chapter 3
Variables
Data types
Depending on what data you need to store there are several kinds of data types. Java has
eight types that are built into the language. These are called primitives. The integer (whole
number) types are byte, short, int and long. The float and double types represent
floating-point numbers (real numbers). The char type holds a Unicode character and the
boolean type contains either a true or false value. Except for these primitive types, every
other type in Java is represented by either a class, an interface or an array.
Declaring variables
To declare (create) a variable you start with the data type you want it to hold followed by
a variable name. The name can be anything you want, but it is a good idea to give your
variables names that are closely related to the values they will hold. The standard naming
5
CHAPTER 3 ■ Variables
convention for variables is that the first word should be lowercase and any subsequent
words initially capitalized.
int myInt;
Assigning variables
To give the variable a value you use the assignment operator (=) followed by the value.
When a variable is initialized (assigned a value) it then becomes defined (declared and
assigned).
myInt = 10;
If you need multiple variables of the same type, there is a shorthand way of declaring
or defining them by using the comma operator (,).
Using variables
Once a variable has been defined it can be used by simply referencing the variable’s
name, for example to print it.
System.out.print(myInt);
Integer types
As shown earlier, there are four signed integer types that can be used depending on how
large a number you need the variable to hold.
6
CHAPTER 3 ■ Variables
Floating-point types
The floating-point types can store integers as well as floats. They can be assigned with
either decimal or exponential notation.
Note that constant floating-point numbers in Java are always kept internally as doubles.
Therefore, if you try to assign a double to a float you will get an error, because a double has
a higher precision than a float. To assign it correctly you can append an “F” character to the
constant, which says that the number is in fact a float.
A more common and useful way to do this is by using an explicit cast. An explicit
cast is performed by placing the desired data type in parentheses before the variable or
constant that is to be converted. This will convert the value to the specified type, in this
case float, before the assignment occurs.
Char type
The char data type can contain a single Unicode character, delimited by single quotes.
Chars can also be assigned by using a special hexadecimal notation that gives access
to all Unicode characters.
Boolean type
The boolean type can store a Boolean value, which is a value that can only be either true
or false. These values are specified with the true and false keywords.
7
CHAPTER 3 ■ Variables
Variable scope
The scope of a variable refers to the code block within which it is possible to use that
variable without qualification. For example, a local variable is a variable declared within
a method. Such a variable will only be available within the method’s code block, after it
has been declared. Once the scope (code block) of the method ends, the local variable
will be destroyed.
In addition to local variables, Java has field and parameter type variables, which
will be looked at in later chapters. Java does not, however, have global variables, as
for example does C++.
Anonymous block
The scope of local variables can be restricted by using an anonymous (unnamed) code
block. This construct is seldom used, because if a method is large enough to warrant the
use of an anonymous block, a better choice is often to break up the code into separate
methods.
8
Chapter 4
Operators
Operators are used to operate on values. They can be grouped into five types: arithmetic,
assignment, comparison, logical and bitwise operators.
Arithmetic operators
There are the four basic arithmetic operators, as well as the modulus operator (%) which is
used to obtain the division remainder.
Notice that the division sign gives an incorrect result. This is because it operates on
two integer values and will therefore round the result and return an integer. To get the
correct value, one of the numbers must be explicitly converted to a floating-point type.
Assignment operators
The second group is the assignment operators. Most importantly, the assignment
operator (=) itself, which assigns a value to a variable.
9
CHAPTER 4 ■ Operators
int x = 0;
x += 5; // x = x+5;
x -= 5; // x = x-5;
x *= 5; // x = x*5;
x /= 5; // x = x/5;
x %= 5; // x = x%5;
++x; // x += 1
−−x; // x -= 1
++x; // pre-increment
−−x; // pre-decrement
x++; // post-increment
x−−; // post-decrement
The result on the variable is the same whichever is used. The difference is that
the post-operator returns the original value before it changes the variable, while the
pre-operator changes the variable first and then returns the value.
Comparison operators
The comparison operators compare two values and return either true or false. They are
mainly used to specify conditions, which are expressions that evaluate to either true or false.
10
CHAPTER 4 ■ Operators
Logical operators
The logical operators are often used together with the comparison operators. Logical and
(&&) evaluates to true if both the left and right side are true, and logical or (||) is true if
either the left or right side is true. For inverting a Boolean result there is the logical not (!)
operator. Note that for both “logical and” and “logical or” the right-hand side will not be
evaluated if the result is already determined by the left-hand side.
Bitwise operators
The bitwise operators can manipulate individual bits inside an integer. For example,
the right shift operator (>>) moves all bits except the sign bit to the right, whereas zero-fill
right shift (>>>) moves all bits right including the sign bit.
These bitwise operators have shorthand assignment operators, just like the
arithmetic operators.
int x = 5;
x &= 5; // "and" and assign
x |= 5; // or and assign
x ^= 5; // xor and assign
x <<= 5; // left shift and assign
x >>= 5; // right shift and assign
x>>>= 5; // right shift and assign (move sign bit)
Operator precedence
In Java, expressions are normally evaluated from left to right. However, when an
expression contains multiple operators, the precedence of those operators decides the
order that they are evaluated in. The order of precedence can be seen in the following
table. This same order also applies to many other languages, such as C++ and C#.
11
CHAPTER 4 ■ Operators
For example, logical and (&&) binds weaker than relational operators, which in turn
binds weaker than arithmetic operators.
To avoid having to learn the precedents of all operators and to clarify the intent,
parentheses can be used to specify which part of the expression will be evaluated first.
Parentheses have the highest precedence of all operators.
12
CHAPTER 9 ■ Methods
void myPrint(String s)
{
System.out.print(s);
}
A method can be defined to take any number of arguments and they can have
any data types, just ensure the method is called with the same types and number of
arguments.
Return statement
A method can return a value. The void keyword is then replaced with the data type
the method will return, and the return keyword is added to the method body with an
argument of the specified return type.
String getPrint()
{
return "Hello";
}
Return is a jump statement that causes the method to exit and return the specified
value to the place where the method was called. For example, the method above can be
passed as an argument to the getPrint method since the method evaluates to a string.
The return statement may also be used in void methods to exit before the end block
is reached.
void myPrint(String s)
{
System.out.print(s);
}
26
Another random document with
no related content on Scribd:
in its attempts. The scattered blocks, with which it strives to form a
symmetrical structure, fit. This design following after finds with joy
that like design went before. Not only man puts things in a row, but
things belong in a row.
It is certain that however we may conceive of the wonderful little
bricks of which the world is builded, we must suppose a similarity
and fitting and identity in their frame. It is necessary to suppose that
every hose in nature fits every hydrant; so only is combination,
chemistry, vegetation, animation, intellection possible. Without
identity at base, chaos must be forever.
And as mind, our mind or mind like ours reappears to us in our
study of nature, nature being everywhere formed after a method
which we can well understand, and all the parts, to the most remote,
allied or explicable,—therefore our own organization is a perpetual
key, and a well-ordered mind brings to the study of every new fact or
class of facts a certain divination of that which it shall find.
This reduction to a few laws, to one law, is not a choice of the
individual, it is the tyrannical instinct of the mind. There is no solitary
flower and no solitary thought. It comes single like a foreign traveller,
—but find out its name and it is related to a powerful and numerous
family. Wonderful is their working and relation each to each. We hold
them as lanterns to light each other and our present design. Every
new thought modifies, interprets old problems. The retrospective
value of each new thought is immense, like a torch applied to a long
train of gunpowder. To be isolated is to be sick, and in so far, dead.
The life of the All must stream through us to make the man and the
moment great.
Well, having accepted this law of identity pervading the universe,
we next perceive that whilst every creature represents and obeys it,
there is diversity, there is more or less of power; that the lowest only
means incipient form, and over it is a higher class in which its
rudiments are opened, raised to higher powers; that there is
development from less to more, from lower to superior function,
steadily ascending to man.
If man has organs for breathing, for sight, for locomotion, for taking
food, for digesting, for protection by house-building, by attack and
defence, for reproduction and love and care of his young, you shall
find all the same in the muskrat. There is a perfect correspondence;
or ’tis only man modified to live in a mud-bank. A fish in like manner
is man furnished to live in the sea; a thrush, to fly in the air; and a
mollusk is a cheap edition with a suppression of the costlier
illustrations, designed for dingy circulation, for shelving in an oyster-
bank or among the sea-weed.
If we go through the British Museum or the Jardin des Plantes in
Paris, or any cabinet where is some representation of all the
kingdoms of nature, we are surprised with occult sympathies; we feel
as if looking at our own bone and flesh through coloring and
distorting glasses. Is it not a little startling to see with what genius
some people take to hunting, with what genius some people fish,—
what knowledge they still have of the creature they hunt? The
robber, as the police-reports say, must have been intimately
acquainted with the premises. How lately the hunter was the poor
creature’s organic enemy; a presumption inflamed, as the lawyers
say, by observing how many faces in the street still remind us of
visages in the forest,—the escape from the quadruped type not yet
perfectly accomplished.
This is the first property of the Intellect I am to point out; the mind
detaches. A man is intellectual in proportion as he can make an
object of every sensation, perception and intuition; so long as he has
no engagement in any thought or feeling which can hinder him from
looking at it as somewhat foreign.
A man of talent has only to name any form or fact with which we
are most familiar, and the strong light which he throws on it
enhances it to all eyes. People wonder they never saw it before. The
detachment consists in seeing it under a new order, not under a
personal but under a universal light. To us it had economic, but to the
universe it has poetic relations, and it is as good as sun and star
now. Indeed this is the measure of all intellectual power among men,
the power to complete this detachment, the power of genius to hurl a
new individual into the world.
An intellectual man has the power to go out of himself and see
himself as an object; therefore his defects and delusions interest him
as much as his successes. He not only wishes to succeed in life, but
he wishes in thought to know the history and destiny of a man; whilst
the cloud of egotists drifting about are only interested in a success to
their egotism.
The senses report the new fact or change; the mind discovers
some essential copula binding this fact or change to a class of facts
or changes, and enjoys the discovery as if coming to its own again.
A perception is always a generalization. It lifts the object, whether in
material or moral nature, into a type. The animal, the low degrees of
intellect, know only individuals. The philosopher knows only laws.
That is, he considers a purely mental fact, part of the soul itself. We
say with Kenelm Digby, “All things that she knoweth are herself, and
she is all that she knoweth.” Insight assimilates the thing seen. Is it
only another way of affirming and illustrating this to say that it sees
nothing alone, but sees each particular object in just connections,—
sees all in God? In all healthy souls is an inborn necessity of
presupposing for each particular fact a prior Being which compels it
to a harmony with all other natures. The game of Intellect is the
perception that whatever befalls or can be stated is a universal
proposition; and contrariwise, that every general statement is
poetical again by being particularized or impersonated.
A single thought has no limit to its value; a thought, properly
speaking,—that is a truth held not from any man’s saying so, or any
accidental benefit or recommendation it has in our trade or
circumstance, but because we have perceived it is a fact in the
nature of things, and in all times and places will and must be the
same thing,—is of inestimable value. Every new impression on the
mind is not to be derided, but is to be accounted for, and, until
accounted for, registered as an indisputable addition to our
catalogue of natural facts.
The first fact is the fate in every mental perception,—that my
seeing this or that, and that I see it so or so, is as much a fact in the
natural history of the world as is the freezing of water at thirty-two
degrees of Fahrenheit. My percipiency affirms the presence and
perfection of law, as much as all the martyrs. A perception, it is of a
necessity older than the sun and moon, and the Father of the Gods.
It is there with all its destinies. It is its nature to rush to expression, to
rush to embody itself. It is impatient to put on its sandals and be
gone on its errand, which is to lead to a larger perception, and so to
new action. For thought exists to be expressed. That which cannot
externize itself is not thought.
Do not trifle with your perceptions, or hold them cheap. They are
your door to the seven heavens, and if you pass it by you will miss
your way. Say, what impresses me ought to impress me. I am
bewildered by the immense variety of attractions and cannot take a
step; but this one thread, fine as gossamer, is yet real; and I hear a
whisper, which I dare trust, that it is the thread on which the earth
and the heaven of heavens are strung.
The universe is traversed by paths or bridges or stepping-stones
across the gulfs of space in every direction. To every soul that is
created is its path, invisible to all but itself. Each soul, therefore,
walking in its own path walks firmly; and to the astonishment of all
other souls, who see not its path, it goes as softly and playfully on its
way as if, instead of being a line, narrow as the edge of a sword,
over terrific pits right and left, it were a wide prairie.
Genius is a delicate sensibility to the laws of the world, adding the
power to express them again in some new form. The highest
measure of poetic power is such insight and faculty to fuse the
circumstances of to-day as shall make transparent the whole web of
circumstance and opinion in which the man finds himself, so that he
releases himself from the traditions in which he grew,—no longer
looks back to Hebrew or Greek or English use or tradition in religion,
laws, or life, but sees so truly the omnipresence of eternal cause that
he can convert the daily and hourly event of New York, of Boston,
into universal symbols. I owe to genius always the same debt, of
lifting the curtain from the common and showing me that gods are
sitting disguised in every company.
The conduct of Intellect must respect nothing so much as
preserving the sensibility. My measure for all subjects of science as
of events is their impression on the soul. That mind is best which is
most impressionable. There are times when the cawing of a crow, a
weed, a snow-flake, a boy’s willow whistle, or a farmer planting in his
field is more suggestive to the mind than the Yosemite gorge or the
Vatican would be in another hour. In like mood an old verse, or
certain words, gleam with rare significance.
But sensibility does not exhaust our idea of it. That is only half.
Genius is not a lazy angel contemplating itself and things. It is
insatiable for expression. Thought must take the stupendous step of
passing into realization. A master can formulate his thought. Our
thoughts at first possess us. Later, if we have good heads, we come
to possess them. We believe that certain persons add to the
common vision a certain degree of control over these states of mind;
that the true scholar is one who has the power to stand beside his
thoughts or to hold off his thoughts at arm’s length and give them
perspective.
I must think this keen sympathy, this thrill of awe with which we
watch the performance of genius, a sign of our own readiness to
exert the like power. I must think we are entitled to powers far
transcending any that we possess; that we have in the race the
sketch of a man which no individual comes up to.
Every sincere man is right, or, to make him right, only needs a little
larger dose of his own personality. Excellent in his own way by
means of not apprehending the gift of another. When he speaks out
of another’s mind, we detect it. He can’t make any paint stick but his
own. No man passes for that with another which he passes for with
himself. The respect and the censure of his brother are alike
injurious and irrelevant. We see ourselves; we lack organs to see
others, and only squint at them.
Don’t fear to push these individualities to their farthest divergence.
Characters and talents are complemental and suppletory. The world
stands by balanced antagonisms. The more the peculiarities are
pressed the better the result. The air would rot without lightning; and
without the violence of direction that men have, without bigots,
without men of fixed idea, no excitement, no efficiency.
The novelist should not make any character act absurdly, but only
absurdly as seen by others. For it is so in life. Nonsense will not
keep its unreason if you come into the humorist’s point of view, but
unhappily we find it is fast becoming sense, and we must flee again
into the distance if we would laugh.
What strength belongs to every plant and animal in nature. The
tree or the brook has no duplicity, no pretentiousness, no show. It is,
with all its might and main, what it is, and makes one and the same
impression and effect at all times. All the thoughts of a turtle are
turtles, and of a rabbit, rabbits. But a man is broken and dissipated
by the giddiness of his will; he does not throw himself into his
judgments; his genius leads him one way but ’tis likely his trade or
politics in quite another. He rows with one hand and with the other
backs water, and does not give to any manner of life the strength of
his constitution. Hence the perpetual loss of power and waste of
human life.
The natural remedy against this miscellany of knowledge and aim,
this desultory universality of ours, this immense ground-juniper
falling abroad and not gathered up into any columnar tree, is to
substitute realism for sentimentalism; a certain recognition of the
simple and terrible laws which, seen or unseen, pervade and govern.
You will say this is quite axiomatic and a little too true. I do not find
it an agreed point. Literary men for the most part have a settled
despair as to the realization of ideas in their own time. There is in all
students a distrust of truth, a timidity about affirming it; a wish to
patronize Providence.
We disown our debt to moral evil. To science there is no poison; to
botany no weed; to chemistry no dirt. The curses of malignity and
despair are important criticism, which must be heeded until he can
explain and rightly silence them.