[PDF Download] Learning Java: Beginning programming with java for dummies Bach fulll chapter

rooyeemokono 48 views 64 slides Aug 20, 2024
Slide 1
Slide 1 of 64
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64

About This Presentation

Instant download Learning Java: Beginning programming with java for dummies Bach after payment at https://ebookmass.com/product/learning-java-beginning-programming-with-java-for-dummies-bach .Get more ebooks or text book new 2024 in https://ebookmass.com . Instant download pdf full chapter


Slide Content

Download More ebooks [PDF]. Format PDF ebook download PDF KINDLE.
Full download ebooks at ebookmass.com
Learning Java: Beginning programming
with java for dummies Bach
For dowload this book click BUTTON or LINK below
https://ebookmass.com/product/learning-java-
beginning-programming-with-java-for-dummies-bach/
OR CLICK BUTTON
DOWLOAD NOW
Download More ebooks from https://ebookmass.com

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$&(--(-& P1.&1 ,,(-& 6(3' J 5
F.1 D4,,($2


By
John Bach

For information contact :
([email protected], 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 typeSize in bytes Change interval
int 4 o t - 2147 483648 up to 2147483647
short 2 from -32768 up to 32767
l ong 8
o t -
9223372036854775808L
up to
922337203685477580
7 L
byte 1 o t - 12 8 up to 1 27
float 4
from - 3.4 02823 47 Е
38 F
up to 3.4 02823 47 E +
38 F
double 8
from - 1.7976931348623 1
57 E + 308
D o 1.79769313486231
57 E + 308
char 2 from 0 ( ' \ u0000 ' )
up to 65535 ( ' \ uFFFF
' )

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)
Returns a large decimal number equal to the value of x or x / 10
sc ale
.
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;
d o
{
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:
0 1
2 3
4 5
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

Another random document with
no related content on Scribd:

el llanto
que quasi tiene mi ánimo
deshecho?
Sólo á Syreno cuento sin
provecho
mi triste desventura,
que della tanto cura
como el furioso viento en
mar insano
las lágrimas que en vano
derrama el congojado
marinero,
pues cuanto más le ruega,
más es fiero.

No ha sido fino amor, Syreno
mío,
el que por estos campos me
mostrabas,
pues un descuido mío ansí
le ofende.
¿Acuérdaste, traidor, lo que
jurabas
sentado en este bosque y
junto al río?
¿pues tu dureza agora qué
pretende?
¿No bastará que el simple
olvido emiende
con un amor sobrado,
y tal, que si al passado
olvido no aventaja de gran
parte
(pues más no puedo
amarte,
ni con mayor ardor
satisfacerte)

por remedio tomar quiero la
muerte?

Mas viva yo en tal pena, pues
la siento
por ti, que haces menor toda
tristura,
aunque más dañe el ánima
mezquina.
Porque tener presente tu
figura
da gusto aventajado al
pensamiento
de quien por ti penando en ti
imagina.
Mas tú á mi ruego ardiente un
poco inclina
el corazón altivo,
pues ves que en penas vivo
con un solo deseo
sostenida,
de oir de ti en mi vida
siquiera un no en aquello
que más quiero.
¿Mas qué se ha de esperar
de hombre tan fiero?

¿Cómo agradesces, dime, los
favores
de aquel tiempo passado
que tenías
mas blando el corazón, duro
Syreno,
cuando, traidor, por causa
mía hacías
morir de pura envidia mil
pastores.

¡Ay, tiempo de alegría! ¡Ay,
tiempo bueno!
Será testigo el valle y prado
ameno,
á do de blancas rosas
y flores olorosas
guirnalda á tu cabeza
componía,
do á veces añadía
por sólo contentarte algún
cabello:
que muero de dolor
pensando en ello.
Agora andas essento
aborresciendo
la que por ti en tal pena se
consume:
pues guarte de las mañas
de Cupido.
Que el corazón soberbio, que
presume
del bravo amor estarse
defendiendo,
cuanto más armas hace, es
más vencido.
Yo ruego que tan preso y tan
herido
estés como me veo.
Mas siempre á mi deseo
no desear el bien le es buen
aviso,
pues cuantas cosas quiso,
por más que tierra y cielos
importuna,
se las negó el Amor y la
Fortuna.
Canción, en algún pino ó dura

encina
no quise señalarte,
mas antes entregarte
al sordo campo y al
mudable viento:
porque de mi tormento
se pierda la noticia y la
memoria,
pues ya perdida está mi vida
y gloria.
La delicada voz y gentil gracia de
la hermosaDiana hacía muy clara
ventaja á las habilidades de su
tiempo: pero más espanto daba
ver las agudezas con que
matizaba sus cantares, porque
eran tales, que parescían salidas
dela avisada corte. Mas esto no
ha de maravillar tanto los
hombres que lo tengan por
impossible: pues está claro que
es bastante el Amor para hacer
hablar á los más simples pastores
avisos más encumbrados,
mayormente si halla aparejo de
entendimiento vivo é ingenio
despierto, que en las pastoriles
cabañas nunca faltan. Pues
estando ya la enamorada pastora
al fin de su canción, al tiempo que
el claro solya comenzaba á dorar
las cumbres de los más altos
collados, el desamado Marcelio,
de la pastoril posada despedido
para venir al lugar que con Diana
tenía concertado, descendió la

cuesta á cuyo pie ella sentada
estaba. Vióle ella delejos, y calló
su voz, porque no entendiesse la
causa de su mal. Cuando
Marcelio llegó donde Diana le
esperaba, le dijo: Hermosa
pastora, el claro día de hoy, que
con la luz detu gesto amaneció
más resplandeciente, sea tan
alegre para ti como fuera triste
para mí si no lehubiesse de
passar en tu compañía. Corrido
estoy en verdad de ver que mi
tardanza haya sido causa que
recibiesses pesadumbre con
esperarme; pero no será este el
primer yerro que le has de
perdonar á mi descuido, en tanto
que tratarás conmigo. Sobrado
sería el perdón, dijoDiana , donde
el yerro falta: la culpa no latiene
tu descuido, sino mi cuidado,
pues mehizo levantar antes de
hora y venir acá, donde hasta
agora he passado el tiempo, á
veces cantando y á veces
imaginando, y en fin entendiendo
en los tratos que á un angustiado
espíritu pertenescen. Mas no
hace tiempo de deternosaquí,
que aunque el camino hasta el
templo de Diana es poco, el
deseo que tenemos dellegar allá
es mucho. Y allende de esto me
paresce que conviene, en tanto
que el sol envía más mitigados
los rayos y no son tan fuertes sus

ardores, adelantar el camino, para
después,á la hora de la siesta, en
algún lugar fresco ysombrío tener
buen rato de sossiego. Dicho
esto, tomaron entrambos el
camino, travesando aquel
espesso bosque, y por alivio del
caminocantaban deste modo:
MARCELIO
Mudable y fiero Amor, que mi
ventura
pusiste en la alta cumbre,
do no llega mortal
merescimiento.
Mostraste bien tu natural
costumbre,
quitando mi tristura,
para doblarla y dar mayor
tormento.
Dejaras descontento
el corazón: que menos daño
fuera
vivir en pena fiera
que recebir un gozo no
pensado,
con tan penosas lástimas
borrado.
DIANA
No te debe espantar que de tal
suerte
el niño poderoso
tras un deleite envíe dos mil

penas.
Que á nadie prometió firme
reposo,
sino terrible muerte,
llantos, congojas, lágrimas,
cadenas.
En Libya las arenas,
ni en el hermoso Abril las
tierras flores
no igualan los dolores
con que rompe el Amor un
blando pecho,
y aun no queda con ello
satisfecho.
MARCELIO
Antes del amoroso
pensamiento
ya tuve conoscidas
las mañas con que Amor
captiva y mata.
Mas él no sólo aflige nuestras
vidas,
mas el conoscimiento
de los vivos juicios arrebata.
Y el alma ansí maltrata,
que tarde y mal y por
incierta vía
allega una alegría,
y por dos mil caminos los
pesares
sobre el perdido cargan á
millares.
DIANA

Si son tan manifiestos los
engaños
con que el Amor nos
prende,
¿por qué á ser presa el
alma se presenta?
Si el blando corazón no se
defiende
de los terribles daños,
¿por qué después se queja
y se lamenta?
Razón es que consienta
y sufra los dolores de
Cupido
aquel que ha consentido
al corazón la flecha y la
cadena:
que el mal no puede darnos
sino pena.
Esta canción y otras cantaron, al
cabo de lascuales estuvieron ya
fuera del bosque, y comenzaroná
caminar por un florido y deleitoso
prado. Entonces dijo Diana estas
palabras: Cosas son maravillosas
las que la industria de los
hombres en las pobladas
ciudades ha inventado, pero más
espauto dan las que la naturaleza
en los solitarios campos ha
producido. ¿A quién no admira la
frescura deste sombroso bosque?
¿quién no se espanta de la
lindeza de este espacioso prado?
Pues ver los matices de las
libreadas flores, y oir el concierto

de las cantadorasaves, es cosa
de tanto contento que noiguala
con ello de gran parte la pompa y
abundancia de la más celebrada
corte. Ciertamente, dijo
Marcelio , en esta alegre soledad
hay gran aparejo de
contentamiento, mayormentepara
los libres, pues les es licito gozar
ásu voluntad de tan admirables
dulzuras y entretenimientos. Y
tengo por muy cierto que si el
Amor, que agora, morando en
estos desiertos, me es tan
enemigo, me diera en la villa
donde yo estaba la mitad del
dolor que agorasiento, mi vida no
osara esperado, pues no pudiera
con semejantes deleites amansar
la bravezadel tormento. A esto no
respondió Dianapalabra, sino
que, puesta la blanca mano
delante sus ojos, sosteniendo con
ella la dorada cabeza, estuvo
gran rato pensosa, dando de
cuando en cuando muy
angustiados suspiros, y á cabo de
gran pieza dijo ansí: ¡Ay de mí,
pastora desdichada! ¿qué
remedio será bastante á consolar
mi mal, si los que quitan á los
otros gran parte del tormento
acarrean más ardiente dolor? No
tengo ya sufrimiento para encubrir
mi pena, Marcelio; mas ya que la
fuerza deldolor me constriñe á
publicarla, una cosa leagradezco,

que me fuerza á decirla en tiempo
yen parte en que tú solo estés
presente, pues por tus generosas
costumbres y por la experiencia
que tienes de semejante mal, no
tendrás por sobrada mi locura,
principalmente sabiendo la causa
della. Yo estoy maltratada del mal
que te atormenta, y no olvidada
como tú de un pastor llamado
Syreno, del cual que en otro
tiempo fuí querida. Mas la
Fortuna, que pervierte los
humanos intentos, quiso que,
obedesciendo más ámi padre
que á mi voluntad, dejasse de
casarme con él, y á mi pesar me
hiciesse esclava deun marido
que, cuando otro mal no tuviera
con él sino el que causan sus
continuos é importunados celos,
bastaba para matarme. Mas yo
metuviera por contenta de sufrir
las sospechas deDelio con que
viera la preferencia de Syreno, el
cual creo que por no verme,
tomando de mi forzado
casamiento ocasión para
olvidarme, seapartó de nuestra
aldea, y está, según he sabido,en
el templo de Diana, donde
nosotros imos. De aquí puedes
imaginar cuál puedo estar,
fatigada de los celos del marido y
atormentada con la ausencia del
amado. Dijo entonces Marcelio :
Graciosa pastora, lastimado

quedo desaber tu dolor y corrido
de no haberle hasta agora sabido.
Nunca yo me vea con el deseado
contento sino querría verle tanto
en tu alma como en la mía. Mas,
pues sabes cuán generales son
las flechas del Amor, y cuán poca
cuenta tienen con los más fuertes,
libres y más honestos corazones,
no tengas afrenta de publicar sus
llagas, pues no quedará por ellas
tunombre denostado, sino en
mucho más tenido. Lo que á mí
me consuela es saber que el
tormento que de los celos del
marido recibías, el cual suele dar
á veces mayor pena que la
ausencia de la cosa amada, te
dejará algún rato descansar, en
tanto que Delio, siguiendo la
fugitiva pastora, estará apartado
de tu compañía.Goza, pues, del
tiempo y acasión que teconcede
la fortuna, y alégrate, que no será
poco alivio para ti passar la
ausencia de Syreno libre de la
importunidad del celoso marido.
No tengo yo, dijo Diana , por tan
dañosos loscelos, que si como
son de Delio fueran de Syreno, no
los sufriera con sólo imaginar que
tenían fundamento en amor.
Porque cierto está que quien ama
huelga de ser amado, y ha de
tener los celos de la cosa amada
por muy buenos, pues son claras
señales de amor, nascen dél y

siempre van con él acompañados.
De míá lo menos te puedo decir
que nunca me tuve por tan
enamorada como cuando me vi
celosa, y nunca me vi celosa sino
estando enamorada. A lo cual
replicó Marcelio : Nunca pensé
que la pastoril llaneza fuesse
bastante á formar tan avisadas
razones como las tuyas en
cuestión tan dificultosa como es
ésta. Y de aquí vengo á condenar
por yerro muy reprobado decir,
como muchos afirman, que en
solas las ciudades ycortes está la
viveza de los ingenios, pues la
hallé también entre las
espessuras de los bosques,y en
las rústicas é inartificiosas
cabañas. Pero con todo, quiero
contradecir á tu parescer,con el
cual heciste los celos tan ciertos
mensajeros y compañeros del
amor, como si no pudiesse estar
en parte donde ellos no estén.
Porque puesto que hay pocos
enamorados que no sean
celosos, no por eso se ha de decir
que elenamorado que no lo fuere
no sea más perfecto y verdadero
amador. Antes muestra en ello el
valor, fuerza y quilate de su
deseo, pues está limpio y sin la
escoria de frenéticas sospechas.
Tal estaba yo en el tiempo
venturoso, y me preciaba tanto
dello, que con mis versos lo iba

publicando, y una vez entre las
otras, que mostró Alcida
maravillarse de verme enamorado
ylibre de celos, le escribí sobre
ello este
Soneto.
Dicen que Amor juró que no
estaria
sin los mortales celos un
momento,
y la Belleza nunca hacer
assiento,
do no tenga Soberbia en
compañía.
Dos furias son, que el bravo
infierno envía,
bastantes á enturbiar todo
contento:
la una el bien de amor
vuelve en tormento,
la otra de piedad la alma
desvía.
Perjuro fué el Amor y la
Hermosura
en mí y en vos, haciendo
venturosa
y singular la suerte de mi
estado.
Porque después que vi
vuestra figura,
ni vos fuistes altiva, siendo
hermosa,
ni yo celoso, siendo
enamorado.

Fué tal el contento que tuvo mi
Alcida cuando le dije este soneto,
entendiendo por élla fineza de mi
voluntad, que mil veces se le
cantaba, sabiendo que con ello le
era muy agradable. Y
verdaderamente, pastora, tengo
pormuy grande engaño, que un
monstruo tan horrendo como los
celos se tenga por cosa buena,
con decir que son señales de
amor y que no están sino en el
corazón enamorado. Porque á
essa cuenta podremos decir que
la calentura es buena, pues es
señal de vida y nunca está sino
en el cuerpo vivo. Pero lo uno y lo
otro son manifiestos errores, pues
no dan menor pesadumbre los
celos que la fiebre. Porque son
pestilencia de las almas, frenesía
de los pensamientos, rabia que
los cuerpos debilita, ira que el
espíritu consume, temor que los
ánimos acobarda y furia que las
voluntades enloquesce. Mas para
que juzgues ser los celos cosa
abominable, imagina la causa
dellos, y hallarás que no es otra
sino un apocado temor de lo que
noes ni será, un vil menosprecio
del propio merescimiento y una
sospecha mortal, que pone en
duda la fe y la bondad de la cosa
querida. Nopueden, pastora, con
palabras encarescerse laspenas
de los celos, porque son tales,

que sobrepujan de gran parte los
tormentos que acompañan el
amor. Porque en fin, todos, sino
él,pueden y suelen parar en
admirables dulzuras y contentos,
que ansí como la fatigosa sed en
el tiempo caloroso hace parescer
más sabrosas las frescas aguas,
y el trabajo y sobresalto dela
guerra hace que tengamos en
mucho el sossiegode la paz, ansí
los dolores de Cupido sirvenpara
mayor placer en la hora que se
rescibe un pequeño favor, y
cuando quiera que segoze de un
simple contentamiento. Mas estos
rabiosos celos esparcen tal
veneno en los corazones, que
corrompe y gasta cuantos deleites
sele llegan. A este propósito, me
acuerdo que yooí contar un día á
un excelente músico en Lisbona
delante del Rey de Portugal un
sonetoque decía ansi:
Quando la brava ausencia un
alma hiere,
se ceba, imaginando el
pensamiento,
que el bien, que está más
lejos, más contento
el corazón hará cuando
viniere.
Remedio hay al dolor de quien
tuviere
en esperanza puesto el
fundamento;

que al fin tiene algún premio
del tormento,
o al menos en su amor
contento muere.
Mil penas con un gozo se
descuentan,
y mil reproches ásperos se
vengan
con sólo ver la angélica
hermosura.
Mas cuando celos la ánima
atormentan,
aunque después mil bienes
sobrevengan,
se tornan rabia, pena y
amargura.
¡Oh, cuán verdadero parescer!
¡Oh, cuán cierta opinión es ésta!
Porque á la verdad, esta
pestilenciade los celos no deja en
el alma parte sana donde pueda
recogerse una alegría. Nohay en
amor contento, cuando no hay
esperanza, y no la habrá, en tanto
que los celos están de por medio.
No hay placer que dellos esté
seguro, no hay deleite que con
ellos no se gaste y no hay dolor
que con ellos no nos fatigue. Y
llega á tanto la rabia y furor de los
venenosos celos, que el corazón,
donde ellos están, recibe
pesadumbre en escuchar
alabanzas de la cosa amada, y no
querría que las perfecciones que
élestima fuessen de nadie vistas

ni conocidas, haciendo en ello
gran perjuicio al valor de la
gentileza que le tiene captivo. Y
no sólo el celoso vive en este
dolor, mas á la que bien quiere le
da tan continua y trabajosa pena,
que nole diera tanta, si fuera su
capital enemigo. Porque claro
está que un marido celoso como
eltuyo, antes querria que su
mujer fuesse la mas fea y
abominable del mundo, que no
que fuesse vista ni alabada por
los hombres, aunque sean
honestos y moderados. ¿Qué
fatiga es para lamujer ver su
honestidad agraviada con una
vana sospecha? ¿qué pena le es
estar sin razón en los más
secretos rincones encerrada?
¿qué dolor ser ordinariamente
con palabras pesadas, y aun á
veces con obras combatida? Si
ella está alegre, el marido la tiene
por deshonesta; siestá triste,
imagina que se enoja de verle; si
está pensando, la tiene por
sospechosa; si lemira, paresce
que le engaña; si no le mira,
piensa que le aborresce; si le
hace caricias, piensa que las
finge; si está grave y honesta,
cree que le desecha; si rie, la
tiene por desenvuelta; si suspira,
la tiene por mala, y en fin, en
cuántas cosas se meten estos
celos, las convierten en dolor,

aunque de suyo sean agradables.
Pordonde está muy claro que no
tiene el mundo pena que iguale
con esta, ni salieron del infierno
Harpías que más ensucien y
corrompan lossabrosos manjares
del alma enamorada. Pues no
tengas en poco, Diana, tener
ausente elceloso Delio, que no
importa poco para passar más
ligeramente las penas del Amor. A
esto Diana respondió: Yo vengo á
conoscer que esta passión, que
has tan al vivo dibujado, es
disforme y espantosa, y que no
meresce estar en los amorosos
ánimos, y creo que esta pena era
la que Delio tenía. Mas quiero que
sepas que semejante dolencia no
pretendí yo defenderla, ni jamás
estuvo en mí: pues nunca tuve
pesar del valor de Syreno, ni fuí
atormentada de semejantes
passiones y locuras, como las
que tú me has contado, mas sólo
tuve miedo de ser por otra
desechada. Y no me engañó de
mucho este recelo, pues he
probado tan á costa mía elolvido
de Syreno. Esse miedo, dijo
Marcelio ,no tiene nombre de
celos, antes es ordinario enlos
buenos amadores. Porque
averiguado estáque lo que yo
amo, lo estimo y tengo por bueno
y merescedor de tal amor, y
siendo ello tal, hede tener miedo

que otro no conozca su bondad y
merescimiento, y no lo ame como
yo. Y ansí el amador está metido
en medio del temor y la
esperanza. Lo que el uno le
niega, la otra se lopromete;
cuando el uno le acobarda, la otra
leesfuerza; y en fin las llagas que
hace el temor se curan con la
esperanza, durando esta reñida
pelea hasta que la una parte de
las dos queda vencida, y si
acontesce vencer el temor á la
esperanza, queda el amador
celoso, y si la esperanza vence al
temor, queda alegre y bien
afortunado. Mas yo en el tiempo
de mi ventura tuve siempre una
esperanza tan fuerte, que nosólo
el temor no la venció, pero nunca
osó acometella, y ansi recibía con
ella tan grandes gustos, que á
trueque dellos no me pesaba
recebir los continuos dolores; y fuí
tan agradescida á laque mi
esperanza en tanta firmeza
sostenía, que no había pena que
viniesse de su mano que nola
tuviesse por alegría. Sus
reproches tenía porfavores, sus
desdenes por caricias y sus
airadas respuestas por corteses
prometimientos.
Estas y otras razones passaron
Diana y Marcelio prosiguiendo su
camino. Acabado de travessar
aquel prado en muy dulce

conversación, ysubiendo una
pequeña cuesta, entraron por un
ameno bosquecillo, donde los
espessos alisos hacían muy
apacible sombrío. Allí sintieron
una suave voz que de una dulce
lira acompañada resonabacon
extraña melodía, y parándose á
escuchar,conocieron que era voz
de una pastoraque cantaba ansí:
Soneto.
Cuantas estrellas tieue el alto
cielo
fueron en ordenar mi
desventura,
y en la tierra no hay prado ni
verdura
que pueda en mi dolor
darme consuelo.
Amor subjecto al miedo, en
puro hielo
convierte el alma triste ¡ay,
pena dura!
que á quien fué tan contraria
la ventura,
vivir no puede un hora sin
recelo.
La culpa de mi pena es justo
darte
á ti, Montano, á ti mis quejas
digo,
alma cruel, do no hay
piedad alguna.
Porque si tú estuvieras de mi