Learning Java Beginning Programming With Java For Dummies Bach Full Chapter PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 69

Learning Java: Beginning programming

with java for dummies Bach


Visit to download the full and correct content document:
https://ebookmass.com/product/learning-java-beginning-programming-with-java-for-d
ummies-bach/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Beginning Programming with Java For Dummies 6th Edition


Barry Burd

https://ebookmass.com/product/beginning-programming-with-java-
for-dummies-6th-edition-barry-burd/

Java For Dummies 8th Edition Barry Burd

https://ebookmass.com/product/java-for-dummies-8th-edition-barry-
burd/

Java Programming 9th Edition Joyce Farrell

https://ebookmass.com/product/java-programming-9th-edition-joyce-
farrell/

Beginning Programming with Python For Dummies 3rd


Edition John Paul Mueller

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/

Introduction to Java Through Game Development: Learn


Java Programming Skills by Working with Video Games 1st
Edition Victor G. Brusca

https://ebookmass.com/product/introduction-to-java-through-game-
development-learn-java-programming-skills-by-working-with-video-
games-1st-edition-victor-g-brusca/

Beginning EJB 3: Java EE 7 Edition Jonathan Wetherbee

https://ebookmass.com/product/beginning-ejb-3-java-ee-7-edition-
jonathan-wetherbee/

(eTextbook PDF) for Murach’s Java Programming 5th


Edition by Joel Murach

https://ebookmass.com/product/etextbook-pdf-for-murachs-java-
programming-5th-edition-by-joel-murach/

Introduction to Programming with Java: A Problem


Solving Approach 3rd Edition John Dean

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

First Edition: july 2020

UNITY GAME PROGRAMMING


Copyright © 2020 by ALEXANDER ARONOWITZ
"Programming isn't about what you
know; it's about what you can figure out.”
Chris Pine -
2020
CONTENT

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 Program Execution


