100% нашли этот документ полезным (8 голосов)
67 просмотров

Full Download Learn Java Fundamentals A Primer for Java Development and Programming 1st Edition Jeff Friesen PDF DOCX

Java

Загружено:

timbmizta
Авторское право
© © All Rights Reserved
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
100% нашли этот документ полезным (8 голосов)
67 просмотров

Full Download Learn Java Fundamentals A Primer for Java Development and Programming 1st Edition Jeff Friesen PDF DOCX

Java

Загружено:

timbmizta
Авторское право
© © All Rights Reserved
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
Вы находитесь на странице: 1/ 75

Download the full version of the ebook at ebookfinal.

com

Learn Java Fundamentals A Primer for Java


Development and Programming 1st Edition Jeff
Friesen

https://ebookfinal.com/download/learn-java-fundamentals-a-
primer-for-java-development-and-programming-1st-edition-
jeff-friesen/

OR CLICK BUTTON

DOWNLOAD EBOOK

Download more ebook instantly today at https://ebookfinal.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Learn Java for Web Development Modern Java Web Development


1st Edition Vishal Layka

https://ebookfinal.com/download/learn-java-for-web-development-modern-
java-web-development-1st-edition-vishal-layka/

ebookfinal.com

Simply Java An Introduction to Java Programming


Programming Series 1st Edition James Levenick

https://ebookfinal.com/download/simply-java-an-introduction-to-java-
programming-programming-series-1st-edition-james-levenick/

ebookfinal.com

Java Programming Exercises Volume Two Java Standard


Library 1st Edition Christian Ullenboom

https://ebookfinal.com/download/java-programming-exercises-volume-two-
java-standard-library-1st-edition-christian-ullenboom/

ebookfinal.com

Learn Java In a Weekend 1st Edition Joseph P. Russell

https://ebookfinal.com/download/learn-java-in-a-weekend-1st-edition-
joseph-p-russell/

ebookfinal.com
Learn Objective C for Java Developers 1st Edition James
Bucanek (Auth.)

https://ebookfinal.com/download/learn-objective-c-for-java-
developers-1st-edition-james-bucanek-auth/

ebookfinal.com

Beginning Programming with Java For Dummies Third Edition


Barry Burd

https://ebookfinal.com/download/beginning-programming-with-java-for-
dummies-third-edition-barry-burd/

ebookfinal.com

Java Servlet Programming Second Edition Jason Hunter

https://ebookfinal.com/download/java-servlet-programming-second-
edition-jason-hunter/

ebookfinal.com

Object Oriented Programming and Java Second Edition Danny


Poo

https://ebookfinal.com/download/object-oriented-programming-and-java-
second-edition-danny-poo/

ebookfinal.com

Wireless Java Programming with J2ME 1st Edition Yu Feng

https://ebookfinal.com/download/wireless-java-programming-
with-j2me-1st-edition-yu-feng/

ebookfinal.com
Learn Java
Fundamentals
A Primer for Java Development and
Programming

Jef f F riesen
Learn Java Fundamentals
A Primer for Java Development
and Programming

Jeff Friesen
Learn Java Fundamentals: A Primer for Java Development and Programming
Jeff Friesen
Dauphin, MB, Canada

ISBN-13 (pbk): 979-8-8688-0350-5 ISBN-13 (electronic): 979-8-8688-0351-2


