Professional Documents
Culture Documents
Learning Java Beginning Programming With Java For Dummies Bach Full Chapter PDF
Learning Java Beginning Programming With Java For Dummies Bach Full Chapter PDF
Learning Java Beginning Programming With Java For Dummies Bach Full Chapter PDF
https://ebookmass.com/product/beginning-programming-with-java-
for-dummies-6th-edition-barry-burd/
https://ebookmass.com/product/java-for-dummies-8th-edition-barry-
burd/
https://ebookmass.com/product/java-programming-9th-edition-joyce-
farrell/
https://ebookmass.com/product/beginning-programming-with-python-
for-dummies-3rd-edition-john-paul-mueller/
Java Programming: A Comprehensive Introduction, First
edition
https://ebookmass.com/product/java-programming-a-comprehensive-
introduction-first-edition/
https://ebookmass.com/product/introduction-to-java-through-game-
development-learn-java-programming-skills-by-working-with-video-
games-1st-edition-victor-g-brusca/
https://ebookmass.com/product/beginning-ejb-3-java-ee-7-edition-
jonathan-wetherbee/
https://ebookmass.com/product/etextbook-pdf-for-murachs-java-
programming-5th-edition-by-joel-murach/
https://ebookmass.com/product/introduction-to-programming-with-
java-a-problem-solving-approach-3rd-edition-john-dean/
Learning Java
B P J
F D
By
John Bach
For information contact :
(alabamamond@gmail.com, memlnc)
http://www.memlnc.com
INTRODUCTION
J P E
BASIC STRUCTURES OF THE JAVA LANGUAGE
A ' J
C
D
C
B
Methods for working with large numbers
O
Converting numeric types
Cast
S
Union with t rock
Substrings
Editing a string
Checking strings for equalit y
Some methods of the String class
C
Block scope
Conditional statement if - else
Multivariate branching - switch statement
While and do - while loops
cycle for
Break statement
The continue statement
A
Copying arrays
Sorting arrays
Arrays Class Methods
Multidimensional array s
Command line parameters
C -
OBJECTS AND CLASSES
I O O P
OOP terminology
Differences between OOP and Traditional Procedural Programming
C
New operation
An example of using existing classes
C
Method overloading
The this keyword in constructors
A
S
Static fields
Static methods
I
P
Using packages
Adding a class to a package
Specifying the path to packages
Package scope
JAR files
C
INHERITANCE
E
O ( )
I
P
D
P I :T C M
A
P A ( ,)
H
I
Interface operator
Implements statement
Constants in interfaces
EXCEPTIONAL SITUATIONS
C E
D M E
How to raise an exceptional situation
Creating Exception Classes
C ( - )
Catching multiple exceptions
Re-raising an exception
Finally section
H
I / O STREAMS
Reading and writing bytes
C
S
D
D F S
T
Writing text to the output stream
Reading text from an input stream
W
LETTER T HURRAY
Introduction
The Java language was created in the early 90's as part of a
software development project for consumer electronic devices. The
original new object-oriented programming language was named Oak
(oak) . With the development of network Internet language Oak was
used to create Internet-applications ( eg, n and this language was
written Oak-browser " WebRunner " ) . In 1995, Sun Microsystems
decided to announce a new product, renaming it Java (the only
reasonable explanation for the name is the love of coffee
programmers) , and WebRunner was renamed HotJava .
The Java language is now increasingly used to create " middleware "
that maintains communication between clients and server resources
. In addition, the Java language has taken over the leadership in
embedded systems , becoming the de facto standard for portable
devices , on-board car computers, and so on .
One of the main advantages of the Java language is independence
from the platform on which programs are executed: the same code
can be run under Windows , Solaris , Linux , Macintosh , etc.
Operating systems . Another advantage is that the syntax of the
Java language is similar to the syntax language s C ++ and C . In
addition, Java is a completely object-oriented language, even more
so than C ++. All entities in the Java language are objects, with the
exception of a few primitive types , such as numbers.
In contrast to C ++ , it is easier to develop error-free programs in
Java . The Java language provides tools to eliminate the very
possibility of creating programs that would hide the most common
errors. To do this, the Java language has done the following :
The possibility of explicit allocation and freeing of memory
has been excluded. Java memory is automatically reclaimed
by garbage collection. The programmer is guaranteed
against errors related to misuse of memory ;
Introduced true arrays and disallowed pointer arithmetic.
Now programmers, in principle, cannot erase data from
memory due to improper use of pointers ;
Eliminated the possibility of confusing the assignment
operator with the equality comparison operator . Now you
can not even compile the expression of the if ( a = 3) { ... }
(this error - the source of most confusion in the languages C
and C ++).
Multiple inheritance is excluded. It has been replaced by
the concept of interface a , borrowed from Objective C. An
interface gives the programmer almost everything a
programmer can get from multiple inheritance, while
avoiding the complexity of managing class hierarchies .
java FirstSample
( no extension . class ) .
When to start from the compiled program, use the command java
ClassName , language interpreter Java always starts with the
implementation of the method main of the specified class. Therefore,
for the program to run at all, the class must contain a main method .
In accordance with the specification of the language Java method
main must be declared public ( the public ) and static ( static ) . With
lovo void means that the method does not return any value.
The brackets in the source code of a program are used to mark parts
of the program (usually called blocks). In Java, the code of any
method must begin with an opening curly brace and end with a
closing curly brace ({…}) .
By azhdy operator must end with a semicolon. In particular, the end-
of-line character does not mean that the statement is terminated , so
the statement can span as many lines as needed.
In this example, for a text string output using tsya object System . out
and cause t Xia its method println , in which the text string is passed
as a parameter. Note that period is used to call the method.
In the language of the Java , as well as in the language of s C / C ++
for the designation used strings double quotes.
Java methods can have one or more parameters , or none at all .
Even if the method has no parameters, you must leave empty
parentheses. For example, there is a parameterless version of the
println method that prints an empty string to the screen. Its call looks
like this: System.out.println () .
Comments
Comments in Java , as in most programming languages, are ignored
when compiling a program. Thus, you can add as many comments
to the program as required without fear of increasing its size.
The Java language has three ways to highlight comments in text.
The most common use of two forward slashes is //, whereby the
comment begins immediately after the // characters and continues to
the end of the line. In addition, the delimiters / * and * / can be used .
T retya variety comments mozh is ispolzovat sya for automatic
generation of documentation. These comments begin with / ** and
end with * /. The javadoc utility is used to automatically generate
documentation . exe .
Data types and variables
The Java language is strongly typed. This means that the type of
each variable must be declared.
In the language of Java , there are eight basic types ( primitive types
) data. Four of them are integers, two - to the actual floating- point,
one is a character type char , used to represent characters in the
format of the Unicode , and the latter - a boolean type boolean - is
used for logical values.
There is no concept of unsigned numbers in Java .
java.mathBigDecimal 1.1
BigDecimal add (BigDecimal other)
BigDecimal subtract (BigDecimal other)
BigDecimal multiply (BigDecimal other)
BigDecimal divide (BigDecimal other, int roundingMod e)
Returns the sum, difference, product, and quotient of a large decimal number
by the value of other . To calculate the quotient, you need to support the
rounding mode. BigDecimal ROUND_HALF_UP means normal rounding (that
is , downward if the last digit is less than 5, and upward if it is greater than 5).
This is sufficient for ordinary calculations. Other rounding modes are described
in the API documentation.
Operations
Any language expression consists of operands (variables, constants,
etc.), connected by operation signs. An operation sign is a symbol or
group of symbols that tells the compiler to perform certain arithmetic,
logical, or other operations.
Operations are performed in a strict sequence. The value that
determines the preemptive right to perform a particular operation is
called priority. Table Figure 2 lists the various Java language
operations . Their priorities are the same for each group (the group is
located between two adjacent horizontal lines). The more advantage
the corresponding group of operations is, the higher it is located in
the table. The order of operations can be adjusted using
parentheses.
Table 2 . Java
Operations
Operation sign Purpose of operation
! Logical negation
~ Bitwise negation
,+ Sign change
++ Increase by one
Decrease by one
( type) Ex ivedenie type (e.g., ( float ) a )
* Multiplication
/ Division
% Determination of the remainder of
division
+ Addition
Subtraction
<< Shift left
>> Shift Right ( Arithmetic )
>>> Shift right ( boolean)
< Less than
<= Less or equal
> More than
>= More or equal
instanceof Checking object ( is there an object
an instance of this class )
== Equally
!= Not equal
& Bitwise and logical " AND "
^ Bitwise and logical exclusive " OR "
| Bitwise and logical " OR "
&& Logical " AND "
|| Logical " OR "
?: Conditional (ternary) operation
= Assignment
+ =, =, * =, / =, Binary operations (e.g. a * = b
% = , << =, >> =, (m. e. a = a * b) , etc.)
& = , | =, ^ =
Editing a string
To determine the length of a string, use the length method , for
example:
String greeting = "Hello";
int n = greeting.length (); // String length is 5
A single character can be selected from a string . Calling greeting
.charAt (n) returns the Unicode character at position n , where n is in
the range 0 to greeting .length () - 1 , for example:
cha r last = greeting.charAt (4); // The fourth character , ie . e
.-'o'
By Lass String do not have methods to change the character at a
given with Troc , about dnako variable of type String , you can assign
a new value (ie. E assign. Reference to the string " the Hello " link on
the next line ) :
String greeting = "Hello";
greeting = " Hello " + ", World ! ";
In this case , new cells are allocated in memory to store the string "
Hello , World !" and the variable greeting gets the address of this
timeline . The memory unit, which stores the value of " the Hello " ,
sooner or later, will be released by a mechanism and automatic
garbage collection.
If you want to change the string , you can use the class om the
StringBuffer .
Checking strings for equalit y
To check if two strings are the same, the equals method should be
used . The Calling up method
s . equals ( t ) ;
returns true if strings s and t are equal, otherwise it returns false .
Note that strings s and t can be both variables and constants. For
example, the expression
" Hello !" equals ( c ommand String );
quite acceptable . To check the identity of strings, ignoring the
distinction between uppercase and lowercase letters, use the equals
I gnoreCase method .
" Hello ". equalsIgnoreCase (" hello "); // Returns true
You cannot use the " ! = " Operation to test strings for equality . He
and checks only if both lines are stored in the same memory area.
Obviously , if both strings are stored in the same place, they must
match. However, it is quite possible that identical strings are stored
in different places.
int length ()
Returns the length of the string.
String toLowerCase ()
Returns a new string consisting of all the characters of the original string, with
all lowercase letters are converted from are in lowercase.
String toUpperCase ()
Returns a new string consisting of all the characters of the original string, with
all lowercase letters Conversion from are in uppercase.
String trim ()
Returns a new string excluding all leading and trailing spaces.
Break statement
There is no goto statement in Java . In order to, in some cases
replacements and be the goto , in Java provides the operator break
statement . This statement tells the runtime to stop executing the
block and transfer control to the statement following the block . The
Java language uses labels to name blocks . Operator break when
working with loops and operators switch can be used , and no label.
In this case, exit from the current block is implied.
For example,
for ( int i = 0; i <10; i ++)
{
System.out.println (i);
if (i> 5)
break;
System.out.println ( i * i ); // He will be satisfied , if i> 5
}
On the Emperor of the break with a tag can be used, for example, as
follows:
la bel :
{
if ( a> b ) break label; // Exit the block
} // When the break statement is executed, control is
transferred
// at this point in
The label must precede the outermost loop you want to exit. The
label is followed by a colon.
The label can be assigned to any operator. About Emperor of the
break can be used only for the transfer of one of the current sub-
blocks. This distinguishes break from the C and goto operator , for
which jumps to arbitrary labels are possible.
The continue statement
The continue statement , like the break statement , interrupts normal
program execution. The continue statement transfers control to the
beginning of the most deeply nested loop.
If the continue statement is used in a for loop , it transfers control to
the loop incrementing statement. Below is an example where the
continue statement is used to have two numbers printed on each
line.
for (int i = 0; i < 6 ; i ++)
{
System.out.print (i + "");
if (i% 2 = = 0) continue;
System.out .println ();
}
If the index is even, the loop continues without outputting a newline.
The result of this first cycle is as follows:
01
23
45
In the language of Java there is also the operator continue Tagged
with transmitting control cycle operator header marked th
corresponding label.
Arrays
An array is a data structure that stores values of the same type. A
single element of an array is accessed using an integer index.
An array is declared as follows: first specified type of the array, ie. E .
the type of the elements contained in the array, followed by a pair of
empty square brackets, followed by the variable name. For example,
an array of integers is declared like this :
int [] a; // Or you can do this : int a [] ;
However, this operator only declares the variable a , not initializing it
with a real array. To create an array, you need to reserve memory for
the array with the opera tion new (see the next section.) :
int [] a = new int [100];
In this example creates Xia array consisting of 100 integers. The
elements of this array are numbered from 0 to 99 . After creating an
array mo zhno filled and may, for example, using a loop :
int [] a = new int [100];
for ( int i = 0; i <100; i ++)
a [i] = i; // fill of the array and the numbers from 0 to 99
To calculate the number of elements in the array can ispol'uet Call
method arrayName. length . For example :
for (int i = 0; i <a.length; i ++ )
System.out.print l n (a [i]);
Once the array is created, it cannot be resized. If during the
execution of the program need to frequently change the size of the
array, it is better to use a different data structure called a list of
arrays (array list).
When you create and the array can be initialisation Rowan initial
values :
int [] small Array = { 1, 2, 3, 4 , 5 , 6 , 7 } ;
Note that in this case you do not need to use the new operation .
Copying arrays
If the arrays are the same, then one can be copied to another as
follows :
int [] small Array = {1, 2, 3, 4, 5, 6 , 7} ;
int [] b = sma l l Array ;
b [5] = 1 2 ; // Now element sma l l Array [5] is also 12
If you need to copy the elements of one array to another, use the
arraycopy method from the System . Its call looks like this:
System . and rr ausoru ( from , from I ndex , to , to I ndex ,
count );
The to array must be large enough to accommodate all of the copied
elements.
For example, shown below are two operators create an array and
then copy the last five element s of the first array to the second.
Copying starts at i = 2 ( that is , at the third position ) in the source
array, and the elements to be copied are placed into the target array
starting at i = 3 (that is , at the fourth element ) .
int [] sma l l Array = {1, 2, 3, 4, 5, 6 , 7} ;
int [] bigArray = {101, 102, 103, 104, 105, 106, 107 , 108, 109
};
System. a rra y c opu (sma l l Array , 2, bigArray , 3, 5 );
for (int i = 0; i < bigArray .length; i ++)
System.print (i + " , " + bigArray [i ]);
Result :
101, 102, 103, 4, 5, 6, 7, 108, 109
Sorting an array of s
To organize an array of numbers in on a row of increase , it is
possible to apply the method sort of class the Arrays .
int [] a = new int [10000];
Array s.sort (a);
The Arrays class has several convenient methods for working with
arrays. These methods are listed below .
Arrays Class Methods
java . lang . System 1.1
static void arraycopy (Object from, int from I ndex, Object to, int to I ndex, int
count)
The method copies elements from the first array to the second.
Parameters: from Array of any type.
from I ndex Index from which copying starts
elements.
to An array of the same type as an array .
fromto I of NDEX Index, with Kotor th starts up
elements.
count The number of items to copy.
float or double .
v A value of the same type as the elements of array
a.
float or double .
other An array of the same type as Xxx [] .
Multidimensional array s
In fact, there are no real multidimensional arrays in Java . However,
there are arrays of arrays that behave like multidimensional arrays
with a few minor differences.
You can declare a multidimensional array like this:
d ouble [] [] matr ix ;
A multidimensional array cannot be used until it is initialized using
the new operation . For example,
matr ix = new double [ n ] [ m ];
(each element of the array is initialized to zero). E If cells are known
in advance, initialization multidimensional array can use the
shorthand notation, which is not used in opera tion new . For
example, like this :
int [] [] magicSquare =
{
{16, 3, 2, 13},
{ 5, 10, 11, 8},
{9, 6, 7, 12},
{4, 15, 14, 1}
};
After initialization, the individual elements ma file of parameters can
be accessed by two pairs of brackets, e.g. matr ix [ i ] [ j ] .
You can determine the dimension of a multidimensional array , for
example, in the following way :
int n = matrix .length; // number of lines
int m = matrix [ 0] .length; // number of elements per line
import java.util. *;
public class StrInOut
{
public static void main (String [] args)
{
Scanne r reader = new Scanner (System.in);
// Scanner - from java.util package
String text = "";
// Or like this :
System.out.p rintf (" You entered :% s \ n", text);
System.out.printf ("\ n"); // translated strings
}
}
To read an integer, you can use the following code :
Scanner reader = new Scanner (System.in);
// Scanner - from package j ava.util
int number = 0 ;
You can read an array of bytes and convert to a string like this :
import java . io . *;
public class StrInOut
{
public static void main (String [] args) throws IOException
{
byte [] buffer = new byte [80];
str = str . trim (); // Cut off the unfilled part of the line
// Or like this :
System . out . printf (" You entered :% s \ n \ n ", str );
}
}
And so :
import java . io . *;
public class StrInOut
{
public static void main (String [] args) throws IOException
{
BufferedReader d =
new BufferedReader (new InputStreamReader (System.in));
String str = d.readLine (); // readLine () from BufferedReader
System.out.println (" You entered :" + str);
}
}
You can read a symbol and print its code like this :
import java.io. *;
pub lic class C har Read
{
public static void main (String [] args) throws IOException
{
BufferedReader d =
new BufferedReader (new InputStreamReader
(System.in));
int ch = d.read (); // read () from BufferedReader
“In Vana-heim
Wise powers him created,
And to the gods a hostage gave.”
Lay of Vafthrudnir (Thorpe’s tr.).
As ruler of the winds, and of the sea near the shore, Niörd was
given the palace of Nôatûn, near the seashore, where we are told he
stilled the terrible tempests stirred up by Ægir, god of the deep sea.
For some time, Niörd and Skadi, who are the personifications of
summer and winter, alternated thus, the wife spending
Parting of
Niörd and the three short summer months by the sea, and he
Skadi. reluctantly remaining with her in Thrym-heim during
the nine long winter months. But, finding at last that their tastes
would never agree, they decided to part forever, and returned to their
respective homes, where each could follow the occupations which
custom had endeared.
Frey, or Fro, as he was called in Germany, was the son of Niörd and
Nerthus, or of Niörd and Skadi, and was born in Vana-heim. He
therefore belonged to the race of the Vanas, the divinities of water and
air, but was warmly welcomed in Asgard when he came thither as
hostage with his father. As it was customary among the Northern nations
to bestow some valuable gift upon a child when he cut his first tooth, the
Æsir gave the infant Frey the beautiful realm of Alf-heim or Fairyland,
the home of all the Light Elves.
Here Frey, the god of the golden sunshine and the warm summer
showers, took up his abode, charmed with the company
The god of
fairyland. of the elves and fairies, who implicitly obeyed his every
order, and at a sign from him flitted to and fro, doing all
the good in their power, for they were preëminently beneficent spirits.
FREY.
Frey received from the gods a marvelous sword (an emblem of the
sunbeams), which had the power of fighting successfully, and of its own
accord, as soon as it was drawn from its sheath. Because he carried this
glittering weapon, Frey has sometimes been confounded with the sword-
god Tyr or Saxnot, although he wielded it principally against the frost
giants, whom he hated almost as much as did Thor.
It is related in one of the lays of the Edda that Frey once ventured to
ascend Odin’s throne Hlidskialf, and from this exalted seat cast a glance
over all the wide earth. Gazing towards the frozen North, he saw a
beautiful young maiden enter the house of the frost giant Gymir, and as
she raised her hand to lift the latch her radiant beauty illuminated sea
and sky.
A moment later, this lovely creature, whose name was Gerda, and
The wooing of who is considered as a personification of the flashing
Gerda. Northern lights, vanished within her father’s house, and
Frey pensively wended his way back to Alf-heim, his heart
oppressed with longing to make this fair maiden his wife. Being deeply in
love, he was melancholy and absent-minded in the extreme, and began
to behave so strangely that his father, Niörd, became greatly alarmed
about his health, and bade his favorite servant, Skirnir, discover the
cause of this sudden change. After much persuasion, Skirnir finally won
from Frey an account of his ascent of Hlidskialf, and of the fair vision he
had seen. He confessed his love and especially his utter despair, for as
Gerda was the daughter of Gymir and Angur-boda, and a relative of the
murdered giant Thiassi, he feared she would never view his suit with
favor.
One month of every year, the Yule month, or Thor’s month, was
considered sacred to Frey as well as to Thor, and began
The Yule
feast. on the longest night of the year, which bore the name of
Mother Night. This month was a time of feasting and
rejoicing, for it heralded the return of the sun. The festival was called
Yule (wheel) because the sun was supposed to resemble a wheel
rapidly revolving across the sky. This resemblance gave rise to a
singular custom in England, Germany, and along the banks of the
Moselle. Until within late years, the people were wont to assemble yearly
upon a mountain, to set fire to a huge wooden wheel, twined with straw,
which, all ablaze, was then sent rolling down the hill and plunged with a
hiss into the water.
“Some others get a rotten Wheele, all worn and cast aside,
Which, covered round about with strawe and tow, they closely hide;
And caryed to some mountaines top, being all with fire light,
They hurle it down with violence, when darke appears the night;
Resembling much the sunne, that from the Heavens down should fal,
A strange and monstrous sight it seemes, and fearful to them all;
But they suppose their mischiefs are all likewise throwne to hell,
And that, from harmes and dangers now, in safetie here they dwell.”
Naogeorgu
All the Northern races considered the Yule feast the greatest of the
year, and were wont to celebrate it with dance, feasting, and drinking,
each god being pledged by name. The missionaries, perceiving the
extreme popularity of this feast, thought best to encourage drinking to
the health of the Lord and his twelve apostles when they first began to
convert the Northern heathens. In honor of Frey, boar’s flesh was eaten
on this occasion. Crowned with laurel and rosemary, the animal’s head
was brought into the banquet hall with much ceremony—a custom long
after observed at Oxford, where the following lines were sung:
But when Menia and Fenia would fain have rested awhile, the king,
whose greed had been excited, bade them work on. In spite of their cries
and entreaties he forced them to labor hour after hour, allowing them
only as much time to rest as was required for the singing of a verse in a
song, until, exasperated by his cruelty, the giantesses resolved to have
their revenge. Once while Frodi slept they changed their song, and
grimly began to grind an armed host, instead of prosperity and peace.
By their spells they induced the Viking Mysinger to land with his troops,
surprise the Danes, who were wrapped in slumber, and slay them all.
This Viking then placed the magic millstones Grotti and the two
slaves on board his vessel, and bade the women grind for him, saying
that he wanted salt, as it was a very valuable staple of commerce at that
time. The women obeyed; the millstones went round, grinding salt in
abundance; but the Viking, as cruel as Frodi, kept the women
persistently at work, until they ground such an immense quantity of salt
that its weight sunk the ship and all on board.
The ponderous millstones sank straight down into the sea in the
Pentland Firth, or off the northwestern coast of Norway, making a deep
round hole. The waters, rushing into the vortex and gurgling in the holes
in the center of the stones, produced the great whirlpool, which is known
as the Maelstrom. As for the salt, it soon melted; but such was the
quantity ground by the giantesses that it tainted all the waters of the sea,
which have ever since been very salt indeed.