A program written in a high-level language (called a source module )
cannot be executed immediately . From the beginning it must be
compiled, that is , translated into a sequence of machine instructions
- an object module. For boot th unit I of bektny module n uzhno build
the libraries used in the module and enable the cross-references
between the object module sections
The source module written in the language of the Java , could not
avoid these procedures, but here is shown the main feature of the
technology the Java - the program is compiled directly into machine
instructions, but does not command a particular processor, and in
the team's so-called in irtualn second machine s the Java ( JVM,
Java Virtual Machi ne ). The Java Virtual Machine is a collection of
commands along with their execution system. Note that the virtual
machine Java completely stack, and therefore does not require
complex th addressing of and memory cells and a large of quantity
and registers. By A team JVM short, most of which it has a length of
1 byte, so the JVM command called a byte - code ( bytecodes ),
although there are teams of length 2 and 3 bytes. Full description of
the commands and the entire JVM architecture is contained in a
virtual machine specification the Java (the VMS, the Virtual Machine
specifica tion of ).
Another feature of Java is that all standard functions that are called
in a program are connected to it only at run time, and are not
included in the bytecode. In other words, there is dynamic linking (
dynamic binding ) , which significantly reduces the amount of the
compiled program.
Since a program written in Java is translated by the compiler into the
bytecode of the Java Virtual Machine , it is independent of the type
of processor and architecture of the computer being used .
Therefore, bytecode can be performed and be on any computer with
a system that implements the JVM. In this case, neither the type of
processor nor the architecture of the computer is important. T. e
language. The Java - machine-independent. (Obviously, the
implementation of the Java virtual machine is platform dependent.)
Bytecode interpretation and dynamic linking slow down program
execution significantly. It does not matter when the bytecode before
ae tsya on the network - network slower than any interpretation ;
however , other situations require a powerful and fast computer. To
increase the speed of interpretation p azrabotany JIT-compiler ( "
timely " compilers - the Just - with In - Time The compiler ),
memories have interpreted sections of code to machine CPU and
simply performing these areas when re-treatment, for example, in
cycles. Only a specialized processor can provide the highest speed
of bytecode execution . The company of SUN Microsystems
released the microprocessors picoJava , running on the system JVM
command, e nce and Java-processors of other companies. These
processors directly execute bytecode.
And nterpreta tori JVM commands in a specific processor
instructions designed for virtually all computing platforms. More and
more operating systems and database management systems include
JVM implementation in their core. A special JavaOS operating
system has also been created , which is used in electronic devices.
Most browsers have a built-in Java virtual machine to run applets.
The company of SUN Microsystems - the creator of technology Java
- distributes a set of software tools required for a full cycle of
software development on the language ie Java under the name of
the JDK ( Java Development Kit ). There are toolkits from other
companies .
The JDK suite of programs and classes contains:
javac - source to bytecode compiler;
java - the interpreter containing the JVM implementation;
appietviewer - browser-replacement applet viewer
jdt - debugger;
javap - disassembler;
jar - pro gram archiving and compression (using the
format zip -files);
the javadoc - prog Ranma to generate documentation
from comments ;
javah - generating program language header file C ;
javakey - a program for adding an electronic signature;
native2ascii - a program that converts binary files to text;
rmic and rmiregistry programs for working with remote
objects;
serialver - the program that determines the version
number of the class;
libraries and header files of " built-in " methods;
Library classes Java API (Application Programming
Interface) and others .
The first version of the JDK 1.0 was released in 1996 g ode . Starting
with the version the JDK 1.2, which came out in December 1998 g .,
Food technology Java Company and SUN became and nazyvat sya
Java 2 Platform of Standard Edition , abbreviated J 2 SE , a the JDK
was pereimenova n in Java 2 of Standard Edition the SDK (
Software Development Kit ) , abbreviated as J 2 SDK . Also issue
were Java 2 Enterprise Edition the SDK and Java 2 Micro Edition the
SDK . ( However, the very company SUN until now has enjoyed ,
and the old name - the JDK .) With the version the JDK 1.6
packages means development began and nazyvat sya the Java
Platform of Standard Edition Development Kit ( the Java SE ) , the
Java Platform Enterprise Edition the SDK ( the Java EE ) and the
Java Platform Micro Edition SDK ( Java ME ). In addition , SUN
separately distributes a set of JRE ( Java Runtime Environment ) for
working with compiled Java programs .

Basic structures of the Java language


A simple Java program
Consider a simple program that prints a message to the console
window :

public class FirstSample


{
public static void main (String [] args)
{
System.out.println ("Hello, World!");
}
}
The first and main point is that in the Java language , uppercase and
lowercase letters are strictly distinguished. If , for example, Dialed
amb word Main instead of main , the program will not be executed.
The keyword public is called the access modifier ( access modifier );
such modifiers control access to this code from other parts of the
program. The keyword class reminds us that all of the entities in the
language Java is inside a class , t. E. In Neki x container x , in which
the logic of the program concluded, defining the application. Classes
are the building blocks that make up all applications and applets
written in the Java language . All entities in Java programs must be
inside classes.
The class keyword is followed by the class name. The rules for
generating class names are not too strict. The name must start with
a letter, and the rest of it can be any combination of letters and
numbers. The length of the name is practically unlimited. Java
reserved words (for example, public or if ) cannot be used as a class
name .
Classes are usually called nouns starting with an uppercase letter.
The file containing the source code must be named the same as the
public class and have the extension . j ava .
Compiling the program :

java c FirstSample . java

The Java compiler will automatically name this file FirstSample .


class and will save it in the directory containing the source file.
To redirect error messages to a file ( when working on UNIX or
Windows NT / 2000 / XP platforms ) , just use the 2> operator:

javac FirstSample . java 2> errors . txt


For in the Run eniya byte code and using an interpreter Java n
uzhno dial command

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 .

Table 1 . Data types


A type Size in bytes Change interval
int 4 o t - 2147 483648 up to 2147483647
short 2 from -32768 up to 32767
up to
ot-
l ong 8
9223372036854775808L
922337203685477580
7L
byte 1 o t - 12 8 up to 1 27
from - 3.4 02823 47 Е up to 3.4 02823 47 E +
float 4
38 F 38 F

double 8 from - 1.7976931348623 1 D o 1.79769313486231


57 E + 308 57 E + 308
up to 65535 ( ' \ uFFFF
char 2 from 0 ( ' \ u0000 ' )
')

Long integers have an L suffix ( for example, 4000000000L).


Hexadecimal numbers are prefixed with 0 x ( for example, 0 xCAFE
or 0 xcafe ). Octal numbers are prefixed with 0. For example, 010 is
8 10 .
Float numbers have an F suffix, for example 3.402F. Floating point
numbers having no suffix F ( e.g., 3.402), are always treated as the
number of type double ( with double precision ) . You can (but not
necessarily) use the D suffix to represent them, for example 3.402D.
All calculations performed on floating point numbers follow the IEEE
754 standard. In particular, the Java language has three special
floating point numbers:
positive infinity (constant Double . POSITIVE _ INFINITY )
;
negative infinity (constant Double . NEGATIVE _
INFINITY ) ;
NaN (not a number) ( constant Double. NaN ) .
They are used to indicate overflow and error. For example, dividing a
positive number by 0 equals positive infinity. Evaluating 0/0 or taking
the square root of a negative number is NaN.
For constants of type char , single quotes are used. For example, ' H
' is a character. It differs from "H" , which is a single character string.
In Java to represent the characters are encoded the Unicode , so the
value of the type as char coded 2-byte of vym code. Unicode is the
union of dozens of character encodings ; it includes Latin, Greek,
Arabic alphabets, Cyrillic and many other character sets.
Unicode character codes are usually expressed as hexadecimal
values from '\ u0000' to ' \ uFFFF' . The \ u prefix means that the
character is in Unicode format , followed by four hexadecimal digits
that identify the character. For example, ' \ u2122 ' is a trademark
(™) symbol .
With quantities of type char mozh but handled as integers . This
makes it possible to add two characters together, or to increment the
value of a character variable :
The Java language has a simple boolean type used to store boolean
values. Variables of this type can take only two values - true (true)
and false (false). Values of type boolean return as a result of all
comparison operators .
Note that the variable name must also begin with a letter and be a
combination of letters and numbers. The terms "letters" and
"numbers" in Java have a broader meaning than in most other
programming languages. Letters are considered Sim oxen ' A' - ' the
Z', 'a' - ' the z ', '_' and any symbol encoding the Unicode . Similarly,
both ordinary decimal digits '0' - ' 9 ' and any Unicode characters
used to denote a digit in any language are considered digits. The
use of other characters in identifiers is prohibited. All characters in
the variable name are important, and the case of the keyboard also
matters. Variable name length is not limited. You cannot use
reserved words as variable names.
In the language of Java size ad is, and determining the e variables
do not differ.
After declaring a variable, you must explicitly initialize it using the
assignment operator. For example :
int vacationDays ; // This is a declaration
vacationDays = 12; // This is an assignment operator
int index = 0 xffffffff ; // -1
long number = 25 L ;
float result = 2.5 F ;
double pi = 3.14159;
char c1 = 0x f132;
char c2 = 'a';
char c3 = '\ n';
char c4 = ' \ u2122 ' ;
boolean done = false ;
The basic form of a variable declaration is as follows:
type identifier [= value] [, identifier [= value 2 ...];
Type - is either one of the built-in types so . e . byte , short , int , long
, char , float , double , boolean , or the name of a class or interface.
Constants
The Java language uses the final keyword to denote constants , for
example:
public class Constants
{
public static void main (String [] args)
{
final double CM_PER_INCH = 2.54 ;
double paperWidth = 8.5;
double PaperHeight = 11;

System . out . the println ( " The size of the page in


inches "
+ paperWidth * CM_PER_INCH + " on "
+ paper H eight * CM _ PER _ INCH );
}
}
The final keyword means that you can assign a value to a given
variable only once. It is not necessary to use only uppercase letters
in constant names .
In the Java language , you often need constants that are available to
multiple methods within the same class. They are usually called
class constants . Class constants are declared using the static final
keywords . Here's an example using a class constant :
public class Constants 2
{
public static final double CM_PER_INCH = 2.54;

public static void main (String [] args)


{
...
}
}
Note the fact that the class constant is defined outside the main
method . Thus, it can be used in other methods of the same class.
Moreover, if (as in this example) a constant is declared public ,
methods from other classes can also access it. In our example, this
can be done using the expression Constants 2. CM _ PER _ INCH .
Big numbers
If the precision of the built-in integer and floating point types is not
sufficient , you can refer to the two classes in the Java package .
math called Big I nteger and BigDecimal . These classes are
designed to manipulate numbers consisting of an arbitrary number of
digits. The Big I nteger and BigDecimal classes implement arbitrary
precision arithmetic on integers and real numbers, respectively.
To convert an ordinary number to “ large ”, use the method
valueOf . Big I nteger a = Big I nteger.value O f (100);
The usual mathematical operators “ + ” and “ * ” cannot be applied to
large numbers . Instead, you need to use the add and multiply
methods from the classes to work with large numbers :
Big I nteger with = a . add ( b ); // c = a + b
BigI nteger d = c .multiply (b.add (BigInteger.valueOf (2)));
// d = c * ( b + 2)
Methods for working with large numbers
java.math.Big I nteger 1.1
Big I nteger add (Big I nteger other)
Big I nteger subtract (Big I nteger othe r)
Big I nteger multiply (Big I nteger other)
Big I nteger divide (Big I nteger other)
Big I nteger mod (Big I nteger other)
These functions return the sum, difference, product, quotient, and remainder of
a given large number by the value of other .

int compa reTo (Big I nteg e r other)


Returns 0 if the given large number is equal to the value of other, a negative
number if the given large number is less than the value of other, and positive
otherwise.

static Big I nteger valueOf (long x)


Returns a large number equal to the value of x.

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.

int compareTo (BigDecimal other)


Returns 0 if this number is equal to the value type variable BigDecimal other , a
negative number if this number is less than the value of the variable other , and
a positive number otherwise.

static BigDecimal valueOf (long x)


static BigDecimal valueOf (long x, int scale)
sc ale
Returns a large decimal number equal to the value of x or x / 10 .

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.)
& = , | =, ^ =

To avoid confusion in the concepts of "operation" and "operator",


note that the operator is the smallest executable unit of the
program. There are expression operators, the action of which is to
evaluate the given expressions (for example: a = b + c ; j ++;),
declaration operators, compound operators, empty operators, label
operators, loop operators, etc. The Java language uses a semicolon
to indicate the end of a statement .

Conversion e numeric types


Solid ones with arrows and in Fig. 1 denote transformations that are
performed without loss of information. The three dashed arrows
indicate transformations that may result in loss of precision. For
example, the number of digits in the large integer 123456 789
exceeds the number of digits that can be represented by the float
type . The number converted to float has the same meaning , but
with slightly lower precision.
int n = 123456789;
float f = n ; // Number n is equal to 1.234567892Е8

Figure: 1. Allowed conversions

If the two values are combined by a binary operator ( e.g., n + f ,


where n - an integer, a f - a floating point number), before performing
the operation, both operands are converted y are in numbers having
the same type .
If at least one of the operands is of type double ,
the second too Conversion from etsya in the number of
type double .
Otherwise, if either operand is float , the second
too Conversion from etsya in the number of type float .
Otherwise, if one operand is long , then the
second, too Conversion from etsya in the number of type
long .
Otherwise, both operands are converted to int
numbers .
Reduction type s
The language Java automatic conversion ( in the case of the
numeric types ) is possible only in the case where the accuracy of
number representation receiver variable enough for storing the initial
value. Such a conversion occurs, for example, when a character
constant or the value of a variable of type byte or short is entered
into a variable of type int . The size of the int type is sufficient to
store numbers in the range allowed for the byte type , so in such
situations, an explicit cast is not required. The converse in most
cases is not true, however for entering a value of type int variable
type byte must use opera tion actuation type ( type casting ) , to the
variable int fits into a variable desired type.
To cast a value to a specific type, you need to specify this type,
enclosed in parentheses, before it. The code snippet below
demonstrates casting from a source (variable of type int ) to the type
of destination (variable of type byte ). If, during such an operation,
the integer value went out of the range allowed for the byte type , it
would be reduced by dividing by modulo by the range allowed for
byte (the result of modulo by number is the remainder of division by
this number).
int a = 100;
byte b = (byte) a;
Automatic conversion type and in expressions can sometimes be the
cause of error messages the compiler. For example, the code below,
although it looks quite correct, results in an error message during the
translation phase. It stores the value 50 * 2 , which must fit into the
byte type (that is , into a byte variable ) . But due to the automatic
conversion of the result type to the int type (since the number 2 is of
the int type by default ), a translator error message is generated -
after all, when an integer is entered into a byte variable , a loss of
precision may occur.
byte b = 50;
b = b * 2;
Corrected text:
byte b = 50;
b = ( b yte ) ( b * 2);
which causes b to enter the correct value of 100.
Strings
Line - is a sequence of characters, such as " the Hello " , submitted
encoded the Unicode . In the language of Java is no built-in type for
strings. Instead, the Java standard library contains a built-in String
class . Each quoted string represents an instance of the String class
.
String e = ""; // Empty string
String greeting = "Hello";
Strings are allocated in dynamic memory, the string identifier is, in
fact, a reference to the string.
Concatenating strings
The Java language , like most programming languages, allows you
to use the “ + ” operation to concatenate (concatenate) two strings.
String a = " Hello ,";
String b = " World ! ";
String message = a + b ;
The code above assigns the string " Hello , World ! " To the message
variable . When the string concatenation with a value that is not a
string, the value is converted from etsya string. For example the
code
int age = 1 8 ;
String rating = " PG " + age ;
assigns the string " PG 1 8 " to the rating variable .
This property is widely used in inference statements :
System.out.println ("The answer is " + answer);
Substrings
You can use the substring method of the String class to extract a
substring from a given string. For example the code
String a = " Hello ";
String s = a . substring (0, 4);
forms a string consisting of the characters " Hell " . In the Java
language , characters in a string are numbered from zero (as in the
C and C ++ languages ). For example, the character 'H' in the string
" Hello " is at position zero, and the character 'o' is at position four.
The second parameter of the substring method specifies the position
to which the copy is performed (that is , the elements at index 0, 1, 2,
and 3 are copied) .

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.

Some methods of the String class


Class String in the language Java contains more than 50 methods.
Below are the most useful ones. Full list of methods can be found in
the documentation for the Java the API .
Java.lang.String 1.0
char char At (int index)
Returns the character at the specified position .

int compareTo ( String other )


It returns a negative value if the row line precedes other in lexicographic order,
a positive value - if a string other preceded this string in lexicographic order,
and 0 - f If the strings are identical .

boolean endsWith ( String suffix )


Returns true if the string ends with suffix substring .

boolean equals ( Object other )


Returns true if the string is equal to the string other .

boolean equalsIgnoreCase ( String other )


Returns true if the string is equal to the string other, disregarding the difference
between uppercase and lowercase letters.

int index (String str)


int indexOf (String str, int from I ndex)
Returns the start of the first substring that matches string str, starting at position
0 or form I ndex.

int last I ndexOf (String str)


int last I ndexOf (String str, int from I ndex)
Returns the beginning of the last substring equal to string str , starting at
position 0 or form I ndex .

int length ()
Returns the length of the string.

String replace (char oldChar, char newChar)


Returns a new string obtained by replacing all oldChar characters in the string
with newChar.

boolean startWith ( String prefix )


Returns true if the string begins with the substring prefix .

String substring (int begin I ndex)


String substring (int begin I ndex, int end I ndex)
Returns a new string consisting of all characters from position Begin I ndex to
the end of the line or position end I ndex (not including it).

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.

Controlling program execution


FIELD visibility unit
A block, or compound statement , is an arbitrary number of simple
Jav a statements , enclosed in curly braces. Blocks define the scope
of their variables. Blocks can be nested within one another. Here's
an example of a block nested inside another block in the main
method :
public static void main (String [] args)
{
int n;
...
{
int k; // Variable k is defined only in this block
}
}
However, in Java it is not possible to declare the same named
variables in two nested blocks. For example, the code snippet below
contains an error and will not compile.
public static void m ain (String [] args)
{
int n;
...
{
int k;
int n; // Error - cannot be overridden
// variable n in the inner block
}
}
Conditional second operator the if - the else
In generalized form, this operator is written as follows:
if (boolean expression) statement1; [ else statement2;]
The else section is optional. Any of the statements can be replaced
by a compound statement enclosed in curly braces. A boolean
expression (condition) is any expression that returns a boolean value
.
For example ,
if ( x > = y )
{
a=x;
b=y;
}
else
{
b=x;
a=y;
}

In the group of if - else statements, the else statements are


combined with the closest if statement . So in the code
if ( x < = 0)
if ( x = = 0)
sign = 0;
else
sign = -1;
the else statement corresponds to the second if statement .
Multivariate branching - switch statement
The switch statement provides a way to switch between different
parts of the program code depending on the value of one variable or
expression. The general form of this operator is as follows:
switch (expression)
{
case value1:
...
break ; // Exit from the switch statement
case value2:
...
break ;
case value:
...
break ;
default :
}
The result of calculating the expression value can be any integer
type ( byte , short , int or char ) , when e is each of the values
specified in the operators case , must be compatible with the
expression type in the operator switch . All of these values must be
unique.
If none of the case statements match the value of the expression ,
control is passed to the code after the default keyword . Note that the
default statement is optional. In the case when none of the case
statements match the value of the expression and there is no default
statement in the switch , the program execution continues from the
statement following the switch statement .
Cycle s while and do - while
The while loop executes the loop body only while its condition is met
:
while (condition) statement ;
The while loop will never execute if the condition is never met .
The while loop condition is checked at the very beginning. Therefore,
a situation is possible when the code contained in the block will
never be executed. If it is necessary for the block to be executed at
least once, the condition check must be moved to the end. This can
be done using a do - while loop . Its syntax looks like this:
do statement while (condition) ;
This statement executes the block and only then
checks the condition. Then it repeats the execution of
the block and checks the condition again, and so on.
For example :
i nt n = 10;
do
{
System.out.pri ntln ("tick" + n);
}
while (--n> 0);
cycle for
The general form of the statement for writing a for loop:
for ( initialization; condition; iteration) operator ;
Any loop written with a for statement can be written as a while loop ,
and vice versa. If the initial conditions are such that the termination
condition is not satisfied when entering the loop, then the body and
iteration statements are not executed even once. In the canonical th
cycle form for an increase integer counter with a minimum value to a
certain limit.
Example :
for (int i = 0 ; i <10; i ++)
System . out . println ( i );
When a variable is declared in the first part of a for statement, its
scope extends to the end of the loop body.
Sometimes there are situations when it is necessary to include
several statements in the initialization or iteration sections of the for
loop . In this case, d in A division operators can use the operation " ,
" ( it is permissible only within round brackets operator for ) . For
example :
int a, b;
for (a = 1, b = 4; a <b; a ++, b--)
{
System.out.println ("a = " + a);
System.out.println ("b =" + b);
}

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.

java . util . Arrays 1.2


static void sort (Xxx [] a)
The method orders the array using the quicksort algorithm.
Parameters : a Array of type int, long, short, char, byte, boolean,
float or double.

s tatic int binarySearch (Xxx [] a, Xxx v)


Method for finding the value v (using a binary search algorithm). If this value
is found, its index is returned.
Parameters: a Ordered array of type int , long , short ,

char, byte, boolean, float, or double.


v A value of the same type as the elements of array
a.
static void fill (Xxx [] a, Xxx v)
Sets all elements of the array v .
Parameters : a Array of type int, long, short, char, byte, boolean,

float or double .
v A value of the same type as the elements of array
a.

static boolean equals (Xxx [] a, Object other)


Returns true if other has the same type and length and the indices of the
corresponding elements match.
Parameters : a Array of type int, long, short, char, byte, boolean,

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

Command line parameters


Every Java program has a main method with a String [] args
parameter . This parameter means that the main method receives an
array of strings, namely the arguments specified on the command
line.
For example, consider the following program:
public class Message
{
public static void main (String [] args)
{
if (args.length ! = 0)
{
if (args [0] .equals ("- h"))
System.out.print ("Hello,");

else if (args [0] .equals ("- g"))


System . out . print (" Goodbye ,");

// Prints other command line arguments,


for (int i = 1; i <args.length; i ++)
System.out.print ("" + args [i]);

System . out . println ("!");


}
}
}
When calling the program with the below parameters
Java Message - h World
the args array will consist of args [0] = "- h " and args [1] = World .
The program will print a message
Hello , World !
Console I / O
I / O streams are discussed below in the appropriate section .
For now, note that the Java language has three built-in stream
objects to support console I / O, System . in , System . out and
System . err that you can use in your program without creating your
own threads.
The stream System . in an embedded object of a subclass of
InputStream and designed for keyboard input information . P ook
System . out is a subclass of OutputStream . and allows you to
display information on the monitor. The stream System . e rr - stream
for displaying error messages to the monitor.
To simplify conversion of input values of simple types and strings, it
is advisable to use the Scanner class from the java . util . Scanner .
First, you need to create an object such as the Scanner , which as a
parameter to be transmitted n Otok the System . in .
Below is a program that reads a line of text from the keyboard and
displays it on the monitor.

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 = "";

if (reader.hasNext ()) // Check for readability


// tokens of some type
{
text = reader.next (); // Returns the entered string
}

System.out.println (); // Or System.out.print ('\ n');

System.out.println (" You entered :" + 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 ;

if (reader.hasNext Int ()) // Check for readability


// values of type int
{
number = reader.next Int (); // Returns the introduction of th
number
}
Also, there are features nextBigDecimal , nextBigInteger ,
nextBoolean , nextByte , NextDouble , nextFloat , nextLong ,
nextShort and others .

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];

System.in.read (buffer); // read - from the InputStream class


String str = new String (buffer);

str = str . trim (); // Cut off the unfilled part of the line

/ / With additional line feed ('\ n ')


System . out . println ("You entered:" + str + '\ n ');

// 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

System.out.println ("You entered:" + ch);

System.out.printf ("You entered:% c \ n \ n", ch);


}
}