https://doi.org/10.1007/979-8-8688-0351-2
Copyright © 2024 by Jeff Friesen
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: James Robinson-Prior
Development Editor: James Markham
Coordinating Editor: Gryffin Winkler
Cover designed by eStudioCalamar
Photo by pariwat pannium on Unsplash
Distributed to the book trade worldwide by Apress Media, LLC, 1 New York Plaza, New York, NY 10004,
U.S.A. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.
springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science
+ Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected]; for reprint,
paperback, or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub (https://github.com/Apress). For more detailed information, please visit https://www.
apress.com/gp/services/source-code.
If disposing of this product, please recycle the paper
To my Lord and Savior, Jesus Christ
and
To the memories of my parents and my older sister
and
To my younger sister and her family.
Table of Contents
About the Author��������������������������������������������������������������������������������������������������� xiii

About the Technical Reviewer���������������������������������������������������������������������������������xv


Introduction�����������������������������������������������������������������������������������������������������������xvii

Chapter 1: Getting Started with Java����������������������������������������������������������������������� 1


What Is Java?�������������������������������������������������������������������������������������������������������������������������������� 1
Java Is a Programming Language������������������������������������������������������������������������������������������� 2
Java Is a Virtual Platform��������������������������������������������������������������������������������������������������������� 3
The Java Development Kit������������������������������������������������������������������������������������������������������������ 4
“hello, world” – Java Style������������������������������������������������������������������������������������������������������������ 6
Application Architecture�������������������������������������������������������������������������������������������������������������� 10
What’s Next?������������������������������������������������������������������������������������������������������������������������������� 12

Chapter 2: Comments, Identifiers, Types, Variables, and Literals��������������������������� 13


Comments����������������������������������������������������������������������������������������������������������������������������������� 13
Single-Line Comments���������������������������������������������������������������������������������������������������������� 14
Multiline Comments�������������������������������������������������������������������������������������������������������������� 14
Javadoc Comments��������������������������������������������������������������������������������������������������������������� 15
Identifiers������������������������������������������������������������������������������������������������������������������������������������ 18
Types������������������������������������������������������������������������������������������������������������������������������������������� 20
Primitive Types���������������������������������������������������������������������������������������������������������������������� 21
User-Defined Types���������������������������������������������������������������������������������������������������������������� 22
Variables������������������������������������������������������������������������������������������������������������������������������������� 24
Literals���������������������������������������������������������������������������������������������������������������������������������������� 26
Putting It All Together������������������������������������������������������������������������������������������������������������������ 28
What’s Next?������������������������������������������������������������������������������������������������������������������������� 30

v
Table of Contents

Chapter 3: Expressions������������������������������������������������������������������������������������������� 31
Introducing Expressions�������������������������������������������������������������������������������������������������������������� 31
Simple Expressions��������������������������������������������������������������������������������������������������������������������� 31
Compound Expressions��������������������������������������������������������������������������������������������������������������� 33
Operator Examples���������������������������������������������������������������������������������������������������������������� 36
Playing with Expressions������������������������������������������������������������������������������������������������������������ 54
What’s Next?������������������������������������������������������������������������������������������������������������������������������� 59

Chapter 4: Statements�������������������������������������������������������������������������������������������� 61
Introducing Statements�������������������������������������������������������������������������������������������������������������� 61
Assignment Statements�������������������������������������������������������������������������������������������������������������� 61
Simple-Assignment Statement���������������������������������������������������������������������������������������������� 61
Compound-Assignment Statement��������������������������������������������������������������������������������������� 62
Decision Statements������������������������������������������������������������������������������������������������������������������� 62
If Statement��������������������������������������������������������������������������������������������������������������������������� 62
If-Else Statement������������������������������������������������������������������������������������������������������������������� 63
Switch Statement������������������������������������������������������������������������������������������������������������������ 66
Loop Statements������������������������������������������������������������������������������������������������������������������������� 68
For Statement������������������������������������������������������������������������������������������������������������������������ 68
While Statement�������������������������������������������������������������������������������������������������������������������� 70
Do-While Statement�������������������������������������������������������������������������������������������������������������� 72
Loop-Branching Statements������������������������������������������������������������������������������������������������������� 73
Break Statement�������������������������������������������������������������������������������������������������������������������� 73
Continue Statement��������������������������������������������������������������������������������������������������������������� 75
Additional Statements����������������������������������������������������������������������������������������������������������������� 77
Assert Statement������������������������������������������������������������������������������������������������������������������� 77
Empty Statement������������������������������������������������������������������������������������������������������������������� 78
Import Statement������������������������������������������������������������������������������������������������������������������ 78
Method-Call Statement��������������������������������������������������������������������������������������������������������� 78
Package Statement��������������������������������������������������������������������������������������������������������������� 79
Return Statement������������������������������������������������������������������������������������������������������������������ 79

vi
Table of Contents

Try Statement������������������������������������������������������������������������������������������������������������������������ 79
Try-with-resources Statement���������������������������������������������������������������������������������������������� 79
Playing with Statements������������������������������������������������������������������������������������������������������������� 79
What’s Next?������������������������������������������������������������������������������������������������������������������������������� 84

Chapter 5: Arrays���������������������������������������������������������������������������������������������������� 85
Introducing Arrays����������������������������������������������������������������������������������������������������������������������� 85
One-Dimensional Arrays������������������������������������������������������������������������������������������������������������� 85
Creating a 1D Array��������������������������������������������������������������������������������������������������������������� 86
Accessing 1D Array Elements������������������������������������������������������������������������������������������������ 88
Searching and Sorting���������������������������������������������������������������������������������������������������������������� 89
Linear Search������������������������������������������������������������������������������������������������������������������������ 90
Binary Search������������������������������������������������������������������������������������������������������������������������ 91
Bubble Sort���������������������������������������������������������������������������������������������������������������������������� 94
Two-Dimensional Arrays������������������������������������������������������������������������������������������������������������� 96
Creating a 2D Array��������������������������������������������������������������������������������������������������������������� 96
Accessing 2D Array Elements������������������������������������������������������������������������������������������������ 98
Ragged Arrays��������������������������������������������������������������������������������������������������������������������� 100
Matrix Multiplication����������������������������������������������������������������������������������������������������������������� 102
What’s Next?����������������������������������������������������������������������������������������������������������������������������� 105

Chapter 6: Classes and Objects���������������������������������������������������������������������������� 107


Introducing Classes������������������������������������������������������������������������������������������������������������������� 107
Declaring Classes���������������������������������������������������������������������������������������������������������������� 107
Describing State via Fields�������������������������������������������������������������������������������������������������� 108
Describing Behaviors via Methods�������������������������������������������������������������������������������������� 109
Describing Initialization via Constructors���������������������������������������������������������������������������� 114
Putting It All Together���������������������������������������������������������������������������������������������������������� 117
Introducing Objects������������������������������������������������������������������������������������������������������������������� 119
Constructing Objects����������������������������������������������������������������������������������������������������������� 119
Accessing Fields������������������������������������������������������������������������������������������������������������������ 120
Calling Methods������������������������������������������������������������������������������������������������������������������� 120

vii
Table of Contents

Putting It All Together���������������������������������������������������������������������������������������������������������� 122


Additional Topics����������������������������������������������������������������������������������������������������������������������� 123
Information Hiding��������������������������������������������������������������������������������������������������������������� 123
Object Initialization�������������������������������������������������������������������������������������������������������������� 125
Utility Classes���������������������������������������������������������������������������������������������������������������������� 127
Class Initialization��������������������������������������������������������������������������������������������������������������� 130
Field-Access Rules�������������������������������������������������������������������������������������������������������������� 132
Method-Call Rules��������������������������������������������������������������������������������������������������������������� 133
Final Fields�������������������������������������������������������������������������������������������������������������������������� 133
Method-Call Chaining���������������������������������������������������������������������������������������������������������� 135
Recursion���������������������������������������������������������������������������������������������������������������������������� 138
Varargs�������������������������������������������������������������������������������������������������������������������������������� 139
What’s Next?����������������������������������������������������������������������������������������������������������������������������� 142

Chapter 7: Reusing Classes via Inheritance and Composition����������������������������� 143


Inheritance�������������������������������������������������������������������������������������������������������������������������������� 143
Class Extension������������������������������������������������������������������������������������������������������������������� 144
Method Overriding��������������������������������������������������������������������������������������������������������������� 149
The Ultimate Ancestor of All Classes����������������������������������������������������������������������������������� 154
Composition������������������������������������������������������������������������������������������������������������������������������ 187
The Trouble with Inheritance����������������������������������������������������������������������������������������������� 188
What’s Next?����������������������������������������������������������������������������������������������������������������������������� 194

Chapter 8: Changing Type via Polymorphism������������������������������������������������������� 195


Upcasting and Late Binding������������������������������������������������������������������������������������������������������ 197
Abstract Classes and Abstract Methods����������������������������������������������������������������������������������� 197
Interfaces���������������������������������������������������������������������������������������������������������������������������������� 200
Interface Declaration����������������������������������������������������������������������������������������������������������� 203
Implementing Interfaces����������������������������������������������������������������������������������������������������� 204
Extending Interfaces������������������������������������������������������������������������������������������������������������ 212
Downcasting and RTTI�������������������������������������������������������������������������������������������������������������� 220
Runtime Type Identification������������������������������������������������������������������������������������������������� 222

viii
Table of Contents

Additional Topics����������������������������������������������������������������������������������������������������������������������� 223


Covariant Return Types�������������������������������������������������������������������������������������������������������� 223
Interface-Based Static Methods������������������������������������������������������������������������������������������ 227
What’s Next?����������������������������������������������������������������������������������������������������������������������������� 229

Chapter 9: Static, Non-static, Local, and Anonymous Classes����������������������������� 231


Static Classes��������������������������������������������������������������������������������������������������������������������������� 232
A More Practical Static Class Example�������������������������������������������������������������������������������� 235
Inner Classes���������������������������������������������������������������������������������������������������������������������������� 241
Shadowing��������������������������������������������������������������������������������������������������������������������������� 244
A More Practical Inner Class Example��������������������������������������������������������������������������������� 246
Local Classes���������������������������������������������������������������������������������������������������������������������������� 250
A More Practical Local Class Example�������������������������������������������������������������������������������� 255
Anonymous Classes������������������������������������������������������������������������������������������������������������������ 261
Summarizing����������������������������������������������������������������������������������������������������������������������� 265
A More Practical Anonymous Class Example���������������������������������������������������������������������� 266
What’s Next?����������������������������������������������������������������������������������������������������������������������������� 270

Chapter 10: Packages������������������������������������������������������������������������������������������� 271


What Are Packages?����������������������������������������������������������������������������������������������������������������� 271
The Package Statement������������������������������������������������������������������������������������������������������������ 272
The Import Statement��������������������������������������������������������������������������������������������������������������� 273
Playing with Packages�������������������������������������������������������������������������������������������������������������� 275
Packaging a Logging Library����������������������������������������������������������������������������������������������� 275
Importing Types from the Logging Library��������������������������������������������������������������������������� 280
Additional Topics����������������������������������������������������������������������������������������������������������������������� 283
Static Imports���������������������������������������������������������������������������������������������������������������������� 283
Protected Access����������������������������������������������������������������������������������������������������������������� 286
JAR Files������������������������������������������������������������������������������������������������������������������������������ 287
What’s Next?����������������������������������������������������������������������������������������������������������������������������� 288

ix
Table of Contents

Chapter 11: Exceptions and Errors����������������������������������������������������������������������� 289


What Are Exceptions and Errors?���������������������������������������������������������������������������������������������� 290
Representing Exceptions and Errors in Source Code���������������������������������������������������������������� 291
Error Codes vs. Objects������������������������������������������������������������������������������������������������������� 291
The Throwable Class Hierarchy������������������������������������������������������������������������������������������� 293
Throwing Exceptions����������������������������������������������������������������������������������������������������������������� 296
The Throw Statement���������������������������������������������������������������������������������������������������������� 296
The Throws Clause�������������������������������������������������������������������������������������������������������������� 297
The Try Statement��������������������������������������������������������������������������������������������������������������������� 299
The Try Block����������������������������������������������������������������������������������������������������������������������� 299
Catch Blocks������������������������������������������������������������������������������������������������������������������������ 301
The Finally Block����������������������������������������������������������������������������������������������������������������� 303
The Try-with-resources Statement������������������������������������������������������������������������������������������� 308
What’s Next?����������������������������������������������������������������������������������������������������������������������������� 310

Chapter 12: Math, BigDecimal, and BigInteger����������������������������������������������������� 311


Math������������������������������������������������������������������������������������������������������������������������������������������ 311
Math Constants������������������������������������������������������������������������������������������������������������������� 312
Trigonometric Methods�������������������������������������������������������������������������������������������������������� 313
Random Number Generation����������������������������������������������������������������������������������������������� 316
BigDecimal�������������������������������������������������������������������������������������������������������������������������������� 320
BigInteger��������������������������������������������������������������������������������������������������������������������������������� 323
What’s Next?����������������������������������������������������������������������������������������������������������������������������� 324

Chapter 13: String and StringBuffer��������������������������������������������������������������������� 325


String���������������������������������������������������������������������������������������������������������������������������������������� 325
Creating Strings������������������������������������������������������������������������������������������������������������������� 325
Comparing Strings��������������������������������������������������������������������������������������������������������������� 326
Concatenating Strings��������������������������������������������������������������������������������������������������������� 327
Exploring String Methods���������������������������������������������������������������������������������������������������� 327
Immutability and Interning�������������������������������������������������������������������������������������������������� 331
Word Counting��������������������������������������������������������������������������������������������������������������������� 333

x
Table of Contents

StringBuffer������������������������������������������������������������������������������������������������������������������������������� 335
Creating String Buffers�������������������������������������������������������������������������������������������������������� 335
Exploring StringBuffer Methods������������������������������������������������������������������������������������������ 336
Text Reversal����������������������������������������������������������������������������������������������������������������������� 341
What’s Next?����������������������������������������������������������������������������������������������������������������������������� 342

Chapter 14: System���������������������������������������������������������������������������������������������� 343


Array Copying���������������������������������������������������������������������������������������������������������������������������� 343
Current Time and Nano Time����������������������������������������������������������������������������������������������������� 346
Garbage Collection�������������������������������������������������������������������������������������������������������������������� 351
Line Separator��������������������������������������������������������������������������������������������������������������������������� 354
Standard I/O������������������������������������������������������������������������������������������������������������������������������ 355
Standard Input��������������������������������������������������������������������������������������������������������������������� 356
Standard Output������������������������������������������������������������������������������������������������������������������ 357
Standard Error��������������������������������������������������������������������������������������������������������������������� 361
System Properties��������������������������������������������������������������������������������������������������������������������� 362
The Properties Class������������������������������������������������������������������������������������������������������������ 367
Virtual Machine Shutdown�������������������������������������������������������������������������������������������������������� 370
What’s Next?����������������������������������������������������������������������������������������������������������������������������� 371

Appendix A: Reserved Words Quick Reference����������������������������������������������������� 373

Appendix B: Operators Quick Reference��������������������������������������������������������������� 375

Index��������������������������������������������������������������������������������������������������������������������� 379

xi
About the Author
Jeff Friesen is a freelance teacher and software developer
with an emphasis on Java. In addition to authoring several
books on Java and Android for Apress such as Java I/O,
NIO and NIO.2 and Java XML and JSON, Jeff has written
numerous articles on Java and other technologies for
JavaWorld (now known as InfoWorld), InformIT, Java.net,
SitePoint, and other websites.

xiii
About the Technical Reviewer
Massimo Nardone is a seasoned cyber, information, and
operational technology (OT) security professional with
28 years of experience working with companies such as
IBM, HP, and Cognizant, with IT, OT, IoT, and IIoT security
roles and responsibilities including CISO, BISO, IT/OT/IoT
Security Architect, Security Assessor/Auditor, PCI QSA, and
ICS/SCADA Expert. He is the founder of Massimo Security
Services, a company providing IT-OT-IoT security consulting
services, and member of ISACA, ISF, Nordic CISO Forum,
and Android Global Forum and owns four international
patents. He is coauthor of five Apress IT books.

xv
Introduction
Java is a popular programming language and environment. Because it is used in the
Information Technology departments of many companies, learning Java is a great way to
boost your career (and earn more money in these difficult financial times).
If you have never worked with Java, this 14-chapter book is for you. Chapter 1 starts
you on a gentle journey to learn Java fundamentals.
Chapters 2 through 11 focus mainly on language syntax, although a few APIs that are
closely related to syntax are also presented.
Chapter 2 focuses on comments, identifiers, types, variables, and literals. These
features are fundamental to many languages, and this chapter also shows you where Java
differs from other languages in their implementation.
Chapter 3 focuses on expressions (and operators), and Chapter 4 focuses on
statements. Again, these features are found in many languages. You will use these
building blocks to construct simple Java programs and will learn where Java’s
implementations of expressions (and operators) and statements diverge from other
languages.
Chapter 5 focuses on arrays. You will use this fundamental data structure to create
programs that work with sequences of data items. For example, you might want to search
a sequence of employee IDs for a specific identifier.
If this was all that Java had to offer, you would be able to create sophisticated
structured programs. In a structured program, data and operations that manipulate the
data are separated. However, Java goes beyond its ability to create structured programs,
as revealed in Chapters 6 through 8.
Chapter 6 introduces you to classes and objects. A class is a template from
which objects are manufactured. It provides an architecture for structuring data and
associating that data with code that manipulates the data. An object is an instance of a
class (kind of like a cookie is an instance of a cookie cutter). It stores data that can be
manipulated by the code that the object receives from its class. (Don’t worry if this seems
complicated. After reading Chapter 6, you’ll have a much better understanding.)
Java and other languages that support classes and objects are known as object-
based languages. To go beyond object based and become an object-oriented language,

xvii
Introduction

a language must also support inheritance. Java supports inheritance, which you’ll learn
about in Chapter 7.
Programs can be made more efficient through polymorphism, which is based on
inheritance. The idea behind polymorphism is that a single symbol can represent many
different types (e.g., the + symbol can represent integer addition, floating-point addition,
or string concatenation). You’ll learn about polymorphism in Chapter 8.
There are a few more language features that you need to learn about before you can
tour Java’s many APIs. Chapter 9 begins by introducing you to static, non-static, local,
and anonymous classes. These features let you logically organize your code, making it
more readable and maintainable.
Packages let you organize related classes in the equivalent of a file folder. This feature
helps you avoid name conflicts by organizing a library of classes under a single prefix.
Check out Chapter 10 to learn about packages.
Java provides a robust exception-handling mechanism for dealing with flawed
code or unexpected difficulties, such as attempting to open a nonexistent file. This
mechanism is covered in Chapter 11.
The final three chapters tour some fundamental APIs that you’ll use in many Java
programs. Chapter 12 focuses on the Math class and related types, Chapter 13 focuses
on String and StringBuffer, and Chapter 14 focuses on System. After you explore
these types, you’ll be able to explore additional APIs on your own to increase your Java
knowledge.
Two appendixes round out this book. Appendix A provides a quick reference to
Java’s supported reserved words, and Appendix B provides a quick reference to Java’s
supported operators.

xviii
CHAPTER 1

Getting Started with Java


Welcome to Java. This technology is widely used in the business world, and you
probably want to learn it quickly so you can capture a job in one of these companies
as a Java programmer. Although Java is vast and constantly evolving, there are various
fundamental features that are timeless and easy to understand. After you master these
fundamentals, you will have an easier time writing Java programs.
This chapter launches you on a tour of Java’s fundamental features. You first receive
an answer to the “What is Java?” question. Next, you learn about the Java Development
Kit, which is the necessary software for developing Java programs on your computer.
Moving on, you are introduced to your first Java program, which outputs a simple “hello,
world” message. Finally, you discover application architecture.

Note A program is a sequence of instructions for a computer to execute. An


application is a program with a single entry point of execution. (In contrast, an
applet – an old form of Java program that is no longer widely used – has multiple
entry points.) For example, a Microsoft Windows program that is stored in an
.exe file has a single entry point. When expressed in C language source code
(textual instructions), the entry point is defined by a function (a named sequence of
instructions) with the name main.

What Is Java?
Java is like a two-sided coin. From one side, it’s a computer programming language.
Conversely, it’s a virtual platform (the hardware and software context in which a
program runs) for running programs written in that language.

1
© Jeff Friesen 2024
J. Friesen, Learn Java Fundamentals, https://doi.org/10.1007/979-8-8688-0351-2_1
Chapter 1 Getting Started with Java

Note Java has an interesting history. Check out Wikipedia’s “Java (programming
language)” (http://en.wikipedia.org/wiki/Java_(programming_
language)#History) and “Java (software platform)” (http://en.wikipedia.
org/wiki/Java_ (software_platform)#History) entries to learn more.

Java Is a Programming Language


Java is a programming language with many features that are identical to those found
in the C and C++ languages. This is no accident. One of Java’s initial goals was to make
it easy for C/C++ programmers to migrate to Java to quickly build up an initial pool of
programmers that would help Java become successful.
You will discover several similarities between these languages:

• The same single-line and multiline comments for documenting


source code are found in Java and C/C++.

• Various identical reserved words are found in Java and C/C++, such
as if, while, for, and switch. Various other reserved words are found in
Java and C++ but not in C, such as try, catch, class, and public.

• Primitive types are shared between the three languages: character


and integer are examples. Furthermore, reserved words for these
types are shared between these languages: char and int are examples.

• Many of the same operators are shared between Java and C/C++.
Arithmetic operators (such as * and +) and relational operators
(such as == and <=) are examples.

• Finally, Java and C/C++ use brace characters ({ and }) to delimit


blocks of statements.

Java also differs from C/C++ in many ways. Here are a few of the many differences:

• Java supports an additional comment style for documenting source


code. This comment style is known as Javadoc.

• Java provides reserved words that are not found in C/C++. Examples
include strictfp and transient.

2
Chapter 1 Getting Started with Java

• Java’s character type is larger than the character type in C and C++.
In those languages, a character occupies one byte of memory. In
contrast, Java’s character type occupies two bytes.

• Java doesn’t support all of C/C++’s operators. For example, you won’t
find the C/C++ sizeof operator in Java. Also, the >>> (unsigned right
shift) operator is exclusive to Java.

• Java provides labeled break and continue statements. These variants


of their C/C++ counterparts, which don’t accept labels, are a safer
alternative to C/C++’s goto statement, which Java doesn’t support.

I discuss comments, reserved words, types, operators, and statements later in


this book.
The Java programming language is rigorously defined by various rules that describe
its syntax (structure) and semantics (meaning). These rules are used by a compiler to
verify correctness when translating a program’s source code into equivalent bytecode,
which is a portable representation of the program’s executable code. This bytecode is
stored in one or more class files, which are the Java equivalent of a Windows program’s
executable (.exe) file.

Java Is a Virtual Platform


Java is a virtual platform that executes Java programs. Unlike real platforms that consist
of a microprocessor (such as an Intel or AMD processor) and operating system (such as
Windows 11), the Java platform consists of virtual machine and execution environment
software.
A virtual machine is a software-based processor with its own set of instructions.
The Java Virtual Machine’s (JVM) associated execution environment consists of a huge
library of prebuilt reference types (think Application Program Interfaces [APIs]) that
Java programs can use to perform routine tasks (such as opening a file). The execution
environment also contains “glue” code that connects the JVM to the underlying
operating system via the Java Native Interface. (I don’t discuss the Java Native Interface
in this book because I don’t consider it to be a fundamental feature.)

3
Chapter 1 Getting Started with Java

Note The combination of bytecode and the virtual machine makes it possible to


achieve portability: the same Java program runs on all platforms that support the
virtual machine. It’s not necessary to recompile the program’s source code for each
platform.

A Java program is run by a special executable, which I call the program launcher.
Because a program consists of one or more class files, the launcher receives the name
of the main class file (the class file where execution begins). After loading the JVM into
memory, it tells the JVM to use its class loader component to load the main class file
into memory. The JVM then verifies that the class file’s bytecode is safe to run (e.g., no
viruses) and runs it.

Note The verifier and a security manager architecture make it possible to


achieve security: a Java application will not be allowed to run when the verifier
detects corrupt bytecode. Furthermore, when a security manager is installed, the
application won’t be able to steal sensitive information, erase files, or otherwise
harm a user’s computer.

During execution, a class file might refer to another class file. When this happens, the
JVM uses the class loader to load the referenced class file into memory and then verifies
and (if okay to run) executes that class file’s bytecode.

The Java Development Kit


The Java Development Kit (JDK) provides the necessary software for creating Java
applications, which are a category of Java programs with a single entry point of
execution. They contrast with Java applets, another category of Java programs that run
embedded in web pages. Applets are rarely used these days.
Follow these steps to download the JDK:
1. Enter www.oracle.com/java/technologies/ in your browser. This
takes you to the main page of Oracle’s Java site.

4
Chapter 1 Getting Started with Java

2. At the time of writing, the newest download is version 21.0.1.


Click on the Java SE 21.0.1 link. (Java SE stands for Java Standard
Edition. This is the foundation on which other editions are based
and is the appropriate edition for this book. Another edition is
Java EE, for Java Enterprise Edition. You would use this edition
when developing complex business solutions involving web
servers, database management systems, and client computers.)

3. In the JDK Development Kit 21.0.1 downloads section of the


resulting Java Downloads page, you will see Linux, macOS,
and Windows tabs. The JDK is available for all three operating
systems. Choose whichever one is right for you. For example, I
clicked the Windows tab because I was running Windows. I then
had a choice between different kinds of installers. I chose the x64
installer whose file name ends with a .exe file extension. I found
this the easiest way to install the JDK.

Once you download the installer, such as jdk-21_windows-x64_bin.exe, run this


program and follow the onscreen prompts to install the JDK.
The JDK contains various tools for use in application development. Four of these
tools are the Java compiler (javac.exe in the Windows download), the Java program
launcher (java.exe in the Windows download), the Java documentation generator
(javadoc.exe in the Windows download), and the Java archiver (jar.exe in the
Windows download). You will only need to work with these tools in this book.
The JDK’s compiler, program launcher, documentation generator, archiver, and other
tools are designed to be run from the command line within the context of a console (an
operating system–specific construct consisting of a window for viewing output and a
command line for obtaining command-based input). To obtain a console on Windows
operating systems, perform the following tasks:

1. Go to the Start menu and select Run.

2. In the Run dialog box, enter cmd in the text field and click the OK
button. On the Windows operating system, you should observe a
window similar to that shown in Figure 1-1.

5
Chapter 1 Getting Started with Java

Figure 1-1. The upper portion of a console as seen on a Windows 8.1 machine

Figure 1-1 reveals C:\Users\jeffrey>, which is a prompt for entering a command


on my Windows 8.1 machine. The rectangular box to the right of > is the cursor, which
indicates the current position for entering text on the command line.

“hello, world” – Java Style


Let’s create a simple application to get a taste of Java code. Traditionally, the first
application does nothing but output the message hello, world on the console.
Listing 1-1 presents the source code to a HelloWorld application that does just that.

Listing 1-1. HelloWorld.java

class HelloWorld
{
   public static void main(String[] args)
   {
      System.out.println("hello, world");
   }
}

Listing 1-1 declares a HelloWorld class (I explain classes in Chapter 6) that serves as
a placeholder for the main() method (a named sequence of instructions that executes in
the context of a class).

Note Languages such as C use functions instead of methods. A function is a


named sequence of instructions that executes outside of any context.

6
Chapter 1 Getting Started with Java

The main() method serves as the entry point to the application. When the
application runs, main()’s code is executed.
The main() method header (public static void main(String[] args)) exhibits
some interesting features:

• The method is marked public so that the Java program launcher


can locate it. If public is absent, an error message is output when
attempting to run the application.

• The method is marked static so that a HelloWorld object does not


need to be created in order to call main(). The launcher calls main()
directly. It knows nothing of objects. If static is absent, an error
message is output when attempting to run the application.

• The method is declared with a parameter list consisting of String[]


args, which identifies an array of string arguments that are passed
after the application’s name (HelloWorld) on the command line
when the application is run by the launcher. A string is a sequence of
characters placed between double quotes (").

• The method is declared with a void return type that signifies the
method returns nothing.

Don’t worry if concepts such as return type and parameter list are confusing. You’ll
learn about these concepts later in this book.
The main() method executes System.out.println("hello, world"); to output
hello, world on the console’s window. I explore System.out and its System.err and
System.in counterparts in Chapter 14.

INDENTATION, OPEN BRACE CHARACTER PLACEMENT, AND CODE-SEPARATION STYLES

Programmers often follow one style when indenting source code, another style when
positioning a block’s open brace character, and a third style when using blank lines to separate
segments of source code. (I briefly discuss blocks, which are sequences of code surrounded
by { and } characters, in Chapter 4.)
Listing 1-1 demonstrates the first two style categories. It shows my tendency to indent, by
three spaces, all lines in a block. I find that doing so makes it easier to follow the organization
of my source code when updating it as requirements change.

7
Chapter 1 Getting Started with Java

Also, Listing 1-1 shows my tendency to align the open ({) and close (}) brace characters, so
I can more easily locate the start and end of a block. Many programmers prefer the following
brace character alignment instead:

class HelloWorld {
   public static void main(String[] args) {
      System.out.println("hello, world");
   }
}

Another style issue involves inserting blank lines to separate segments of code, where each
segment consists of statements that work collectively on some aspect of the program. Here is
a contrived example, involving a pair of classes, A and B:

class A
{
   void method1()
   {
      for (int i = 0; i < 10; i++)
         System.out.println(i);

      while (true)
      {
         // ... do something here
      }
   }

   void method2()
   {
      for (int i = 0; i < 10; i++)
         System.out.println(i);

      while (true)
      {
         // ... do something here
      }
   }
}

8
Chapter 1 Getting Started with Java

class B
{
   void method1()
   {
      for (int i = 0; i < 10; i++)
         System.out.println(i);
      while (true)
      {
         // ... do something here
      }
   }
   void method2()
   {
      for (int i = 0; i < 10; i++)
         System.out.println(i);
      while (true)
      {
         // ... do something here
      }
   }
}

Each of classes A and B declares two methods: method1() and method2(). Furthermore,
each of method1() and method2() declares a for statement followed by a while
statement.

Don’t worry about classes, methods, and statements. I cover classes and methods in
Chapter 6 and cover statements in Chapter 4.

For now, pay attention to the blank line styles in each of A and B. A’s style is to place a blank
line between each method and between each group of related statements. B’s style is to
eliminate the blank line from between the methods and from between the statements.

Form your own styles for indentation, brace character placement, and code separation.
Although these styles don’t impact the generated code, adhering to them religiously sets you
apart from other programmers and can make your source code easier to read and maintain.
I tend to vary my code-separation style, which you’ll discover throughout this book’s code
listings.

9
Chapter 1 Getting Started with Java

Compile the source code as follows (you must include the .java file extension):

javac HelloWorld.java

If everything goes well, you should observe a HelloWorld.class file in the current
directory.
Now, execute the following command to run HelloWorld.class (you must not
include the .class file extension):

java HelloWorld

If all goes well, you should observe the following output:

hello, world

Congratulations! You’ve just run your first Java application. You should feel proud.

Application Architecture
An application consists of at least one class, and this class must declare a main() entry-
point method, as you saw in Listing 1-1. However, many applications will consist of
multiple classes. All of these classes might be declared in a single source file, or each
class might be declared in its own source file. Consider Listing 1-2.

Listing 1-2. Classes.java

class A
{
   static void a()
   {
       System.out.println("a() called");
   }
}

class B
{
   static void b()

10
Chapter 1 Getting Started with Java

   {
       System.out.println("b() called");
   }
}

class C
{
   public static void main(String[] args)
   {
      A.a();
      B.b();
   }
}

Listing 1-2 declares three classes (A, B, and C) in the same source file – Classes.java.
Class C is the entry-point class because it declares the main() method.
Compile Classes.java as follows:

javac Classes.java

You should observe A.class, B.class, and C.class class files in the current
directory.
Run this application as follows:

java C

You should observe the following output:

a() called
b() called

If you try to execute A (java A) or B (java B), you’ll discover an error message
because neither class declares the main() entry-point method.
This brings up an interesting point. You could declare main() methods in A and B
and run these classes as applications. However, this could get confusing.
You might want to declare a main() method in each of A and B to test these classes,
but there’s probably no other good reason to do so. It’s best to avoid confusion by
declaring main() in the entry-point class only.

11
Chapter 1 Getting Started with Java

What’s Next?
Now that you’ve had a taste of Java, it’s time to build on that knowledge by exploring
language features. Chapter 2 begins this process by focusing on the most basic language
features: comments, identifiers (and reserved words), types, variables, and literals.

12
CHAPTER 2

Comments, Identifiers,
Types, Variables,
and Literals
When learning a new programming language, starting with the most basic of language
features is best. These features are comments, identifiers (with reserved words as a
subset), types, variables, and literals. This chapter introduces you to these features in a
Java context.

Comments
It’s important to document your source code so that you and anyone else who might
maintain it in the future can understand the code’s purpose. Our brains tend to forget
things as we age, and we may not understand why we wrote the code the way we did.
Source code should be documented when it is written. This documentation might have
to be modified whenever the code is changed so that it accurately explains the new code.
Java provides comments for documenting source code. Whenever you compile the
source code, the compiler ignores the comments – no bytecode is generated. Single-line,
multiline, and Javadoc (documentation) comments are supported.

13
© Jeff Friesen 2024
J. Friesen, Learn Java Fundamentals, https://doi.org/10.1007/979-8-8688-0351-2_2
Chapter 2 Comments, Identifiers, Types, Variables, and Literals

Single-Line Comments
A single-line comment appears on one line of source code. It begins with the // character
sequence and continues to the end of the line. The compiler ignores everything on this
line starting with the // characters. The following example demonstrates a single-line
comment:

double degrees = (5.0 / 9.0) * (x - 32.0); // Convert x degrees Fahrenheit


to Celsius.

Single-line comments are useful for specifying short but meaningful information.
They shouldn’t be used to insert unhelpful information, for example, // This is a
comment.

Multiline Comments
A multiline comment typically extends over multiple lines of source code although
it can appear on a single line. This comment begins with /* and ends with */. The
compiler ignores everything in between (including /* and */). The following example
demonstrates a multiline comment:

/* Extract both components of an email address into a two-element array.


   email_parts[0] stores "xyz" and email_parts[1] stores "gmail.com". */
String[] email_parts = "[email protected]".split("@", 2); // extract

You cannot nest a multiline comment inside of another multiline comment. For
example, the compiler generates an error when it encounters the following nested
comments:

/*
  /*
    Nested multiline comments are illegal.
  */
*/

Caution The compiler reports an error when it encounters nested multiline


comments.

14
Chapter 2 Comments, Identifiers, Types, Variables, and Literals

Javadoc Comments
A Javadoc comment is a variation of the multiline comment. It begins with /** (instead
of /*) and (like a multiline comment) ends with */. All characters from /** through */
are ignored by the compiler. The following example presents a Javadoc comment:

/**
*  Application entry point
*
*  @param args array of command-line arguments passed to this method
*/
public static void main(String[] args)
{
   // TODO code application logic here
}

This example’s Javadoc comment describes an application’s main() method.


Sandwiched between /** and */ is a description of the method and the @param Javadoc
tag (an @-prefixed instruction to the javadoc tool).
Here is a list of some commonly used Javadoc tags (including @param):

• @author identifies the source code’s author.

• @deprecated identifies a source code entity (such as a method) that


should no longer be used.

• @param identifies one of a method’s parameters.

• @see provides a see-also reference.

• @since identifies the software release where the entity first


originated.

• @return identifies the kind of value that the method returns.

• @throws documents an exception thrown from a method.

Listing 2-1 presents updated source code to Listing 1-1’s HelloWorld application.
This source code includes a pair of Javadoc comments that document the HelloWorld
class and its main() entry-point method.

15
Chapter 2 Comments, Identifiers, Types, Variables, and Literals

Listing 2-1. HelloWorld.java

/**
   A simple class for introducing Java applications.

   @author Jeff Friesen


*/

public class HelloWorld


{
   /**
      Application entry point

      @param args array of command-line arguments passed to this method


   */

   public static void main(String[] args)


   {
      System.out.println("hello, world");
   }
}

Apart from the Javadoc comments, Listing 2-1 differs from Listing 1-1 in that it
prefixes class HelloWorld with the public keyword, which makes HelloWorld accessible
outside of its package. (I will discuss public in Chapter 6 and packages in Chapter 10.)
I use the javadoc tool to generate HTML-based documentation for HelloWorld.
java. This tool requires that the public keyword be prefixed to the HelloWorld class.
Furthermore, the .java file extension is required:

javadoc HelloWorld.java

In response, javadoc generates the following output:

Loading source file HelloWorld.java...


Constructing Javadoc information...
Building index for all the packages and classes...
Standard Doclet version 20.0.1+9-29
Building tree for all the packages and classes...
Generating .\HelloWorld.html...

16
Chapter 2 Comments, Identifiers, Types, Variables, and Literals

HelloWorld.java:7: warning: use of default constructor, which does not


provide a comment
public class HelloWorld
       ^
Generating .\package-summary.html...
Generating .\package-tree.html...
Generating .\overview-tree.html...
Building index for all classes...
Generating .\allclasses-index.html...
Generating .\allpackages-index.html...
Generating .\index-all.html...
Generating .\search.html...
Generating .\index.html...
Generating .\help-doc.html...
1 warning

The warning message refers to an undocumented default constructor. Constructors


are used to initialize objects when they are created. I discuss constructors, objects, and
the creation of objects in Chapter 6.
I’ve created a second version of HelloWorld.java that includes a commented
constructor. You can find this file in this book’s code archive. Instructions for obtaining
the code archive are provided in the book’s introduction.
The generated documentation includes an index file (index.html) that describes the
documentation’s start page. Figure 2-1 shows the start page for HelloWorld.java.

17
Chapter 2 Comments, Identifiers, Types, Variables, and Literals

Figure 2-1. The javadoc-generated documentation for HelloWorld.java

The javadoc tool was also used to generate the documentation for JDK 21’s reference
type library. This documentation’s start page is located at http://docs.oracle.com/en/
java/javase/21/docs/api/index.html. Figure 2-2 shows you part of this start page.

Figure 2-2. The javadoc-generated documentation for JDK 21’s reference


type library

Identifiers
Variables, statements, classes, and other language features need to be named to be
referenced from elsewhere in the code. Java supports this capability through identifiers.

18
Chapter 2 Comments, Identifiers, Types, Variables, and Literals

An identifier is a sequence of letters (A–Z, a–z, or equivalent uppercase/lowercase


letters in other human alphabets), digits (0–9 or equivalent digits in other human
alphabets), connecting punctuation characters such as the underscore, and currency
symbols (e.g., the $ sign). It must begin with a letter, a currency symbol, or a connecting
punctuation character. Its length cannot exceed the line in which it appears.

Note According to page 28 of the “Java Language Specification” for JDK 21


(http://docs.oracle.com/javase/specs/jls/se21/jls21.pdf), “the
dollar sign [$] should be used only in mechanically generated source code or,
rarely, to access pre-existing names on legacy systems.”

Examples of valid identifiers include i, grade_letter, counter10, and


degreesCelsius. Examples of invalid identifiers include 6Age (starts with a digit) and
last#Name (# is not a valid identifier symbol).

Note Java is a case-sensitive language. This means that identifiers differing in


case are considered different identifiers. For example, age and Age are different
identifiers.

Almost any valid identifier can be used to name a language feature. However, some
identifiers are reserved for special use by Java. These reserved identifiers are known as
reserved words. Figure 2-3 reveals Java’s 53 reserved words.

Figure 2-3. Java-reserved identifiers

19
Chapter 2 Comments, Identifiers, Types, Variables, and Literals

JDK 9 added a single underscore character (_) to Java’s list of reserved words. It’s an
error to use a single underscore to name anything. However, it’s okay to use multiple
underscores (although you probably shouldn’t).

Note Most of Java’s reserved words are also known as keywords. The three
exceptions are false, null, and true. They are examples of literals (values
expressed verbatim).
Also, const and goto are reserved by Java but are not used.

Types
Computers process different types of data: integers, characters, floating-point values,
Boolean true/false values, strings of characters, and so on. Java associates a type with
each data category.
A type identifies a set of values (and their representation in memory) and a set of
operations that transform these values into other values of that set. For example, the
floating-point type identifies numeric values with fractional parts and floating-point-
oriented math operations, such as adding two floating-point values to produce another
floating-point value that represents their sum.

Note Java is a strongly typed language. Every expression, variable, and so on


has a type known to the compiler. This capability helps the compiler detect type-
related errors at compile time rather than having these errors manifest themselves
at runtime. Expressions are discussed in Chapter 3. Variables are discussed later in
this chapter.

Java supports primitive types, user-defined types, and array types. I discuss primitive
and user-defined types here. I discuss array types in Chapter 5.

20
Chapter 2 Comments, Identifiers, Types, Variables, and Literals

Primitive Types
A primitive type (also known as a value type) is a basic type from which user-defined
types (discussed later in this chapter) are built. It identifies a set of values (such as
integers) and operations (such as addition) that are performed on these values. These
operations are built into the Java Virtual Machine (JVM).
More specifically, a primitive type consists of a reserved word that describes the
memory organization of an instance of this type. The reserved word also implies the
operations that can be performed on this type. For example, the Boolean primitive type
consists of reserved word boolean and implies operations such as logical negation (!),
which converts from true to false and false to true.
Java supports the Boolean, character, byte integer, short integer, integer, long integer,
floating-point, and double-precision floating-point primitive types. They are described
in Table 2-1.

Table 2-1. Java’s Primitive Types


Primitive Type Reserved Word Size Min Value Max Value

Boolean boolean -- -- --
Character char 16-bit Unicode 0 Unicode 216 - 1
Byte integer byte 8-bit -128 +127
Short integer short 16-bit -32768 +32767
Integer int 32-bit -231 +231 - 1
Long integer long 64-bit -263 +263 - 1
Floating-point float 32-bit IEEE 754 IEEE 754
Double-precision floating-point double 64-bit IEEE 754 IEEE 754

Table 2-1 describes each primitive type in terms of its reserved word, size, minimum
value, and maximum value. A -- entry indicates that the column in which it appears does
not apply to the primitive type described in the entry’s row.
The size column identifies the number of bits required to hold a value. Except for
Boolean, whose size is JVM dependent, each type’s implementation has a specific size.

21
Chapter 2 Comments, Identifiers, Types, Variables, and Literals

The minimum and maximum size columns identify the smallest and largest values
that the type represents. Besides Boolean, which has only true and false values, each
type has minimum and maximum values.
The character type’s minimum and maximum values refer to Unicode, a standard for
consistently encoding, representing, and handling text expressed in most of the world’s
writing systems (see http://en.wikipedia.org/wiki/Unicode for more information).

Note The character type is unsigned, which its limits suggest (the smallest value
is 0). In contrast, the byte integer, short integer, integer, and long integer types
are signed.

The minimum and maximum values for the four integer types reveal one more
negative value than positive value (0 is usually not regarded as positive). This
imbalance has to do with how integers are represented in two’s-complement (http://
en.wikipedia.org/wiki/Two's_complement) format. In contrast, the minimum and
maximum values for the floating-point types are defined by the IEEE 754 (http://
en.wikipedia.org/wiki/IEEE_754) specification.

User-Defined Types
A user-defined type is a combination of primitive types and user-defined types. For
example, a user-defined type for representing the concept of man might combine a user-
defined, string-based name along with a primitive integer-based age. The following code
fragment shows how you would specify man as a user-defined type:

class Man
{
   // implementation of the structure for representing a set of Man values

   String name;
   int age;

   // implementation of the operations that are performed on these values

22
Chapter 2 Comments, Identifiers, Types, Variables, and Literals

   int getName()
   {
      return name;
   }

   void setName(String name_)


   {
      return name = name_;
   }

   int getAge()
   {
      return age;
   }

   void setAge(int age_)


   {
      return age = age_;
   }
}

The class reserved word introduces Man as a user-defined type. It is conventional to


begin the name of a user-defined type with a capital letter.
The class’s body describes Man’s implementation in terms of the structure for
implementing Man values and the operations that are performed on these values.
The structure is comprised of two fields (variables that store a class type’s values – see
Chapter 6 for an introduction to fields). Man stores its values in name and age fields:

• name stores a man’s name. This field’s type is String, which is a


special user-defined type that represents a string (a sequence of
characters placed between double quotes ["]). JDK 21’s reference
type library includes the pre-created String type. (I discuss String in
Chapter 13.)

• age stores a man’s age. This field’s type is int, which is a primitive
type that represents a 32-bit integer.

23
Chapter 2 Comments, Identifiers, Types, Variables, and Literals

The operations consist of four methods (functions that execute in the context
of a class – see Chapter 6 for an introduction to methods). Man provides get and set
operations:

• get returns a Man value by retrieving the values of its name and age
fields. It provides getName() and getAge() methods for this purpose.

• set changes a Man value by changing the values of its name and age
fields. It provides setName() and setAge() methods for this purpose.

User-defined types are also known as reference types because a variable (discussed
shortly) whose type is user defined stores a reference (a memory address or other
location identifier) to a value of that type. In contrast, a variable of a primitive type stores
the type’s value instead of a reference to a value.

Variables
Data items are stored in variables, which symbolically (via their names) identify memory
locations where these items are stored. For a primitive type, the data item is stored
directly in the variable. For a user-defined type, a data item is an object stored elsewhere
in memory and a reference to the object is stored in the variable.
Variables must be declared before they are used. A declaration minimally consists of
a type name followed by an identifier that names the variable. Here are some examples:

boolean first; // Determine first time through the loop.


int counter; // Count the number of times a file has been opened.
char gradeLetter; // Identify a student’s end-of-year grade in a particular
subject.
double temperature; // Specify the current temperature.
String direction; // In what direction is the wind blowing?

The first example declares a Boolean variable named first. The second example
declares an integer variable named counter. The third example declares a character
variable named gradeLetter. The fourth example declares a double-precision floating-
point variable named temperature. The fifth example declares a String variable named
direction.

24
Chapter 2 Comments, Identifiers, Types, Variables, and Literals

When a variable is declared and not explicitly initialized (demonstrated later in this
chapter), it is implicitly initialized to a default value. A Boolean variable is initialized
to false, variables of the four integer types are initialized to 0, a character variable is
initialized to Unicode character 0, variables of the floating-point types are initialized to
0.0, and String variables are initialized to null.

DECLARATION VS. DEFINITION

I use the term declaration when introducing an identifier and associated syntax for a new
variable, method, or other relevant language feature into a program’s source code. (I use
declaration regardless of whether or not I initialize the variable, specify a non-abstract
method, and so on. [I cover methods in Chapter 6 and abstract methods in Chapter 8.] Some
programmers prefer the term definition over declaration, which has led to confusion. If you
are wondering what’s the big deal, remember that being precise in terminology can minimize
mistakes and clear up confusion – you’ll save yourself many headaches that arise from
arguments over seemingly trivial matters. However, such matters cannot be trivial if you spend
time getting worked up and angry while trying to defend your position.)

According to The C Programming Language (http://en.wikipedia.org/wiki/The_C_


Programming_Language), the definitive reference book on C, which was written by Brian
Kernighan and the late Dennis Ritchie (the creator of C), there is a difference. Page 76 of the
1978 edition states: “It is important to distinguish between the declaration of an external
variable and its definition. A declaration announces the properties of a variable (its type, size,
etc.); a definition also causes storage to be allocated.”

Regarding Java, the best resource for addressing this issue is probably The Java® Language
Specification (http://docs.oracle.com/javase/specs/jls/se21/jls21.pdf).
Chapter 6 (which covers names) uses the term declaration. In contrast, the most popular
answer to stackoverflow’s “What is the difference between declaration and definition
in Java” topic (http://stackoverflow.com/questions/11715485/what-is-
the-difference-between-declaration-and-definition-in-java) states that
declaration deals with the existence of a variable, method, and so on, whereas definition deals
with “how something is implemented” – what it is. The answer goes on to state that there is
little difference between declaration and definition in Java. Furthermore, the answer states
that “a declaration not only includes the identifier, but also its definition.”

25
Chapter 2 Comments, Identifiers, Types, Variables, and Literals

Literals
A literal is a value expressed verbatim in source code. Java supports literals for its
primitive types, initializing reference type variables, and a special reference type known
as String (discussed in Chapter 13).

Note Literals are also known as simple expressions. I discuss expressions in


terms of their simple and compound variants in Chapter 3.

A Boolean literal consists of either the keyword true or the keyword false.
A character literal consists of a single Unicode character surrounded by single quotes
(e.g., '6').
An integer literal consists of a sequence of digits. The type of an integer literal is int
(a 32-bit value). You can change the type to long by suffixing the literal with l or L (which
is easier to read).
Integer literals can be specified in the decimal, hexadecimal, octal, and binary
formats:

• The decimal format is the default format, for example, 127.

• The hexadecimal format requires that the literal be prefixed with


0x or 0X and continue with hexadecimal digits (a–f and/or A–F), for
example, 0x3FB2.

• The octal format requires that the literal be prefixed with 0 and
continue with octal digits (0–7), for example, 0276.

• The binary format requires that the literal be prefixed with 0b or 0B


and continue with 0s and 1s, for example, 0b11010110.
Starting with JDK 7, you can improve readability by inserting underscores between
digits. For example, 204_555_1212 is easier to read than 2045551212. Although you can
insert multiple successive underscores between digits (such as 987___235), you cannot
insert a leading underscore (_4222). The compiler will report an error when you try to
do so. Also, the compiler reports an error when you specify a trailing underscore, for
example, 99_.

26
Chapter 2 Comments, Identifiers, Types, Variables, and Literals

A floating-point literal consists of an integer part followed by a decimal point


followed by a fractional part followed by an exponent (starting with letter E or e) followed
by a type suffix (D or d for double-precision floating-point; F or f for floating-
point – a floating-point literal defaults to double-precision floating-point). Most parts
are optional, but you must specify enough information to distinguish the floating-point
literal from an integer literal. Examples include 0.9 (double-precision floating-point),
36F (floating-point), 900D (double-precision floating-point – the D changes 32-bit integer
900 to an equivalent double-precision floating-point value), and 33.8E+22 (double-
precision floating-point).
The null literal is assigned to a reference variable to indicate that the variable does
not refer to an object. It signifies the absence of a meaningful value.

Caution The compiler reports an error when you attempt to assign null to a
variable that has a primitive (value) type (such as int).

It’s possible to run into trouble when working with null. For example, when a user-
defined variable contains the null reference instead of a reference to an object, and
you attempt to access a field or invoke (call) a method, you will encounter the dreaded
NullPointerException. (I will discuss objects, fields, and methods in Chapter 6. Also, I
will discuss exceptions and mention NullPointerException in Chapter 11.)

Note You can learn more about the concept of nullness (being null) and
NullPointerException by reading Yoshitaka Shiotsu’s excellent article “Null
In Java: Understanding the Basics” (www.upwork.com/resources/what-is-
null-in-java).

Finally, a string literal consists of a sequence of Unicode characters surrounded by


a pair of double quotes, for example, "What is the weather like today?". It might
also include escape sequences, which are special syntax for representing certain printable
and nonprintable characters that otherwise cannot appear in a literal. For example, "The
title of the book is \"Mastering Java\" and is written by John Doe." This
example uses the \" escape sequence to surround Mastering Java with double quotes.

27
Chapter 2 Comments, Identifiers, Types, Variables, and Literals

The following escape sequences are supported: \\ (backslash), \" (double quote),
\' (single quote), \b (backspace), \f (form feed), \n (newline), \r (carriage return), and
\t (tab).
A string literal might also contain Unicode escape sequences, which are a special
syntax for representing Unicode characters. A Unicode escape sequence starts with \u
and continues with four hexadecimal digits (0–9, A–F, or a–f) with no intervening space.
For example, \u0043 represents the capital letter C, and \u20ac represents the European
Union currency symbol.
The following examples use literals to initialize the previously presented variables:

boolean first = true;


int counter = 10;
char gradeLetter = 'A';
double temperature = 37.9;
String direction = "East";

Putting It All Together


Listing 2-2 presents the source code to a VarInit application that demonstrates
identifiers, types, variables, and literals via the previous examples. You can modify
VarInit’s source code to introduce your own examples and learn more about these basic
language features.

Listing 2-2. VarInit.java

class VarInit
{
   public static void main(String[] args)
   {
      boolean first = true;
      int counter = 10;
      char gradeLetter = 'A';
      double temperature = 37.9;
      String direction = "East";
      System.out.println(first);
      System.out.println(counter);

28
Chapter 2 Comments, Identifiers, Types, Variables, and Literals

      System.out.println(gradeLetter);
      System.out.println(temperature);
      System.out.println(direction);
   }
}

Compile Listing 2-2 as follows:

javac VarInit.java

Run the application as follows:

java VarInit

You should observe the following output:

true
10
A
37.9
East

VAR

JDK 10 introduced var, a shortcut to declaring and initializing variables. To save keystrokes,
you no longer have to enter a variable’s type name because the compiler infers the variable’s
type from the literal’s (or other expression’s) type during initialization. For example, in var ch
= 'C';, the compiler infers that variable ch has type char because the type of 'C' is char.
Without var, you would specify char ch = 'C';. Although you saved one keystroke, which
doesn’t seem like much, you could save more keystrokes in longer syntactic contexts, such as
var amount = 10.0; instead of double amount = 10.0;.

Remember two important points when working with var:

• You must always use var in an initialization and not a declaration-only context.
In other words, you must always assign a literal or other expression to the
variable. If you specify var and a variable name by themselves, as in var ch;,
the compiler will report an error because it cannot infer a type for ch.

29
Chapter 2 Comments, Identifiers, Types, Variables, and Literals

• The var identifier might seem like a reserved word (or keyword, if you like),
but that is not the case. You cannot use a reserved word to name a variable.
However, the following declaration is legal: var var = 10.0;. In this
example, var is a double-precision floating-point variable initialized to 10.0.

I recommend not using var to name a variable (as in var var) because the result might
confuse someone who is reading your source code. Also, var might become a reserved word
someday.

What’s Next?
Now that you’ve mastered comments, identifiers, types, variables, and literals, you’re
ready to explore operators and expressions. These language features let you manipulate
data items to produce new data items, which is done in every kind of program, from a
business payroll application to a machine-learning demo.

30
CHAPTER 3

Expressions
Computer programs manipulate data via expressions. This chapter introduces you to
expressions in terms of simple and compound expressions.

Introducing Expressions
An expression is a combination of literals, variable names, method calls (discussed in
Chapter 6), and operators. At runtime, the expression evaluates to a type referred to as
the expression’s type.
If an expression is being assigned to a variable, their types must agree (it must be
possible to convert from one type to the other without losing information) or else the
compiler will report an error.

Simple Expressions
A simple expression is a literal value, a variable name (containing a value), or a method
call (returning a value) – I cover methods and method calls in Chapter 6. The following
examples demonstrate these simple expressions being used to initialize variables:

int i = 2; // a literal value (2) of type int


int j = i; // a variable name (i) of type int
boolean success = open("file.txt"); // a method call that returns Boolean
true/false

The first example assigns literal 2 to variable i. The literal and variable have the same
type: int.
The second example assigns variable i to variable j. Both variables have the same
int type.

31
© Jeff Friesen 2024
J. Friesen, Learn Java Fundamentals, https://doi.org/10.1007/979-8-8688-0351-2_3
Chapter 3 Expressions

The third example calls an open() method, passing to this method the name of a file
to open, and assigns the result to variable success. Let’s assume that open()’s return
type is boolean, which matches success’s return type.
These examples assume that only expressions whose types match the types of the
variables that they are initializing can be assigned to those variables. However, it is
possible to assign a simple expression having a different type. For example, Java lets you
assign various int literals to a variable of type short, as in short x = 90;, and assign a
short to an int variable, as in int y = x;.
The former assignment is okay because 90 can be represented as a short integer – the
largest short that can be represented is 32767, so 90 fits into a short. In contrast, the
compiler would complain when encountering short x = 80000; because 80000 cannot
be represented in 16-bit space, and information would be lost.
The latter assignment is acceptable because there is no loss of information when
you convert from a type with a lesser set of values to a type with a greater set of values. A
short’s range of values can easily fit into an int’s greater range of values.
Java uses widening conversion rules to support the following primitive-type
conversions:

• byte to short, int, long, float, or double

• short to int, long, float, or double

• char to int, long, float, or double

• int to long, float, or double

• long to float or double

When converting a smaller integer to a longer integer, Java copies the smaller
integer’s sign bit into the larger integer’s extra bits (on the left). If you would
like to understand signed integer representation, check out Wikipedia’s “Signed
number representations” (http://en.wikipedia.org/wiki/Signed_number_
representations) entry.
The previous examples focus on simple expressions in a variable-declaration
context. One of these simple expression categories, the method call, can also appear in a
non-variable-declaration context. Here is an example:

success = open("file.txt");

This example assumes that a boolean success; declaration appeared earlier.

32
Chapter 3 Expressions

Compound Expressions
A compound expression is a sequence of simple expressions connected to each other via
operators, which are symbolically represented sequences of instructions that transform
their operands into new values. For example, -1 is a compound expression where - is an
operator and int literal 1 is its operand. This expression transforms 1 into its negative
equivalent: -1. Also, 4 * y is a compound expression where * is an operator and 4 and
y are its operands. When this expression is evaluated, y’s value is fetched and multiplied
by 4. The expression’s value becomes the result of the multiplication.

Note If x’s type is byte or short, the variable’s value is widened to an int.
However, if the type is long, double, or float, 4 is widened to the appropriate
type. The addition is performed after the widening is carried out.

Java classifies its operators via the number of operands that they take:

• A unary operator takes a single operand. In the previous -1 example,


the - (unary minus) operator takes a single operand.

• A binary operator takes two operands. The * (multiplication)


operator in 4 * y is an example of a binary operator.

• Java supports a single ternary operator that takes three operands.


This operator is represented by two symbols ( ? :) and is known as
the conditional operator. I’ll discuss this operator later.

Java also classifies its operators as prefix, postfix, and infix:

• A prefix operator is a unary operator that precedes its single operand


(as in -1).
• A postfix operator is a unary operator that follows its single operand
(as in x++ – increment the value in x).

• An infix operator is a binary operator that appears between the


binary operator’s two operands (as in 4 * y) or the ternary operator’s
three operands.

33
Chapter 3 Expressions

When evaluating an expression, the compiler considers each operator’s precedence


and associativity:

• Precedence determines how an expression is evaluated when


it contains two or more operators with different precedences.
Operators with higher precedence are evaluated first. For example, in
the expression 4 + 2 * 3, subexpression 2 * 3 is evaluated first because
multiplication takes precedence over addition.
• Associativity determines how an expression is evaluated when it
contains two or more operators with the same precedence. For
example, 4 + 2 + 3 would first evaluate 4 + 2 because + has left-to-
right associativity. If + had right-to-left associativity, 2 + 3 would first
be evaluated, and the result would be added to 4.

Table 3-1 presents all of Java’s operators in terms of their symbols, descriptions,
precedences, and associativity.

Table 3-1. Java’s Operators Grouped by Precedence


Operator Type Precedence Associativity

() Parentheses 15 Left to right


[] Array index
. Member selection
++ Unary post-increment 14 Right to left
-- Unary post-decrement
++ Unary pre-increment 13 Right to left
-- Unary pre-decrement
+ Unary plus
- Unary minus
! Unary logical negation
~ Unary bitwise complement
(type) Unary type cast
(continued)

34
Chapter 3 Expressions

Table 3-1. (continued)


Operator Type Precedence Associativity

* Multiplication 12 Left to right


/ Division
% Modulus
+ Addition 11 Left to right
+ String concatenation
- Subtraction
<< Bitwise left shift 10 Left to right
>> Bitwise right shift with sign extension
>>> Bitwise right shift with zero extension
< Relational less than 9 Left to right
<= Relational less than or equal to
> Relational greater than
>= Relational greater than or equal to
instanceof Relational type comparison for objects
== Is equal to 8 Left to right
!= Is not equal to
& Bitwise AND 7 Left to right
^ Bitwise exclusive OR 6 Left to right
| Bitwise inclusive OR 5 Left to right
&& Logical AND 4 Left to right
|| Logical OR 3 Left to right
?: Conditional 2 Right to left
(continued)

35
Exploring the Variety of Random
Documents with Different Content
Tres españoles, Hoz, Camargo y Valdivia, acariciaron al mismo
tiempo la idea de proseguir la abandonada empresa. Mas

Á solo el de Valdivia esta victoria


Con justa y gran razón le fué otorgada,
Y es bien que se celebre su memoria,
Pues pudo adelantar tanto su espada:
Éste alcanzó en Arauco aquella gloria
Que de nadie hasta allí fuera alcanzada;
La altiva gente al grave yugo trujo
Y en opresión la libertad redujo.

Así cantaba, con verdad y justicia, el insigne autor de La


Araucana; pero se aparta igualmente de una y otra cuando, más
adelante, nos dice que Valdivia

Con una espada y capa solamente,


Ayudado de industria que tenía,
Hizo con brevedad de buena gente
Una lucida y gruesa compañía.

Valdivia, al emprender la conquista de Chile, no era un simple y


vulgar aventurero de capa y espada, como nos cuenta Ercilla, sino
Maestre de Campo en el Perú, reputado por sus hazañas en las
guerras de Italia, en el descubrimiento y conquista de Venezuela y
en la batalla de las Salinas. Á su bien ganada fama y á su alto grado
en la milicia, el esforzado extremeño añadía una posición
desahogada, pues poseía el valle de la Canela, en las Charcas, que
después de su partida fué suficiente para ser distribuído entre tres
conquistadores; y una mina de plata que, en un decenio, produjo
más de 200.000 castellanos. Consta del modo más auténtico, por
confesión del mismo Valdivia en carta al Emperador Carlos V,
fechada el 15 de Octubre de 1550. Si no hubiese estado
acomodado, no habría podido emprender, como emprendió por su
cuenta, la conquista de Chile. De Pizarro sólo recibió el
nombramiento de Teniente de Gobernador y Capitán general de la
Nueva Toledo y Chile, con facultades de explorar la tierra de allende
los Andes, á su costa, como pudiera, sin proporcionarle ninguna
especie de auxilio.
Uno de sus compañeros de armas, el capitán Alonso de Góngora
Marmolejo, nos ha dejado el siguiente retrato de Valdivia: «Era
hombre de buena estatura, de rostro alegre, la cabeza grande
conforme al cuerpo, que se había hecho gordo, espaldudo, ancho
de pecho, hombre de buen entendimiento, aunque de palabras no
bien limadas, liberal, y hacía mercedes graciosamente. Después
que fué señor rescibía gran contento en dar lo que tenía; era
generoso en todas sus cosas, amigo de andar bien vestido y
lustroso, y de los hombres que lo andaban, y de comer y beber bien:
afable y humano con todos; mas tenía dos cosas con que
obscurecía todas estas virtudes: que aborrecía á los hombres
nobles, y de ordinario estaba amancebado con una mujer española,
á lo cual fué dado.»
No son estas las faltas que censura en Valdivia el autor de La
Araucana, sino que fuese

Remiso en graves culpas y piadoso,


Y en los casos livianos riguroso.

Trece años duró el descubrimiento, conquista y gobierno de Chile


por Valdivia; trece años de trabajos en tierras, no auríferas, sino
yermas, y en lucha, no con indios como los del Perú, sino con uno
de los pueblos más fieros y valerosos del Nuevo Mundo: los
indómitos araucanos. «No eran éstos ciertamente—escribe el ilustre
historiador chileno Amunátegui—los cumplidos caballeros armados
de lanzas y macanas que ha pintado Don Alonso de Ercilla en
octavas bien rimadas y peinadas, sino bárbaros sin más religión que
algunas supersticiones groseras, ni más organización social que la
que resultaba de la obediencia á los jefes que sobresalían por el
valor ó la astucia; obediencia que, sobre todo en tiempo de paz, era
sumamente floja.»
¿Qué testimonio mayor de la barbarie de estas gentes que lo que
hicieron con Valdivia cuando cayó en sus manos prisionero, en la
desgraciada rota de Tucapel? Según Ercilla, el conquistador de
Chile fué muerto de un golpe de maza. El Padre Alonso de Ovalle
dice que le echaron oro derretido en la boca. Pero lo más cierto en
este punto es la relación de Góngora Marmolejo, confirmada por la
carta del Cabildo de Santiago á la Real Audiencia de Lima, el 26 de
Febrero de 1554, según la cual el desgraciado Valdivia, después de
prisionero, vivió hasta tres días, herido y maltrado horriblemente, y,
después de muerto, los feroces araucanos cortaron el cadáver en
pedazos y se lo comieron. Ercilla, que con tan patéticos colores nos
pinta la muerte del bárbaro Caupolicán, no tuvo para el heroico
español sino vulgares frases, desnudas de poesía. No sabemos si
para la honra de España han sido más fatales los versos de Ercilla ó
las páginas del Padre Las Casas, abogados igualmente de los
Indios é injustos con los conquistadores.

Codicia, fué ocasión de tanta guerra,


Y perdición total de aquesta tierra.

Decía el autor de la La Araucana, La codicia, y solamente la


codicia, han repetido después, en su odio á nuestra patria, los
detractores de sus glorias.
Por dicha nuestra, es la gloriosa figura del conquistador de Chile
una de las que, de manera más cumplida, patentizan ante el mundo
la grandeza civilizadora del descubrimiento y conquista del Nuevo
Mundo. No fué sólo la codicia el móvil de obra tan grande, ni la
guerra el único medio que emplearon nuestros padres. Valdivia,
maestre de campo; Valdivia, acomodado, no fué á Chile por pura
codicia; fué por dar rienda suelta á su espíritu aventurero, religioso y
patriótico; fué por encontrar un campo en que poder dar vuelo á la
fuerza de acción que sentía en sí mismo. Por eso en Valdivia vale,
tanto ó más que el soldado, el civilizador y colonizador, el fundador
de la sociedad chilena. Díganlo, si no, las ciudades que dejó
fundadas, que son hoy las más florecientes de la República chilena.
Santiago, La Serena, La Concepción, La Imperial, Valdivia,
Valparaíso, todas fueron erigidas por Valdivia. En ninguna otra
conquista entró por menos la sed de oro ni el afán de riquezas que
en la conquista de Chile. Precisamente las minas de este país casi
no han sido conocidas y explotadas hasta nuestro tiempo. La
población de Chile fué desde el principio de gente trabajadora y
modesta, pero fuerte y valerosa. Á esto quiza deba principalmente la
hoy poderosa República el fundamento sólido y venturoso de su
prosperidad y de su gloria.
Y, dicho sea en su honra, de todas las nuevas naciones
americanas de origen español, Chile es la que más noblemente ha
conservado y honrado las memorias de sus padres. En el cerro de
Santa Lucía, en Santiago, coronando la ciudad, se alza hace años la
estatua de Valdivia, ejemplo que no ha tenido hasta ahora los
imitadores que debiera en otros Estados. Aún no tienen estatuas en
Méjico Hernán Cortés, en Lima Pizarro, en Bogotá Quesada, en
Buenos Aires Garay, y así otros grandes conquistadores de pueblos
y fundadores de ciudades. Lejos de mi ánimo acusar de ingratas,
sino de perezosas, á las naciones que se encuentran en este caso.
Estoy seguro de que no ha de tardar mucho tiempo en que todas
honrarán á sus conquistadores como Chile á Valdivia.
Importa añadir que, no sólo la estatua, sino la casa y capilla de
Valdivia, en Santiago, publican la gratitud de los chilenos al
desventurado y glorioso conquistador. Es más: la fiesta que
anualmente consagran á su memoria, no fué interrumpida ni en los
días de la guerra entre Chile y España. De este modo el pueblo
chileno revela bien á las claras los caracteres que distinguen á su
organización social, fundada igualmente en la tradición y el
progreso, y la fuerza y esplendor de su cultura, de la que puede
envanecerse justamente y con Chile la patria de Almagro y de
Valdivia.
GONZALO JIMÉNEZ DE QUESADA
EN LA POESÍA Y EN LA HISTORIA
EL 6 de Abril de 1536, D. Pedro Fernández de Lugo, Gobernador de
Santa Marta, envió á su Teniente y Justicia mayor, el Licenciado
Gonzalo Jiménez de Quesada, con 800 hombres, 100 caballos y 5
bergantines, Río Grande de la Magdalena arriba, «á inquirir
particularmente lo que por este río la tierra adentro se pudiese calar
y entender.»
El resultado de esta expedición fué el descubrimiento y conquista
del territorio que Jiménez de Quesada, como granadino que era,
bautizó con el nombre de Nuevo Reino de Granada, y que hoy
constituye la mejor parte de la actual República de Colombia.
Entre los héroes españoles en el Nuevo Mundo, el conquistador
de Nueva Granada y autor de la maravillosa expedición á Eldorado,
por sus condiciones personales como por sus gigantescas hazañas,
se cuenta sin duda entre los más grandes, acaso, después del
conquistador de Méjico, y seguramente al lado de Cortés, Pizarro,
Valdivia, Almagro y Orellana. Letrado, poeta, historiador, inteligencia
aguda y brillante, añadía á estas prendas las que más enaltecieron
á los mayores conquistadores: la constancia, la prudencia, la
generosidad; en suma, las cualidades del General y del político á un
tiempo.
Fué el descubrimiento del Nuevo Reino de Granada una de las
empresas más admirables de aquella época, tan fecunda en hechos
asombrosos. Buscando el nacimiento del Río Grande de la
Magdalena, por las aguas y por las orillas subieron nuestros
expedicionarios ciento seis leguas hasta llegar á Tora. En el
transcurso de trece meses, de los 800 hombres quedaron vivos
poco más de 150. El hambre les llevó, en ocasiones, á comer raíces
de árboles, y aun las mismas adargas que llevaban para su defensa.
Al salir de Tora, aquel puñado de héroes, rendidos, enfermos,
caminaban apoyándose muchos en palos y ramas. El Capitán, no
pudiéndose tener á pie ni á caballo, era llevado á hombros por su
gente. Escena verdaderamente grandiosa, que deben tener
presente los que sólo ven en los conquistadores la codicia del oro,
olvidando sus padecimientos incomparables. Así atravesaron las
montañas del Opón, y entraron en las altas tierras de Bogotá.
En estas condiciones acometieron la conquista de un territorio que
podía tener sesenta leguas de N. á S., y sobre poco más ó menos
otras tantas de E. á O. Obra de la prudencia y el ingenio, aunados al
valor y á la firmeza, la conquista y pacificación de la tierra no fueron
acompañadas de ferocidades y matanzas, como otras empresas
semejantes. Y no es de olvidar que en algunas partes tenían que
habérselas con indios como los Panches, «gente bestial y de mucha
salvajía.» El hallazgo de las esmeraldas no suscitó tampoco
sangrientas luchas entre los españoles. Las nuevas poblaciones
nacieron sin violencia ni despojos, singularmente Bogotá, que aún
conserva, como pocas ciudades de América, el sello impreso por su
fundador en los primeros orígenes.
Cuando Sebastián de Belalcázar, viniendo de Quito, llegó á Nueva
Granada, encontró á Quesada y á los suyos «en mucha neçesidad,
por que ya les avía faltado casi todas las armas y herraje y vestidos
y cosas de España.» Estas palabras de Belalcázar se contienen en
carta escrita el 20 de Marzo de 1540, que saldrá íntegra á luz, muy
en breve, en el tomo civ de la Colección de documentos inéditos
para la Historia de España. Precioso testimonio que prueba el
penosísimo estado en que aquellos héroes se encontraban después
del vencimiento.
Por fortuna, los sucesos principales de tan gran empresa
quedaron registrados en documentos del más autorizado origen y
procedencia. El primero de todos es la relación escrita por el
conquistador, cuyo original se ha perdido, pero que manejó y copió
en gran parte el cronista Fernández de Oviedo. «Muchas veces—
escribe—tuve plática en Madrid con el licenciado Ximenez, y en
Valladolid, en la corte del príncipe Don Felipe, nuestro señor, y nos
comunicamos; y á la verdad es hombre honrado y de gentil
entendimiento y bien hábil. Y como yo sabía quél avía conquistado
el nuevo reyno de Granada y descubierto la mina de las esmeraldas,
y avía visto la relaçion que los offiçiales avían enviado a Su
Magestad Cessárea... quise informarme dél de algunas cosas viva
voce, y él no solamente de palabra, pero por escripto, me mostró un
gran cuaderno de sus subçesos, y lo tuve muchos días en mi poder,
y hallé en él muchas cosas de las que tengo aquí dichas en los
capítulos preçedentes, y de otras que aquí se pondrán.»
Después de Quesada, el historiador más antiguo y más
importante es el autor de las Elegías de varones ilustres de Indias,
Juan de Castellanos. Bien como continuación de las Elegías y
formando cuerpo con ellas, que es lo que tengo por más seguro,
bien como obra aparte y especial, como otros creen, ello es que
Castellanos escribió en verso la historia del Nuevo Reino de
Granada, desleída más tarde en prosa, sin decirlo, por Luis
Fernández Piedrahita, fuente, á su vez, de los trabajos históricos
posteriores. Castellanos pasó la mayor parte de su vida en el reino
conquistado por Quesada, conoció á éste y á muchos de sus
compañeros, y estaba, por consiguiente, en condiciones de relatar
los sucesos con verdadero conocimiento de causa. Su versificación,
desmayada y ramplona, vecina de la prosa, hace pesada la lectura
de esta historia, por otra parte más fiel y exacta que los poemas
históricos de descubrimientos y conquistas, incluso La Araucana de
Ercilla, su modelo.
No puede decirse otro tanto de la comedia La Conquista de
Bogotá, de D. Fernando Orbea. Precisamente esta comedia es todo
lo contrario del poema del buen Clérigo de Alanis. Si éste descuella
por su valor histórico, aquélla sobresale por su desconocimiento de
la historia. De este modo, es el poema de Castellanos crónica
rimada, y la comedia de Orbea pura novela, en su argumento, en
sus situaciones, en una palabra, en todo. Solamente hay de real en
ella los nombres de Quesada, Belalcázar y Lugo, y los de Tundama
y Nemequene, aplicados á dos personajes bogotanos. Hasta en
punto á versificación no cabe imaginar mayor contraste que el que
ofrecen el poema y la comedia, prosaico en superlativo grado el
primero, culterana á más no poder la segunda.
Hállase entre los manuscritos de nuestra Biblioteca Nacional
procedentes de la de los Duques de Osuna, adquirida por el Estado.
Su título es el siguiente:
«COMEDIA
NUEVA

La Conquista de Santa Fee de Bogotá


su autor Don Fernando Orbea. Copiada
fielmente segun su insigne Original.»
Ni de la comedia ni de su autor tenemos otras noticias. Conjeturo
que Orbea era americano ó español residente en América. Me fundo
para ello en las canciones que canta en indio y en español, en el
acto III, la india Florela. En lo que no cabe duda es en que fué
compuesta para Lima, como lo prueban sus últimos versos:

Ilustre Lima, aquí tiene


Fin el concepto expresado:
Vuestra discreción tolere
Los yerros, que han sido tantos.

No dejan de ser, en efecto, muchos los yerros de nuestro autor,


desde el principio al fin de su comedia, sobre todo en lo que
respecta á la verdad histórica, que sale, con leves diferencias, tan
bien librada como en las demás comedias de descubrimientos y
conquistas, inclusas las de Lope y Calderón.
Tundama, general de Osmín, rey de Bogotá, acaba de derrotar,
en descomunal batalla, los ejércitos del rey de Popayán, trayendo
entre los trofeos de su victoria á la infanta Amirena, por quien siente
un amor tan súbito y vehemente como el que ha logrado inspirar á la
intrépida amazona. Llegado á la corte, recíbenlo, con grande fiesta,
el Monarca bogotano y su esposa Palmira. Entonces les sorprende
la venida del Mariscal Quesada con Belalcázar y Lugo, que llegan á
Bogotá por un río tan fantástico como el rey Osmín, la reina Palmira,
la infanta Amirena, el general Tundama, la victoria de éste, las
fiestas, en suma, todo. Bien es verdad que en lo que toca á los
españoles, se permite nuestro autor libertades semejantes,
convirtiendo á Belalcázar y Lugo en compañeros y capitanes de
Quesada. Pero donde raya más alto su inventiva es en la marcha de
la acción, que se reduce á una serie de batallas y de escenas
mágicas y milagrosas, en las que ostentan todo su poder la Religión
Cristiana y los dioses bogotanos en simbólicos combates. Y como si
todo esto no fuese bastante para agotar la rica vena de nuestro
autor, Quesada se enamora de Palmira, y ésta de Quesada,
terminando la comedia con la boda en perspectiva del Capitán
español y la Reina bogotana, á quien su futuro acaba de nombrar
Duquesa de Cali y Tunga.

¡Dulce fin! Venus y Marte


Han vencido y han triunfado,

exclama Palmira, satisfecha del venturoso desenlace, y asunto


terminado,
No es cosa de privar á los lectores del conocimiento de algunos
otros incidentes de nuestra comedia. Amirena muere peleando
como la más heroica amazona. Tundama, su amante, que aspiraba
á ceñir á sus sienes la corona de Bogotá, perece en la demanda. El
rey Osmín, es, en toda la obra, trasunto fiel del infortunado Boabdil.
Y para serlo en todo, hasta es reprendido en iguales términos que
aquél cuando rompe á llorar viendo perdido su reino.

Llore, pues, como mujer


Quien valiente no ha sabido
Ser en la campaña rayo
De aleves advenedizos.
Por el contrario, Castellanos nos representa al Rey de Bogotá
digno, en su persona y en sus hechos, del poder que ejercía:

Éste, segun oyeron españoles,


Representaba bien en su persona,
Alta disposición y gallardía
Y gravedad de rostro bien compuesto,
La dignidad y mando que tenía
Sobre los otros reyes desta tierra.

Oviedo nos asegura «que era muy cruel é muy temido y no


amado; y el día que se supo cierto que era muerto, fué general el
alegría en toda su tierra, porque los caciques y señores quitaron de
sí una tiranía muy grande.»
Orbea creyó preferible, sin duda, en vez de consultar los
testimonios históricos, entregarse de lleno al libre vuelo de su
fantasía, comenzando por bautizar al pobre Rey con el nombre
turco-moro de Osmín, tan bogotano como el de Palmira, que da á su
esposa.
De la propiedad histórica en todo lo demás, puede juzgarse sólo
con parar mientes en los románticos amores que sirven de base al
argumento de la comedia, recordando que en el territorio
descubierto por Quesada existía la poligamia; que el Rey de Bogotá
tenía centenares de mujeres, y cada uno de su reino cuantas podía
mantener, y que, como refiere Castellanos, cuando un indio gustaba
de alguna india

Contrata con los padres ó parientes


Que la tienen debajo de su mano,
Cerca del precio que dará por ella;
Y si la cantidad no les contenta,
El comprador añade por dos veces
La mitad más de lo que dió primero;
Y si de la tercera vez no compra,
Busca mujer que sea más barata;
Mas si les satisface lo que manda,
Dánsela, sin usarse de más ritos
De recibirla, dándoles la paga,
Quedándose con ella quien la vende,

Corre parejas con el romanticismo de los indios la erudición


clásica que nuestro autor les prodiga á manos llenas, y aun más, si
cabe, el manejo de la Historia de España que les atribuye, hasta el
punto de que Amirena, al arengar á los soldados bogotanos,
comienza por decirles:

Ea, valientes soldados,


Examinad la campaña;
No quede tronco ni selva
Que no registre la saña,
En pavesas renovando
Los estragos de Numancia.

Á pesar de tantas impropiedades, por otra parte, como el estilo


gongorino, corrientes en nuestro viejo teatro, hay de vez en cuando
en la comedia de Orbea algunos rasgos de cierto mérito, como, por
ejemplo, aquel en que Quesada, después de amonestar al rey
Osmín á que se convierta, le amenaza si no lo hace, diciéndole:

Te quitaré la corona;
Pisarála Carlos Quinto;
Pondré en tus bárbaros templos
Lo estandartes de Cristo.
Pondré la planta en tu cuello,
Después que te haya vencido:
Y al subir á mi caballo
Me servirás por estribo.
En ocasiones semejantes, Orbea suele abandonar el culteranismo
y hablar el lenguaje propio de los afectos del alma. No así en las
descripciones y relatos, en los cuales vierte el caudal de sus
tinieblas, como, pongo por caso, en la relación que hace Tundama
de su victoria sobre los popayanos, que es larga y tenebrosa como
noche de invierno.
Para concluir, La Conquista de Bogotá es una de tantas comedias
de descubrimientos y conquistas, en las cuales ni éstas ni aquéllos
se nos muestran con la verdad y poesía que tuvieron. Toda la
realidad y la vida con que aparecen en los monumentos históricos,
desaparecen al ser convertidas en alegorías artificiales, batallas de
teatro ó enredos de damas y galanes, ni más ni menos que en las
comedias de capa y espada.
Digámoslo de una vez: los hechos del descubrimiento y conquista
del Nuevo Mundo no caben en el teatro. Caben, sí, en la Historia,
que puede presentarlos en su propia grandeza y con su natural
hermosura.
EL ALFÉREZ DOÑA CATALINA DE
ERAUSO
EL Capitán Miguel de Erauso, vecino de San Sebastián, á fines del
siglo xvi y principios del xvii hubo en su mujer María Pérez de
Galarraga tres hijos, militares los tres, otras tantas hijas, todas
monjas profesas, y, además, el sér extraño vulgarmente conocido
con el nombre de La Monja Alférez, militar como sus hermanos,
monja como sus hermanas, en el claustro Soror Catalina de Erauso,
y en los ejércitos de Chile y el Perú Alonso Díaz Ramírez de
Guzmán.
La existencia de este fenómeno antropológico consta del modo
más auténtico en documentos y testimonios fehacientes de su
época. Hablan de tan singular mujer: el Dr. Isasti, en su Compendio
histórico de la Provincia de Guipúzcoa; el maestro Gil González
Dávila, en su Historia de la vida del ínclito monarca, amado y santo
Don Felipe III; Pedro de la Valle, el Peregrino, en Carta á Mario
Schipano, fechada en Roma el 11 de Julio de 1626, y otros textos de
menor importancia, escritos, como los anteriores, en vida de la
célebre Monja.
Á los mismos días pertenece también la comedia de Montalbán La
Monja Alférez, compuesta el año en que ésta se hallaba en Roma,
que fué el de 1626.

.......tenga fin aquí


Este caso verdadero.
Donde llega la comedia
Han llegado los sucesos.
Que hoy está el Alférez Monja
En Roma, y si casos nuevos
Dieren materia á la pluma,
Segunda parte os prometo.

Aun más importantes son, sin duda, los documentos originales


que existen en el Archivo de Indias, en Sevilla, sobre todo el
Expediente de méritos y servicios del famoso Alférez, encabezado
con un pedimento suyo, verdadera autobiografía, comprobada por
las certificaciones de autoridades militares tan importantes como D.
Luis de Céspedes Xeria, Gobernador y Capitán general del
Paraguay, D. Juan Cortés de Monroy, Gobernador y Capitán general
de Veraguas, y D. Juan Recio de León, Maestre de Campo y
Teniente de Gobernador y Capitán general y Justicia mayor de las
provincias de Tipoán y Chunchos. No hay personaje de aquel
tiempo cuyos hechos capitales estén comprobados más plenamente
que los del Alférez Doña Catalina de Erauso.
Á estas fuentes, de autenticidad indiscutible, podemos recurrir, por
fortuna, para conocer la verdad, ya en vida de Catalina,
considerablemente adulterada en narraciones novelescas tenidas
por históricas aun en los mismos días que alcanzamos.
La principal de estas narraciones, considerada como verdadera
autobiografía, y en la cual se funda cuanto dentro y fuera de España
se ha escrito modernamente tocante á nuestra heroína, es la
publicada en París, en 1829, por el ilustre hombre de Estado y de
letras D. Joaquín María Ferrer, con el título: Historia de la Monja
Alférez, Doña Catalina de Erauso, escrita por ella misma.
Ya el docto crítico pudo observar en el texto de esta obra,
comparándola algunas veces con preciosos documentos hasta
entonces desconocidos y por él sacados á luz, numerosas
equivocaciones en punto á fechas y nombres; pero, lejos de entrar
en sospechas respecto á la autenticidad del manuscrito, atribuyó los
errores observados á la impericia del copista; cuando estos errores,
y otros de más bulto no reparados hasta ahora; la índole misma de
la supuesta Historia, que tiene desde la cruz á la fecha todo el corte
y sabor de novela picaresca, más burda quizás que ninguna otra; la
carencia de toda prueba, ni memoria siquiera de que la Monja
Alférez hubiera escrito su vida en ninguna forma, y, sobre todo, la
radical diferencia de la figura verdaderamente histórica, la que los
documentos nos ofrecen con la que aparece en algunos capítulos
de la novela, bastan sobradamente para evidenciar por completo
que la pretendida autobiografía es poco más ó menos tan histórica
como la comedia de Montalbán ó la zarzuela de Coello.
Como en otros casos, la persona histórica es mucho más
interesante, más poética que la personalidad de la leyenda. La
imaginación del novelista ó del poeta, lejos de embellecer, ha afeado
la figura de la heroína que intentaba enaltecer con sus invenciones,
al convertirla en personaje, ya de comedia de capa y espada, ya de
novela picaresca. El Alférez Monja de su pretendida autobiografía
no es siquiera un pícaro de la familia de los Lazarillos y Guzmanes;
es un espadachín ó perdonavidas adocenado, más bien un guapo ó
jaque vulgar, sin talento, sin grandeza, hasta sin gracia, cuyas
aventuras, toscamente referidas, están siempre lejos de despertar
interés, y mucho menos simpatía. Pasajes hay en ese libro, tan
repugnantes los unos, tan chabacanos los otros, que sólo con
sólidas pruebas podían ser atribuidos á la verdadera Monja Alférez,
hija de padres nobles, hidalgos y personas principales, como ella
misma nos dice, y de quien sus antiguos jefes aseguraban á una
voz haberle conocido siempre con mucha virtud y limpieza.
¿Pues qué diremos de la licencia para vestir siempre hábito de
varón, que en ese libro se supone haber otorgado á nuestra heroína
la Santidad de Urbano VIII? ¿Ni qué del título de ciudadano romano
concedido por el Senado de Roma? Es cierto que en cambio
encontramos en él hechos ciertos y probados. Todo lo cual nos
lleva, naturalmente, á creer que el autor de la novela tuvo en cuenta
algún relato de la vida del Alférez Monja, en que las invenciones y
las verdades andaban ya mezcladas y confundidas.
La confusión comienza precisamente en lo relativo á la fecha del
nacimiento de Catalina. El retrato de Pacheco, hecho en 1630, dice
que tenía ésta entonces cincuenta y dos años, por cuya cuenta se la
supone nacida en 1578. La novela comienza así: «Nací yo Doña
Catalina de Erauso en la villa de San Sebastián de Guipúzcoa, en el
año 1585.» Ahora bien: en los libros parroquiales de San Vicente
consta que recibió el bautismo el 10 de Febrero de 1592.
Su infancia nos es desconocida por completo. Todo cuanto se ha
dicho sobre la violencia de su condición, que obligó á sus padres á
recluirla desde muy niña en un convento, en el cual, al decir de un
escritor francés, «on eût dit d’un faucon élevé par mégarde dans un
nid de tourterelles», pertenece al dominio de la fábula. Entró en el
convento de monjas Dominicas de San Sebastián el Antiguo, como
entraron también en él tres hermanas suyas, como entraban
entonces tantas doncellas principales, esto es, por vocación
religiosa ó conveniencia de las familias. Las condiciones personales
de sus hermanas les permitieron profesar; las suyas le llevaron á
abandonar el convento antes que abrazar una profesión contraria á
sus inclinaciones y deseos.
La noticia más antigua que de su vida ha llegado á nosotros se
refiere al año de 1605, décimotercero de su edad y primero de su
estancia en el convento, en el cual estuvo en calidad de novicia
hasta Marzo de 1607. Desde esta fecha dejan de mencionarla los
libros conventuales. Á este mismo año pertenecen en cambio las
primeras noticias de su vida militar. «Certifico y hago fe á S. M. que
conozco á Catalina de Erauso de más de diez y ocho años á esta
parte que ha que entró por soldado en hábito de hombre», escribía,
en 1625 D. Luis de Céspedes Xeria, antes citado. Catalina decía en
1626, en su pedimento, que «en tiempo de diez y nueve años á esta
parte, los quince los ha empleado en las guerras del reino de Chile é
Indios del Pirú.» Ahora bien: añadiendo á estos quince años los
cuatro siguientes hasta 1626, en los cuales, descubierto su sexo,
dejó de servir en la milicia, resultan los diez y nueve á que hace
referencia, y el de 1607, principio de su vida militar. Á mayor
abundamiento, el Capitán de infantería española D. Francisco Pérez
de Navarrete asegura en su certificación “que cuando llegué al reino
de Chile, que fué el año de seiscientos y ocho, le hallé (al Alférez
Monja) sirviendo en el Estado de Arauco.”
Maravilla en verdad que una joven de diez y seis años, casi una
niña, tuviese en tan tierna edad resolución y fortaleza bastante para
abandonar su país, su familia, el convento en que vivía, atravesar el
Atlántico y, lo que es más sorprendente todavía, que la novicia de
San Sebastián el Antiguo se nos muestre de repente convertida en
soldado, combatiendo entre aquellos héroes

Que á la cerviz de Arauco no domada


Pusieron duro yugo por la espada.

Sus condiciones militares fueron tantas y tales, que el Capitán


Guillén de Casanova, castellano del castillo de Arauco, “la entresacó
de la compañía, por valiente y buen soldado, para salir á campear al
enemigo.” Por sus hechos mereció igualmente “tener bandera de S.
M., sirviendo, como sirvió, de Alférez de la compañía de infantería
del Capitán Gonzalo Rodríguez.” Y en todo el tiempo que sirvió en
Chile y el Perú “se señaló con mucho esfuerzo y valor, recibiendo
heridas, particularmente en la batalla de Purén.”
No conocemos caso semejante en nuestra historia. Nuestras
heroínas antiguas y modernas fuéronlo, por decirlo así, de ocasión,
en momentos determinados, en alguna empresa memorable. Pero
abrazar la carrera de las armas, ser militares de profesión, rivalizar
con los mejores soldados en valor, disciplina, fortaleza, heroísmo, y
por espacio de tantos años como la Monja Alférez, ninguna.
Solamente la doncella de Orleans es comparable con la doncella
donostiarra. Naturalezas, no diré idénticas, pero sí parecidas,
parecidos fueron también los impulsos que las arrojaron al combate.
Cuenta la leyenda de Catalina que ésta abandonó el convento por
una reyerta que tuvo con otra monja. ¡Pequeña causa para explicar
tan grandes efectos! Es Catalina quien nos refiere los verdaderos
móviles de su pasada á las Indias: “la particular inclinación que tuvo
de ejercitar las armas en defensa de la fe católica y el servicio del
Rey”, es decir, de la patria.
La fe y la patria, he aquí los grandes sentimientos que
despertaron las energías varoniles de aquella mujer extraordinaria,
los que la infundieron el entusiasmo, el vigor, la constancia con que
se arrojó á defenderlos al otro lado de los mares, en las tierras
americanas. La sublime visionaria de la Lorena y la esforzada
doncella vascongada son hermanas, mayor, si se quiere, la primera,
y menor la segunda, pero hermanas, seguramente. La leyenda, que
ha contribuído tanto á sublimar la figura de Juana de Arco, ha
empequeñecido, por el contrario, la de la heroína del Arauco. La
glorificación del martirio corona la grandeza de la doncella de
Orleans: en este punto, como en otros, Juana de Arco no tiene igual,
ni en la historia de Francia ni en la de ningún otro pueblo.
Lo que más es de admirar en el Alférez-Monja es que pudiera
conservar, como rigurosamente conservó, el secreto de su sexo, de
tal modo, que en los quince años que sirvió en Chile no fuera
conocida sino por hombre, hecho el más comprobado de todos en
su expediente. Y no es que debamos atribuirlo exclusivamente al
poder de su voluntad, como algunos pretenden, sino también á la
singularidad de sus condiciones físicas, manifiestamente varoniles,
como lo prueban su retrato y la descripción de su persona, que nos
han dejado algunos de los que la conocieron y trataron.
Su resolución y entereza en la ocultación de su sexo rayaron, á no
dudarlo, en lo increíble. Basta saber «que con estar en compañía
del Alférez Miguel de Erauso, su hermano legítimo, en el reino de
Chile, nunca se descubrió á él, aunque ella le conocía por tal
hermano, y esto hizo por no ser descubierta, negando la afición de
la sangre.»
De su aspecto varonil cabe formar cabal idea por la relación de
Pedro de la Valle, que la conoció y trató en Roma en 1626, cuando
la antigua novicia fué en aquel año á echarse á los pies del Papa,
confesando su vida é implorando el perdón de sus faltas. «Es—
escribía—de estatura grande y abultada para mujer, bien que por
ella no parezca no ser hombre. No tiene pechos: que desde muy
muchacha me dijo haber hecho no sé qué remedio para secarlos y
quedar llanos, como le quedaron: el cual fué un emplasto que le dió
un italiano, que cuando se lo puso le causó gran dolor; pero
después, sin hacerle otro mal, surtió el efecto.»
«De rostro no es fea, pero no hermosa, y se le reconoce estar
algún tanto maltratada, pero no de mucha edad. Los cabellos son
negros y cortos como de hombre, con un poco de melena como hoy
se usa. En efecto, parece más eunuco que mujer. Viste de hombre á
la española: trae la espada bien ceñida, y así la vida: la cabeza un
poco agobiada, más de soldado valiente que de cortesano y de vida
amorosa. Sólo en las manos se le puede conocer que es mujer,
porque las tiene abultadas y carnosas, y robustas y fuertes, bien que
las mueve algo como mujer.»
¿Cómo y cuándo se descubrió que fuese tal mujer? Lo
positivamente cierto que se sabe en este punto, es que se descubrió
ella misma, en 1622 ó 23, al Obispo de Guamanga, por unas
heridas de muerte que tuvo. Los pormenores de este hecho han
quedado desconocidos. La leyenda se ha apoderado de él más que
de ningún otro. Baste decir que la supuesta Historia, la comedia de
Montalbán y la zarzuela de Coello, nos dan otras tantas versiones,
todas ellas igualmente fantásticas. La más poética, sin duda, es la
de Coello, quien, con su admirable instinto dramático, atribuye al
amor el secreto de la mudanza operada en Catalina.

¿Qué es lo que cambia mi sér?


Ya lo empiezo á vislumbrar:
La desgracia me hizo amar.....
Y el amor me hace mujer.

«Venida á España, en hábito de varón, solicitó y obtuvo, en


premio de «sus servicios y largas peregrinaciones y hechos
valerosos», un entretenimiento de setenta pesos, de á veintidós
quilates, al mes, en la ciudad de Cartagena de Indias, y una ayuda
de costa para el viaje.» Diríase que ya no sabía vivir lejos de la tierra
americana, teatro de sus hazañas, tumba de sus cenizas.
Omito algunos otros pormenores de su vida, por considerarlos de
secundaria importancia para el conocimiento de esta heroína
excepcional, única en su siglo y en los anales de España, cuya
verdadera historia concluyó el día en que se vió forzada á cerrar el
ciclo de sus aventuras con la revelación de su sexo.

Вам также может понравиться