Objects and Classes


Introduction to Object Oriented Programming
Object-oriented programming (OOP) has become the dominant
programming paradigm, supplanting the "structured", procedural-
oriented programming techniques developed in the early 1970s. The
Java language is a fully object-oriented language .
Traditional structured programming consists in developing a set of
functions (algorithms) to solve a given problem. Having defined
these functions, the programmer must define an appropriate way to
store the data. T. . E first decided Xia question , how to manipulate
the data , and then - what structure to use for the organization of the
data. OOP has reversed the order of these actions by putting data
first and making the algorithms for processing it a secondary issue.
In OOP, any program consists of objects. The basic principle behind
the high performance of OOP is that each object is designed to
perform specific tasks. If an object is faced with a task for which it is
not intended, it must have access to another object that can solve
this task. Another object is accessed by calling a method on that
object. This is a generalized version of function calls used in
procedural programming.
An object should not directly manipulate the internal data of another
object, nor should it provide other objects with direct access to its
data. All communications between them are provided by calling a
methods.
OOP terminology
The main elements of the program are classes . A class is a
template by which an object is created . The class contains a
description of the data and algorithms for working with them . Create
an object on the basis of a class called creating an instance (
instance ) of the class.
Encapsulation ( the encapsulation ) - a key concept when working
with objects. Formally, encapsulation is the combination of data and
operations on them and hiding data from the user of the object. The
data object and are called instance fields ( instance fields ), and the
functions and procedures for carrying out operations on the data, -
its methods ( methods ). In a specified object, that is , an instance of
a class, the instance fields have specific values. The set of these
values is called the current state ( state ) of the object. Applying any
method to an object can change its state.
We emphasize once again that the main principle of encapsulation is
to prohibit direct access to the fields of an instance of a given class
by methods of other classes. Programs should interact with object
data only by the methods of this object. This means that the class
can completely change the way data storage, saving methods for
their treatment, while other objects can work with objects of this
class is and ever.
The object is also characterized by the concepts of n on the run by
me ( behavior ) and nature ( identity ) .
The behavior of an object is determined by methods that can be
called. All objects that are instances of the same class behave the
same.
SUMMARY s object is determined by what the object is different
from the other, characterized in the same behavior and condition.
And ndividualnye objects that represent instances of a class, are
always characterized by their essence and usually distinguished by
their state.
K lass can be constructed based on other classes. In this case, the
newly created class is said to extend the class on the basis of which
it is implemented . Language of the Java , in essence, is based on
"the global superclass" called the Object . All other objects expand it.
The new class contains all the properties and methods of the
extendable class, as well as new methods and data fields. Extension
of the class to create a new concept called inheritance ( inheritance
).
The ability of an object variable (t. E. A variable of type " object " ) to
refer to objects having different actual types is called polymorphism (
po lymorphism ).
Differences between OOP and Traditional
Procedural Programming
In procedural programming, the problem is first formulated and then:
or , using stepwise refinement, the original problem is
broken down into smaller and smaller subtasks until they
become so simple that they can be implemented directly
(top-down programming);
or procedures are created to solve simple problems; then
these procedures are combined into more complex ones,
until the program does exactly what is required
(programming "bottom-up").
Normally , of course, used camping mixed strategies - and the "top
down" , and "bottom-up".
The essential difference is that in object-oriented programming ,
classes are first allocated in the project , and only then their methods
are defined. There is another significant difference between
traditional procedures and OOP: each method is associated with a
class and the class is responsible for executing them.
For solving small problems, splitting a program into procedures is
quite justified. However, when developing large projects, classes and
methods have two advantages. Classes provide a convenient
mechanism for clustering methods. Simple nd Web-br and uzer for
its implementation may require 2000 functions and 100 classes, t. E.
An average of 20 methods in the classroom. The latter structure is
much easier for the programmer to understand . It is also easier to
distribute across the programming team. Encapsulation also
contributes to this: classes hide the details of the data presentation
from any code except their methods. E it means that if a
programming error distorts the data, the reason it is easier to find
among the 20 classes than in 2000 procedures.
There is also a more serious problem: while it is possible to create
several objects with the same behavior based on a class, in
procedural languages it is impossible to obtain multiple copies of the
same module. To do this, copy and rename all procedures . Classes
do not have such restrictions. Once you define a class, it is easy to
create any number of instances of it (while a module has only one
instance).
By Lass s
In order to create a class that is enough to have the source file that
will attend the keyword class and , after him , - a valid ID and curly ie
parentheses and which is determined by his body on .
class Point
{
... // class body
}
The name of the source file must match the name of the class it
contains. The case of letters is important in both the class name and
the file name. In this case, Point . java .
More generally, a class in a program is defined as follows (without
specifying access modifiers) :
class class_name [ extends superclass_name]
{
type object_variable [= value ]; // Fields
type object_variable2 [= value ]; // class
type variableN_object [= value ] ;

name _klassa () // The default constructor


{
}
name _klassa (list) // Constructor
Another random document with
no related content on Scribd:
“A wolf’s skin they gave her,
In which herself she clad.”
Odin’s Ravens’ Song (Thorpe’s tr.).

But although Idun passively allowed them to wrap her up in the


warm wolfskin, she persistently refused to speak or move, and the
gods sadly suspected she foresaw great ills, for the tears continually
rolled down her pallid cheeks. Bragi, seeing her unhappiness, bade
the other gods return to Asgard without him, vowing that he would
remain beside her until she was ready to leave Hel’s dismal realm.
But the sight of her woe oppressed him so sorely that he had no
heart for his usual merry songs, and the strings of his harp remained
entirely mute.

“That voice-like zephyr o’er flow’r meads creeping,


Like Bragi’s music his harp strings sweeping.”
Viking Tales of the North (R. B. Anderson).

In this myth Idun’s fall from Yggdrasil is symbolical of the


autumnal falling of the leaves, which lie limp and helpless on the cold
bare ground until they are hidden from sight under the snow,
represented by the wolfskin, which Odin, the sky, sends down to
keep them warm; and the cessation of the birds’ songs is further
typified by Bragi’s silent harp.
CHAPTER VIII.
NIÖRD.

We have already seen how the Æsir and Vanas exchanged


hostages after the terrible war they had waged against each other,
and that while Hoenir, Odin’s brother, went to live in Vana-heim,
Niörd, with his two children, Frey and Freya, definitely took up his
abode in Asgard.

“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.

“Niörd, the god of storms, whom fishers know;


Not born in Heaven—he was in Van-heim rear’d,
With men, but lives a hostage with the gods;
He knows each frith, and every rocky creek
Fringed with dark pines, and sands where sea fowl scream.”
Balder Dead (Matthew Arnold).

He also extended his special protection over commerce and


fishing, which two occupations could be pursued with advantage only
during the short summer months, of which he was in a measure
considered the personification.
Niörd is represented in art as a very handsome god, in the prime
of life, clad in a short green tunic, with a crown of
God of
summer. shells and seaweed upon his head, or a broad-
brimmed hat adorned with eagle or heron plumes. As
personification of the summer, he was invoked to still the raging
storms which desolated the coasts during the winter months. He was
also implored to hasten the vernal warmth and thereby extinguish
the winter fires.
As agriculture was practiced only during the summer months,
and principally along the fiords or sea inlets, Niörd was also invoked
for favorable harvests, for he was said to delight in prospering those
who placed their trust in him.
Niörd’s first wife, according to some authorities, was his sister
Nerthus, Mother Earth, who in Germany was identified with Frigga,
as we have seen, but in Scandinavia was considered a separate
divinity. He was, however, obliged to part with her when summoned
to Asgard, where he occupied one of the twelve seats in the great
council hall, and was present at all the assemblies of the gods,
withdrawing to Nôatûn only when his services were not required by
the Æsir.

“Nôatûn is the eleventh;


There Niörd has
Himself a dwelling made,
Prince of men;
Guiltless of sin,
He rules o’er the high-built fane.”
Lay of Grimnir (Thorpe’s tr.).

In his own home by the seashore, Niörd delighted in watching


the gulls fly to and fro, and in observing the graceful movements of
the swans, his favorite birds, which were held sacred to him. He
spent many an hour, too, considering the gambols of the gentle
seals, which came to bask in the sunshine at his feet.
Skadi, Shortly after Idun’s recovery from Thrym-heim,
goddess of and Thiassi’s death within the bounds of Asgard, the
winter.
assembled gods were greatly surprised and dismayed
to see Skadi, the giant’s daughter, appear one day in their midst,
demanding satisfaction for her father’s death. Although the daughter
of an ugly old Hrim-thurs, Skadi, the goddess of winter, was very
beautiful indeed, in her silvery armor, with her glittering spear, sharp-
pointed arrows, short white hunting dress, white fur leggings, and
broad snowshoes, and as she confronted the gods they could not
but recognize the justice of her claim, and offered the usual fine in
atonement. Skadi, however, was so very angry that she at first
refused this compromise, and sternly demanded a life for a life, until
Loki, wishing to appease her wrath, and thinking that if he could only
make those proud lips unbend enough to smile the rest would be
easy, began to play all manner of pranks. Fastening a goat to himself
by an invisible cord, he went through a series of antics, grotesquely
reproduced by the goat; and this sight was so very comical that all
the gods fairly shouted with merriment, and even Skadi was seen to
smile.
Taking advantage of this softened mood, the gods pointed to the
firmament where her father’s eyes glowed like radiant stars in the
northern hemisphere. They told her they had placed them there to
show him all honor, and finally added that she might select as
husband any of the gods present at the assembly, providing she
were content to judge of their attractions by their naked feet.
Blindfolded, so that she could see only the feet of the gods
standing in a circle around her, Skadi looked about her until she saw
a pair of beautifully formed feet. She felt sure they must belong to
Balder, the god of light, whose bright face had charmed her, and she
designated their owner as her choice.
But when the bandage was removed, she discovered to her
secret chagrin that she had chosen Niörd, to whom her troth was
plighted, and with whom she nevertheless spent a very happy
honeymoon in Asgard, where all seemed to delight in doing her
honor. This time passed, however; Niörd took his bride home to
Nôatûn, where the monotonous sound of the waves, the shrieking of
the gulls, and the cries of the seals so disturbed Skadi’s slumbers
that she finally declared it was quite impossible for her to remain
there any longer, and implored her husband to take her back to her
native Thrym-heim.

“Sleep could I not


On my sea-strand couch,
For screams of the sea fowl.
There wakes me,
When from the wave he comes,
Every morning the mew (gull).”
Norse Mythology (R. B. Anderson).

Niörd, anxious to please his new wife, consented to take her to


Thrym-heim and dwell there with her nine nights out of every twelve,
providing she would spend the remaining three with him at Nôatûn;
but when he reached the mountain region, the soughing of the wind
in the pines, the thunder of the avalanches, the cracking of the ice,
the roar of the waterfalls, and the howling of the wolves appeared to
him as unbearable as the sound of the sea had seemed to his wife,
and he could not but rejoice when his time of exile was ended, and
he once more found himself domiciled at Nôatûn.

“Am weary of the mountains;


Not long was I there,
Only nine nights;
The howl of the wolves
Methought sounded ill
To the song of the swans.”
Norse Mythology (R. B. Anderson).

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.

“Thrym-heim it’s called,


Where Thjasse dwelled,
That stream-mighty giant;
But Skade now dwells,
Pure bride of the gods,
In her father’s old mansion.”
Norse Mythology (R. B. Anderson).

Skadi now resumed her wonted pastime of hunting, leaving her


realm again only to marry the semi-historical Odin, to whom she bore
a son called Sæming, the first king of Norway, and the supposed
founder of the royal race which long ruled that country.
According to other accounts, however, Skadi eventually married
Uller, the winter-god. As Skadi was a skillful markswoman, she is
represented with bow and arrow, and, as goddess of the chase, she
is generally accompanied by one of the wolf-like Eskimo dogs so
common in the North. Skadi was invoked by hunters and by winter
travelers, whose sleighs she guided over the snow and ice, thus
helping them to reach their destination in safety.
Skadi’s anger against the gods, who had slain her father, the
storm giant, is an emblem of the unbending rigidity of the ice-
enveloped earth, which, softened at last by the frolicsome play of
Loki (the heat lightning), smiles, and permits the embrace of Niörd
(summer). His love, however, cannot hold her for more than three
months of the year (typified in the myth by nights), as she is always
secretly longing for the wintry storms and her wonted mountain
amusements.
As Niörd was supposed to bless the vessels passing in and out
Worship of of port, his temples were situated by the seashore; it
Niörd. was there that the oaths in his name were commonly
sworn, and his health was drunk at every banquet, where he was
invariably named with his son Frey.
As all aquatic plants were supposed to belong to him, the marine
sponge was known in the North as “Niörd’s glove,” a name which
was retained until lately, when the same plant has been popularly
called the “Virgin’s hand.”
CHAPTER IX.
FREY.

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.

“Alf-heim the gods to Frey


Gave in days of yore
For a tooth gift.”
Sæmund’s Edda (Thorpe’s tr.).

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.

“With a short-shafted hammer fights conquering Thor;


Frey’s own sword but an ell long is made.”
Viking Tales of the North (R. B. Anderson).

The dwarfs from Svart-alfa-heim gave Frey the golden-bristled boar


Gullin-bursti (the golden-bristled), a personification of the sun. The
radiant bristles of this animal were considered symbolical either of the
solar rays, of the golden grain, which at his bidding waved over the
harvest fields of Midgard, or of agriculture, for the boar (by tearing up the
ground with his sharp tusk) was supposed to have first taught mankind
how to plow.

“There was Frey, and sat


On the gold-bristled boar, who first, they say,
Plowed the brown earth, and made it green for Frey.”
Lovers of Gudrun (William Morris).

Frey sometimes rode astride of this marvelous boar, whose celerity


was very great, and at other times harnessed him to his golden chariot,
which was said to contain the fruits and flowers which he lavishly
scattered abroad over the face of the earth.
Frey was, moreover, the proud possessor, not only of the dauntless
steed Blodug-hofi, which dashed through fire and water at his command,
but also of the magic ship Skidbladnir, a personification of the clouds.
This vessel, navigating over land and sea, was always wafted along by
favorable winds, and was so elastic that, while it could assume large
enough proportions to carry the gods, their steeds, and all their
equipments, it could also be folded up like a napkin and thrust out of
sight.
“Ivaldi’s sons
Went in days of old
Skidbladnir to form,
Of ships the best,
For the bright Frey,
Niörd’s benign son.”
Lay of Grimnir (Thorpe’s tr.).

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.

“In Gymer’s court I saw her move,


The maid who fires my breast with love;
Her snow-white arms and bosom fair
Shone lovely, kindling sea and air.
Dear is she to my wishes, more
Than e’er was maid to youth before;
But gods and elves, I wot it well,
Forbid that we together dwell.”
Skirner’s Lay (Herbert’s tr.).

Skirnir, however, consolingly replied that he could see no reason


why his master should take such a despondent view of the matter, and
proposed to go and woo the maiden in his name, providing Frey would
lend him his steed for the journey, and give him his glittering sword in
reward.
Overjoyed at the mere prospect of winning the beautiful Gerda, Frey
handed Skirnir the flashing sword, and bade him use his horse, ere he
resumed his interrupted day-dream; for ever since he had fallen in love
he had frequently indulged in revery. In his absorption he did not even
notice that Skirnir was still hovering near him, and did not perceive him
cunningly steal the reflection of his face from the surface of the brook
near which he was seated, and imprison it in his drinking horn, intending
“to pour it out in Gerda’s cup, and by its beauty win the heart of the
giantess for the lord” for whom he was about to go a-wooing. Provided
with this portrait, with eleven golden apples, and with the magic ring
Draupnir, Skirnir now rode off to Jötun-heim, to fulfill his embassy. As
soon as he came near Gymir’s dwelling he heard the loud and persistent
howling of his watch dogs, which were personifications of the wintry
winds. A shepherd, guarding his flock in the vicinity, told him, in answer
to his inquiry, that it would be impossible for him to approach the house,
on account of the flaming barrier which surrounded it; but Skirnir,
knowing that Blodug-hofi would dash through any fire, merely set spurs
to his steed, and, riding up to the giant’s door, soon found himself
ushered into the presence of the lovely Gerda.
To induce this fair maiden to lend a favorable ear to his master’s
proposals, Skirnir showed her the purloined portrait, and proffered the
golden apples and magic ring, which she haughtily refused to accept,
declaring that her father had gold enough and to spare.

“I take not, I, that wondrous ring,


Though it from Balder’s pile you bring.
Gold lack not I, in Gymer’s bower;
Enough for me my father’s dower.”
Skirner’s Lay (Herbert’s tr.).
Indignant at her scorn, Skirnir now threatened to use his magic
sword to cut off her head; but as this threat did not in the least frighten
the maiden, and she calmly defied him, he had recourse to magic arts.
Cutting runes in his stick, he told her that unless she yielded ere the
spell was ended, she would be condemned either to eternal celibacy, or
to marry some hideous old frost giant whom she could never love.
Terrified into submission by the frightful description he gave of her
cheerless future in case she persisted in her refusal, Gerda finally
consented to become Frey’s wife, and dismissed Skirnir, promising to
meet her future spouse on the ninth night, in the land of Buri, the green
grove, where she would dispel his sadness and make him happy.

“Burri is hight the seat of love;


Nine nights elapsed, in that known grove
Shall brave Niorder’s gallant boy
From Gerda take the kiss of joy.”
Skirner’s Lay (Herbert’s tr.).

Delighted with his success, Skirnir hurried back to Alf-heim, where


Frey eagerly came to meet him, and insisted upon knowing the result of
his journey. When he learned that Gerda had consented to become his
wife, his face grew radiant with joy; but when Skirnir further informed him
that he would have to wait nine nights ere he could behold his promised
bride, he turned sadly away, declaring the time would appear
interminable.

“Long is one night, and longer twain;


But how for three endure my pain?
A month of rapture sooner flies
Than half one night of wishful sighs.”
Skirner’s Lay (Herbert’s tr.).

In spite of this loverlike despondency, however, the time of waiting


came to an end, and Frey joyfully hastened to the green grove, where
he met Gerda, who became his happy wife, and proudly sat upon his
throne beside him.
“Frey to wife had Gerd;
She was Gymir’s daughter,
From Jötuns sprung.”
Sæmund’s Edda (Thorpe’s tr.).

According to some mythologists, Gerda is not a personification of


the aurora borealis, but of the earth, which, hard, cold, and unyielding,
resists the spring-god’s proffers of adornment and fruitfulness (the
apples and ring), defies the flashing sunbeams (Frey’s sword), and only
consents to receive his kiss when it learns that it will else be doomed to
perpetual barrenness, or given over entirely into the power of the giants
(ice and snow). The nine nights of waiting are typical of the nine winter
months, at the end of which the earth becomes the bride of the sun, in
the groves where the trees are budding forth into leaf and blossom.
Frey and Gerda, we are told, became the parents of a son called
Fiolnir, whose birth consoled Gerda for the loss of her brother Beli. The
latter had attacked Frey and had been slain by him, although the sun-
god, deprived of his matchless sword, had been obliged to defend
himself with a stag horn which he hastily snatched from the wall of his
dwelling.
Besides the faithful Skirnir, Frey had two other attendants, a married
couple, Beyggvir and Beyla, the personifications of mill refuse and
manure, which two ingredients, being used in agriculture for fertilizing
purposes, were therefore considered Frey’s faithful servants, in spite of
their unpleasing qualities.
Snorro-Sturleson, in his “Heimskringla,” or chronicle of the ancient
The historical kings of Norway, states that Frey was an historical
Frey. personage who bore the name of Ingvi-Frey, and ruled in
Upsala after the death of the semi-historical Odin and
Niörd. Under his reign the people enjoyed such prosperity and peace
that they declared their king must be a god. They therefore began to
invoke him as such, carrying their enthusiastic admiration for him to such
lengths that when he died the priests, not daring to reveal the fact, laid
him in a great mound instead of burning his body, as had been
customary until then. They then informed the people that Frey—whose
name was the Northern synonym for “master”—had “gone into the
mound,” an expression which eventually became the Northern phrase
for death.
Only three years later the people, who had continued paying their
taxes to the king by pouring the gold, silver, and copper coin into the
mound by three different openings, discovered that Frey was dead. As
their peace and prosperity had remained undisturbed, they decreed that
his corpse should never be burned, and thus inaugurated the custom of
mound burial, which in due time supplanted the funeral pyre in many
places. One of the three mounds near Gamla Upsala still bears this
god’s name. His statues were placed in the great temple there, and his
name was duly mentioned in all solemn oaths, of which the usual
formula was, “So help me Frey, Niörd, and the Almighty Asa” (Odin).
No weapons were ever admitted in Frey’s temples, the most
Worship of celebrated of which were at Throndhjeim, and at Thvera
Frey. in Iceland where oxen or horses were offered up in
sacrifice to him, and where a heavy gold ring was dipped
in the victim’s blood ere the above-mentioned oath was solemnly taken
upon it.
Frey’s statues, like those of all the other Northern divinities, were
roughly hewn blocks of wood, and the last of these sacred images
seems to have been destroyed by Olaf the Saint, who forcibly converted
many of his subjects. Besides being god of sunshine, fruitfulness, peace,
and prosperity, Frey was considered the patron of horses and horsemen,
and the deliverer of all captives.

“Frey is the best


Of all the chiefs
Among the gods.
He causes not tears
To maids or mothers:
His desire is to loosen the fetters
Of those enchained.”
Norse Mythology (R. B. Anderson).

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:

“Caput apri defero


Reddens laude Domino.
The boar’s head in hand bring I,
With garlands gay and rosemary.
I pray you all sing merrily
Qui estis in convivio.”
Queen’s College Carol, Oxford.
The father of the family then laid his hand on this dish, which was
called “the boar of atonement,” swearing he would be faithful to his
family, and would fulfill all his obligations—an example which was
followed by all present, from the highest to the lowest. This dish could be
carved only by a man of unblemished reputation and tried courage, for
the boar’s head was a sacred emblem which was supposed to inspire
every one with fear. For that reason a boar’s head was frequently used
as ornament for the helmets of Northern kings and heroes whose
bravery was unquestioned.
As Frey’s name of Fro is phonetically the same as the word used in
God of German for gladness, he was considered the patron of
conjugal every joy, and was invariably invoked by married couples
happiness. who wished to live in harmony. Those who succeeded in
doing so for a certain length of time were publicly rewarded by the gift of
a piece of boar’s flesh, for which, in later times, the English and
Viennese substituted a flitch of bacon or a ham.

“You shall swear, by custom of confession,


If ever you made nuptial transgression,
Be you either married man or wife:
If you have brawls or contentious strife;
Or otherwise, at bed or at board,
Offended each other in deed or word;
Or, since the parish clerk said Amen,
You wish’d yourselves unmarried again;
Or, in a twelvemonth and a day
Repented not in thought any way,
But continued true in thought and desire
As when you join’d hands in the quire.
If to these conditions, with all feare,
Of your own accord you will freely sweare,
A whole gammon of bacon you shall receive,
And bear it hence with love and good leave:
For this our custom at Dunmow well known—
Though the pleasure be ours, the bacon’s your own.”
Brand’s Popular Antiquities.
At Dunmow, England, and in Vienna, Austria, this custom was kept
up very long indeed, the ham or flitch of bacon being hung over the city
gate, whence the successful candidate was expected to bring it down,
after he had satisfied the judges that he lived in peace with his wife, but
was not under petticoat rule. It is said that in Vienna this ham once
remained for a long time unclaimed until at last a worthy burgher
presented himself before the judges, bearing his wife’s written affidavit
that they had been married twelve years and had never disagreed—a
statement which was confirmed by all their neighbors. The judges,
satisfied with the proofs laid before them, told the candidate that the
prize was his, and that he only need climb the ladder placed beneath it
and bring it down. Rejoicing at having secured such a fine ham, the man
obeyed; but as he was about to reach upwards, he noticed that the ham,
exposed to the noonday sun, was beginning to melt, and that a drop of
fat threatened to fall upon and stain his Sunday coat. Hastily beating a
retreat, he pulled off his coat, jocosely remarking that his wife would
scold him roundly were he to stain it, a confession which made the
bystanders roar with laughter, and which cost him his ham.
Another Yule-tide custom was the burning of a huge log, which had
to last all night or it was considered of very bad omen indeed. The
charred remains of this log were carefully collected, and treasured up to
set fire to the log of the following year.

“With the last yeeres brand


Light the new block, and
For good successe in his spending,
On your psaltries play,
That sweet luck may
Come while the log is a-tending.”
Hesperides (Herrick).

This festival was so popular in Scandinavia, where it was celebrated


in January, that King Olaf, seeing how dear it was to the Northern heart,
transferred most of its observances to Christmas day, thereby doing
much to reconcile the ignorant people to their change of religion.
As god of peace and prosperity, Frey is supposed to have
reappeared upon earth many times, and to have ruled the Swedes
under the name of Ingvi-Frey, whence his descendants were called
Inglings. He also governed the Danes under the name of Fridleef. In
Denmark he is said to have married the beautiful maiden Freygerda,
whom he had rescued from a dragon. By her he had a son named Frodi,
who, in due time, succeeded him as king.
This Frodi ruled Denmark in the days when there was “peace
throughout all the world,” that is to say, just at the time when Christ was
born in Bethlehem of Judea; and because all his subjects lived in amity,
he was generally known as Peace Frodi.
This king once received from Hengi-kiaptr a pair of magic millstones,
How the sea called Grotti, which were so ponderous that none of his
became salt. servants nor even his strongest warriors could turn them.
As Peace Frodi knew that the mill was enchanted and
would grind anything he wished, he was very anxious indeed to set it to
work, and, during a visit to Sweden, saw and purchased as slaves the
two giantesses Menia and Fenia, whose powerful muscles and frames
had attracted his attention.
On his return home, Peace Frodi led these women to the mill, and
bade them turn the grindstones and grind out gold, peace, and
prosperity—a wish which was immediately fulfilled. Cheerfully the
women worked on, hour after hour, until the king’s coffers were
overflowing with gold and his land with prosperity and peace.

“Let us grind riches to Frothi!


Let us grind him, happy
In plenty of substance,
On our gladdening Quern.”
Grotta-Savngr (Longfellow’s tr.).

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.

“An army must come


Hither forthwith,
And burn the town
For the prince.”
Grotta-Savngr (Longfellow’s tr.).

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.

You might also like