100% found this document useful (2 votes)
14 views

Java in a Nutshell: A Desktop Quick Reference Benjamin Evans - Quickly download the ebook to never miss any content

The document provides information about the book 'Java in a Nutshell: A Desktop Quick Reference' by Benjamin J. Evans, which serves as a comprehensive reference for Java programming, covering the latest Java 17 features and concepts. It includes chapters on Java syntax, object-oriented programming, memory management, and more, designed for both beginners and experienced developers. Additionally, it offers links to download the book and other related digital products instantly.

Uploaded by

sefyantholin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
14 views

Java in a Nutshell: A Desktop Quick Reference Benjamin Evans - Quickly download the ebook to never miss any content

The document provides information about the book 'Java in a Nutshell: A Desktop Quick Reference' by Benjamin J. Evans, which serves as a comprehensive reference for Java programming, covering the latest Java 17 features and concepts. It includes chapters on Java syntax, object-oriented programming, memory management, and more, designed for both beginners and experienced developers. Additionally, it offers links to download the book and other related digital products instantly.

Uploaded by

sefyantholin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

Read Anytime Anywhere Easy Ebook Downloads at ebookmeta.

com

Java in a Nutshell: A Desktop Quick Reference


Benjamin Evans

https://ebookmeta.com/product/java-in-a-nutshell-a-desktop-
quick-reference-benjamin-evans/

OR CLICK HERE

DOWLOAD EBOOK

Visit and Get More Ebook Downloads Instantly at https://ebookmeta.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Java in a Nutshell: A Desktop Quick Reference Benjamin J.


Evans

https://ebookmeta.com/product/java-in-a-nutshell-a-desktop-quick-
reference-benjamin-j-evans/

ebookmeta.com

Java in a Nutshell, 8th Edition Benjamin J. Evans

https://ebookmeta.com/product/java-in-a-nutshell-8th-edition-benjamin-
j-evans/

ebookmeta.com

Java in a Nutshell, 8th Edition (Third Early Release)


Benjamin J. Evans

https://ebookmeta.com/product/java-in-a-nutshell-8th-edition-third-
early-release-benjamin-j-evans/

ebookmeta.com

The How and Wow of Teaching Quick Ideas for Mastering Any
Classroom Situation Effectively Efficiently and
Enthusiastically 1st Edition Kathy Paterson
https://ebookmeta.com/product/the-how-and-wow-of-teaching-quick-ideas-
for-mastering-any-classroom-situation-effectively-efficiently-and-
enthusiastically-1st-edition-kathy-paterson/
ebookmeta.com
Ethereally Tainted A Dark Thriller Romance Tainted Souls
Book 1 1st Edition Rainelyn

https://ebookmeta.com/product/ethereally-tainted-a-dark-thriller-
romance-tainted-souls-book-1-1st-edition-rainelyn/

ebookmeta.com

Supply Chain Logistics Management, 6th Edition Donald J.


Bowersox

https://ebookmeta.com/product/supply-chain-logistics-management-6th-
edition-donald-j-bowersox/

ebookmeta.com

Stata A Really Short Introduction 1st Edition Felix


Bittmann

https://ebookmeta.com/product/stata-a-really-short-introduction-1st-
edition-felix-bittmann/

ebookmeta.com

English Japanese Conversation Dictionary Classic Reprint


1st Edition Arthur Rose-Innes

https://ebookmeta.com/product/english-japanese-conversation-
dictionary-classic-reprint-1st-edition-arthur-rose-innes/

ebookmeta.com

Specialty Imaging Hepatobiliary and Pancreas 1st Edition M


D Federle Michael P M D Jeffrey R Brooke M D Tublin
Mitchell E M D Borhani Amir A
https://ebookmeta.com/product/specialty-imaging-hepatobiliary-and-
pancreas-1st-edition-m-d-federle-michael-p-m-d-jeffrey-r-brooke-m-d-
tublin-mitchell-e-m-d-borhani-amir-a/
ebookmeta.com
Buckminster Fuller s World Game and Its Legacy 1st Edition
Timothy Stott

https://ebookmeta.com/product/buckminster-fuller-s-world-game-and-its-
legacy-1st-edition-timothy-stott/

ebookmeta.com
Java in a Nutshell
A Desktop Quick Reference

EIGHTH EDITION

Benjamin J. Evans, Jason Clark, and David


Flanagan
Java in a Nutshell, Eighth Edition
by Benjamin J. Evans, Jason Clark, and David Flanagan
Copyright © 2023 Benjamin J. Evans and Jason Clark. All rights
reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North,
Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales
promotional use. Online editions are also available for most titles
(http://oreilly.com). For more information, contact our
corporate/institutional sales department: 800-998-9938 or
corporate@oreilly.com.

Acquisitions Editors: Brian Guerin and


Zan McQuade

Development Editor: Melissa Potter

Production Editor: Ashley Stussy

Copyeditor: Piper Editorial Consulting, LLC

Proofreader: Amnet Systems, LLC

Indexer: WordCo Indexing Services, Inc.

Interior Designer: David Futato

Cover Designer: Karen Montgomery

Illustrator: Kate Dullea

February 2023: Eighth Edition


Revision History for the Eighth Edition
2023-02-14: First Release

See http://oreilly.com/catalog/errata.csp?isbn=9781098131005 for


release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc.
Java in a Nutshell, the cover image, and related trade dress are
trademarks of O’Reilly Media, Inc.
The views expressed in this work are those of the authors, and do
not represent the publisher’s views. While the publisher and the
authors have used good faith efforts to ensure that the information
and instructions contained in this work are accurate, the publisher
and the authors disclaim all responsibility for errors or omissions,
including without limitation responsibility for damages resulting from
the use of or reliance on this work. Use of the information and
instructions contained in this work is at your own risk. If any code
samples or other technology this work contains or describes is
subject to open source licenses or the intellectual property rights of
others, it is your responsibility to ensure that your use thereof
complies with such licenses and/or rights.
978-1-098-13100-5
[LSI]
Dedication
This book is dedicated to all who teach peace and resist violence.
Foreword
A lot can happen in four years.
This is as true of programming languages as it is of anything else.
Java 11, the first post-8 Java release with long-term support, arrived
in September 2018 and the seventh edition of Java in a Nutshell
came out a few months later.
Since then, both the wider world and the Java ecosystem have seen
major upheavals that were largely unpredictable at that time.
The new release cadence, of a LTS release every three years (now
changed to every two years), has found favor with the Java
ecosystem—very few companies have chosen to adopt the interim,
feature releases, and instead everyone prefers to stay on an upgrade
path where only the LTS releases are productionized.
Java 11 has proved to be an excellent release and a worthy
successor to the now-legacy Java 8.
With the release of Java 17, the language has moved forward yet
again, with new features such as switch expressions and the
introduction of Java’s version of algebraic data types, in the form of
records and sealed types.
Java performance continues to improve, and Java 17 is the fastest
release yet.
In all, this is a great time to be joining (or returning to) application
development in Java. Looking forward, the future holds some major
changes that will alter the character of Java development in
fundamental ways.
The next year or two will start to see these changes arrive and
become part of the Java developer’s everyday experience.
Once again, in working on this new edition of a classic text, if we
have preserved the feel of Java in a Nutshell, while updating it to
bring it to the attention of a new generation of developers, then we
shall be well satisfied.

Ben Evans, Barcelona, Spain, 2022 Jason Clark, Portland,


Oregon (& Barcelona, Spain), 2022
Preface

This book is a desktop Java reference, designed to sit faithfully by


your keyboard while you program. Part I, “Introducing Java” is a
fast-paced, “no-fluff” introduction to the Java programming language
and the core runtime aspects of the Java platform. Part II, “Working
with the Java Platform” is a reference section that blends elucidation
of core concepts with examples of important core APIs. The book
covers Java 17, but we recognize that some shops may not have
adopted it yet—so where possible we call out if a feature was
introduced after Java 8. We use Java 17 syntax throughout,
including var and lambda expressions.

Changes in the Eighth Edition


The seventh edition of this book covers Java 11, whereas this edition
covers Java 17. However, the release process of Java changed
significantly with the arrival of Java 9, and certain releases of Java
are now badged as long-term support (LTS) releases. So, Java 17 is
the next LTS release of Java after Java 11.
With the eighth edition we have tried to update the concept of what
it means to be a “Nutshell” guide. The modern Java developer needs
to know more than just syntax and APIs. As the Java environment
has matured, such topics as concurrency, object-oriented design,
memory, and the Java type system have all grown in importance for
all developers.
In this edition, we have taken the approach that only the most
recent versions of Java are likely to be of interest to the majority of
Java developers, so we usually only call out when new features
arrived after Java 8.
For example, the module system (that arrived with Java 9) is still
likely to be new for at least some developers, and it represents a
major change. However, it is also something of an advanced topic
and is in someways separate from the rest of the language, so we
have restricted our treatment of it to a single chapter.

Contents of This Book


The first six chapters document the Java language and the Java
platform—they should all be considered essential reading. The book
is biased toward the Oracle/OpenJDK (Open Java Development Kit)
implementation of Java but not greatly so. Developers working with
other Java environments will still find plenty to occupy them. Part I
includes:
Chapter 1, “Introduction to the Java Environment”
This chapter is an overview of the Java language and the Java
platform. It explains the important features and benefits of Java,
including the lifecycle of a Java program. We also touch on Java
security and answer some criticisms of Java.

Chapter 2, “Java Syntax from the Ground Up”


This chapter explains the details of the Java programming
language, including the Java 8 language changes. It is a long and
detailed chapter that does not assume substantial programming
experience. Experienced Java programmers can use it as a
language reference. Programmers with substantial experience
with languages such as C and C++ should be able to pick up
Java syntax quickly by reading this chapter; beginning
programmers with only a modest amount of experience should
be able to learn Java programming by studying this chapter
carefully, although it is best read in conjunction with an
introductory text (such as O’Reilly’s Head First Java by Kathy
Sierra, Bert Bates, and Trisha Gee).
Chapter 3, “Object-Oriented Programming in Java”
This chapter describes how the basic Java syntax documented in
Chapter 2 is used to write simple object-oriented programs using
classes and objects in Java. The chapter assumes no prior
experience with object-oriented programming. It can be used as
a tutorial by new programmers or as a reference by experienced
Java programmers.

Chapter 4, “The Java Type System”


This chapter builds on the basic description of object-oriented
programming in Java and introduces the other aspects of Java’s
type system, such as generic types, enumerated types, and
annotations. With this more complete picture, we can discuss the
biggest change in Java 8—the arrival of lambda expressions.

Chapter 5, “Introduction to Object-Oriented Design in Java”


This chapter is an overview of some basic techniques used in the
design of sound object-oriented programs, and it briefly touches
on the topic of design patterns and their use in software
engineering.

Chapter 6, “Java’s Approach to Memory and Concurrency”


This chapter explains how the Java Virtual Machine manages
memory on behalf of the programmer, and how memory and
visibility are intimately entwined with Java’s support for
concurrent programming and threads.

These first six chapters teach you the Java language and get you up
and running with the most important concepts of the Java platform.
Part II is all about how to get real programming work done in the
Java environment. It contains plenty of examples and is designed to
complement the cookbook approach found in some other texts. This
part includes:
Chapter 7, “Programming and Documentation Conventions”
This chapter documents important and widely adopted Java
programming conventions. It also explains how you can make
your Java code self-documenting by including specially formatted
documentation comments.

Chapter 8, “Working with Java Collections”


This chapter introduces Java’s standard collections libraries.
These contain data structures that are vital to the functioning of
virtually every Java program—such as List, Map, and Set. The
new Stream abstraction and the relationship between lambda
expressions and the collections are explained in detail.

Chapter 9, “Handling Common Data Formats”


This chapter discusses how to use Java to work effectively with
very common data formats, such as text, numbers, and temporal
(date and time) information.

Chapter 10, “File Handling and I/O”


This chapter covers several different approaches to file access—
from the more classic approach found in older versions of Java,
to more modern and even asynchronous styles. The chapter
concludes with a short introduction to networking with the core
Java platform APIs.

Chapter 11, “Classloading, Reflection, and Method Handles”


This chapter introduces the subtle art of metaprogramming in
Java—first introducing the concept of metadata about Java types,
then turning to the subject of classloading and how Java’s
security model is linked to the dynamic loading of types. The
chapter concludes with some applications of classloading and the
relatively new feature of method handles.
Chapter 12, “Java Platform Modules”
This chapter describes Java Platform Module System (JPMS), the
major feature that was introduced as part of Java 9, and provides
an introduction to the wide-ranging changes that it brings.

Chapter 13, “Platform Tools”


Oracle’s JDK (as well as OpenJDK) includes a number of useful
Java development tools, most notably the Java interpreter and
the Java compiler. This chapter documents those tools, as well as
the jshell interactive environment and new tools for working
with modular Java.

Appendix
This appendix covers Java beyond version 17, including the
releases Java 18 and 19 as well as ongoing research and
development projects to enhance the language and JVM.

Related Books
O’Reilly publishes an entire series of books on Java programming,
including several companion books to this one:
Learning Java by Patrick Niemeyer and Daniel Leuck
This book is a comprehensive tutorial introduction to Java and
includes topics such as XML and client-side Java programming.

Java 8 Lambdas by Richard Warburton


This book documents the new Java 8 feature of lambda
expressions in detail and introduces concepts of functional
programming that may be unfamiliar to Java developers coming
from earlier versions.
Head First Java by Kathy Sierra, Bert Bates, and Trisha Gee
This book uses a unique approach to teaching Java. Developers
who think visually often find it a great accompaniment to a
traditional Java book.

You can find a complete list of Java books from O’Reilly at


http://java.oreilly.com.

Conventions Used in This Book


The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file
extensions.

Constant width
Used for program listings, as well as within paragraphs to refer to
program elements such as variable or function names, databases,
data types, environment variables, statements, and keywords.

Constant width bold


Shows commands or other text that should be typed literally by
the user.

Constant width italic


Shows text that should be replaced with user-supplied values or
by values determined by context.
TIP
This element signifies a tip or suggestion.

NOTE
This element signifies a general note.

WARNING
This element indicates a warning or caution.

Using Code Examples


Supplemental material (code examples, exercises, etc.) is available
for download at https://github.com/kittylyst/javanut8.
If you have a technical question or a problem using the code
examples, please send an email to bookquestions@oreilly.com.
This book is here to help you get your job done. In general, if
example code is offered with this book, you may use it in your
programs and documentation. You do not need to contact us for
permission unless you’re reproducing a significant portion of the
code. For example, writing a program that uses several chunks of
code from this book does not require permission. Selling or
distributing examples from O’Reilly books does require permission.
Answering a question by citing this book and quoting example code
does not require permission. Incorporating a significant amount of
example code from this book into your product’s documentation
does require permission.
We appreciate, but generally do not require, attribution. An
attribution usually includes the title, author, publisher, and ISBN. For
example: “Java in a Nutshell, Eighth Edition by Ben Evans, Jason
Clark, and David Flanagan (O’Reilly). Copyright 2023 Benjamin J.
Evans and Jason Clark, 978-1-098-13100-5.”
If you feel your use of code examples falls outside fair use or the
permission given above, feel free to contact us at
permissions@oreilly.com.

O’Reilly Online Learning

NOTE
For more than 40 years, O’Reilly Media has provided technology and business
training, knowledge, and insight to help companies succeed.

Our unique network of experts and innovators share their knowledge


and expertise through books, articles, and our online learning
platform. O’Reilly’s online learning platform gives you on-demand
access to live training courses, in-depth learning paths, interactive
coding environments, and a vast collection of text and video from
O’Reilly and 200+ other publishers. For more information, visit
https://oreilly.com.

How to Contact Us
Please address comments and questions concerning this book to the
publisher:

O’Reilly Media, Inc.

1005 Gravenstein Highway North


Sebastopol, CA 95472

800-998-9938 (in the United States or Canada)

707-829-0515 (international or local)

707-829-0104 (fax)

We have a web page for this book, where we list errata, examples,
and any additional information. You can access this page at
https://oreil.ly/java-in-a-nutshell-8e.
Email bookquestions@oreilly.com to comment or ask technical
questions about this book.
For news and information about our books and courses, visit
https://oreilly.com.
Find us on LinkedIn: https://linkedin.com/company/oreilly-media
Follow us on Twitter: https://twitter.com/oreillymedia
Watch us on YouTube: https://youtube.com/oreillymedia

Acknowledgments
Melissa Potter was the editor of the eighth edition. Her guidance and
many useful contributions were a great help throughout the process.
Special thanks are due to Dan Heidinga, Ashutosh Mehra, and
Aleksey Shipilëv.
Our technical reviewers for this edition were Mario Torre, Tony
Mancill, Achyut Madhusudan, Jeff Maury, Rui Vieira, Jeff Alder, Kevin
Earls, and Ashutosh Mehra.
Part I. Introducing Java

Part I is an introduction to the Java language and the Java platform.


These chapters provide enough information for you to get started
using Java right away:

Chapter 1, “Introduction to the Java Environment”

Chapter 2, “Java Syntax from the Ground Up”

Chapter 3, “Object-Oriented Programming in Java”

Chapter 4, “The Java Type System”

Chapter 5, “Introduction to Object-Oriented Design in Java”

Chapter 6, “Java’s Approach to Memory and Concurrency”


Chapter 1. Introduction to the
Java Environment

Welcome to Java in 2023.


You may be coming to the Java world from another tradition, or
maybe this is your first taste of computer programming. Whatever
road you may have traveled to get here, welcome—​we’re glad you’ve
arrived.
Java is a powerful, general-purpose programming environment. It is
one of the most widely used programming environments in the
world and has been exceptionally successful in business and
enterprise computing for over 25 years.
In this chapter, we’ll set the scene by describing the Java language
(which programmers write their applications in), the Java execution
environment (known as the “Java Virtual Machine,” which actually
runs those applications), and the Java ecosystem (which provides a
lot of the value of the programming environment to development
teams).
All three of these concepts (language, execution environment, and
ecosystem) are habitually referred to just as “Java,” with the precise
usage inferred from context. In practice, they are such connected
ideas that this isn’t as confusing as it might first seem.
We’ll briefly cover the history of the Java language and virtual
machine, move on to discuss the lifecycle of a Java program, and
then clear up some common questions about the differences
between Java and other environments.
The Language, the JVM, and the Ecosystem
The base Java programming environment has been around since the
late 1990s. It is composed of the Java language and the supporting
runtime, the Java Virtual Machine (JVM). The third leg—the Java
ecosystem beyond the standard library that ships with Java—is
provided by third parties, such as open-source projects and Java
technology vendors.
At the time that Java was initially developed, this split was
considered novel, but trends in software development in the
intervening years have made it more commonplace. Notably,
Microsoft’s .NET environment, announced a few years after Java,
adopted a very similar approach to platform architecture.
One important difference between Microsoft’s .NET platform and
Java is that Java was always conceived as a relatively open
ecosystem of multiple vendors, albeit led by a steward who owns the
technology. Throughout Java’s history, these vendors have both
cooperated and competed on aspects of Java technology.
One of the main reasons for Java’s success is that this ecosystem is
a standardized environment. This means there are specifications for
the technologies that comprise the environment. These standards
give the developer and consumer confidence that the technology will
be compatible with other components, even if they come from a
different technology vendor.
The current steward of Java is Oracle Corporation (which acquired
Sun Microsystems, the originator of Java). Other corporations, such
as Red Hat, IBM, Amazon, Microsoft, AliBaba, SAP, Azul Systems,
and Bellsoft, are also involved in producing implementations of
standardized Java technologies.
TIP
From Java 7 onwards, the reference implementation of Java is the open source
OpenJDK (Java Development Kit), which many of these companies collaborate
on and base their shipping products upon.

Java was originally composed of several different, but related,


environments and specifications, such as Java Mobile Edition (Java
ME),1 Java Standard Edition (Java SE), and Java Enterprise Edition
(Java EE).2 In this book, we’ll only cover Java SE, version 17, with
some historical notes related to when certain features were
introduced into the platform. Generally speaking, if someone says
“Java” without any further clarification, they usually mean Java SE.
We will have more to say about standardization later, so let’s move
on to discuss the Java language and JVM as separate but related
concepts.

What Is the Java Language?


Java programs are written as source code in the Java language. This
is a human-readable programming language, which is strictly class
based and object-oriented. The language syntax is deliberately
modeled on that of C and C++, and it was explicitly intended to be
familiar to programmers coming from those languages, which were
very dominant languages at the time Java was created.

NOTE
Although the source code is similar to C++, in practice Java includes features
and a managed runtime that has much more in common with dynamic
languages such as Smalltalk.
Java is considered to be relatively easy to read and write (if
occasionally a bit verbose). It has a rigid grammar and simple
program structure and is intended to be easy to learn and to teach.
It is built on industry experience with languages like C++ and tries
to remove complex features as well as preserving “what works” from
previous programming languages.
The Java language is governed by the Java Language Specification
(JLS), which defines how a conforming implementation must
behave.
Overall, Java is intended to provide a stable, solid base for
companies to develop business-critical applications. As a
programming language, it has a relatively conservative design and a
slow rate of change. These properties are a conscious attempt to
serve the goal of protecting the investment that organizations have
made in Java technology.
The language has undergone gradual revision (but no complete
rewrites) since its inception in 1996. This does mean that some of
Java’s original design choices, which were expedient in the late
1990s, are still affecting the language today—see Chapters 2 and 3
for more details.
On the other hand, in the last 10 or so years, Java has modernized
its language syntax somewhat, to address concerns about verbosity
and provide features more familiar to programmers coming from
other popular languages.
For example, in 2014, Java 8 added the most radical changes seen in
the language for almost a decade. Features like lambda expressions
and the introduction of the Streams API were enormously popular
and changed forever the way that Java developers write code.
As we’ll discuss later in this chapter, the Java project has transitioned
to a new release model. In this new model Java versions are
released every 6 months but only certain versions (8, 11, and 17)
are considered eligible for LTS. All other versions are supported for
only 6 months and have not seen widespread adoption by
development teams.

What Is the JVM?


The JVM is a program that provides the runtime environment
necessary for Java programs to execute. Java programs cannot run
unless there is a JVM available for the appropriate hardware and OS
platform we wish to execute on.
Fortunately, the JVM has been ported to run on a large number of
hardware environments—anything from a set-top box or Blu-ray
player to a huge mainframe will probably have a JVM available for it.
The JVM has its own specification, the Java Virtual Machine
Specification, and every implementation must conform to the rules
of the specification. When new hardware types arrive in the
mainstream market then it is likely that companies or individuals
interested in the hardware will start a project to port OpenJDK to the
new chip. A recent example of this was the new Apple M1 chip—Red
Hat ported the JVM to the AArch64 architecture and then Microsoft
ported the build changes needed to build on Apple’s silicon.
Java programs can be started in several ways, but the simplest (and
oldest) method is to start from a command line:

java <arguments> <program name>

This brings up the JVM as an operating system process that provides


the Java runtime environment and then executes our program in the
context of the freshly started (and empty) virtual machine.
It is important to understand that when the JVM takes in a Java
program for execution, the program is not provided as Java
language source code. Instead, the Java language source must be
compiled into a form known as Java bytecode. Java bytecode is then
supplied to the JVM in a format called class files (which always have
a .class extension). The Java platform has always emphasized
backward compatibility, and code written for Java 1.0 will still run on
today’s JVMs without modification or recompilation.
The JVM provides an execution environment for the program. It
starts an interpreter for the bytecode form of the program that steps
through one bytecode instruction at a time. However, production-
quality JVMs also provide a special compiler that operates while the
Java program is running. This compiler (known as a “JIT” or just-in-
time) will accelerate the important parts of the program by replacing
them with equivalent compiled (and heavily optimized) machine
code.
You should also be aware that both the JVM and the user program
are capable of spawning additional threads of execution, so that a
user program may have many different functions running
simultaneously.
The original design of the JVM was built on many years of
experience with earlier programming environments, notably C and
C++, so we can think of it as having several different goals—all
intended to make life easier for the programmer:
Comprise a standard execution environment for application code
to run inside
Facilitate secure and reliable code execution (as compared to
C/C++)
Take low-level memory management out of the hands of
developers
Provide a cross-platform execution environment
These objectives are often mentioned together in discussions of the
platform.
We’ve already mentioned the first of these goals, when we discussed
the JVM and its bytecode interpreter—it functions as the container
for application code.
We’ll discuss the second and third goals in Chapter 6, when we talk
about how the Java environment deals with memory management.
The fourth goal, sometimes called “write once, run anywhere”
(WORA), is the property that Java class files can be moved from one
execution platform to another, and they will run unaltered provided a
JVM is available.
This means that a Java program can be developed (and converted to
class files) on a machine running macOS on an M1 chip, and then
the class files can be moved to Linux or Microsoft Windows on Intel
hardware (or other platforms) and the Java program will run without
any further work needed.

NOTE
The Java environment has been very widely ported, including to platforms that
are very different from mainstream platforms like Linux, macOS, and Windows.
In this book, we use the phrase “most implementations” to indicate those
platforms that the majority of developers are likely to encounter; macOS,
Windows, Linux, BSD Unix, and the like are all considered “mainstream
platforms” and count within “most implementations.”

In addition to these four primary goals, there is another aspect of


the JVM’s design that is not always recognized or discussed—it uses
runtime information to self-manage.
Software research in the 1970s and 1980s revealed that the runtime
behavior of programs has a large number of interesting and useful
patterns that cannot be deduced at compile time. The JVM was the
first truly mainstream programming environment to use the results
of this research.
It collects runtime information to make better decisions about how
to execute code. That means that the JVM can monitor and optimize
a program running on it in a manner not possible for platforms
without this capability.
A key example is the runtime fact that not all parts of a Java
program are equally likely to be called during the lifetime of the
program—some portions will be called far, far more often than
others. The Java platform takes advantage of this fact with a
technology called just-in-time (JIT) compilation.
In the HotSpot JVM (which was the JVM that Sun first shipped as
part of Java 1.3, and is still in use today), the JVM first identifies
which parts of the program are called most often—the “hot
methods.” Then the JVM compiles these hot methods directly into
machine code, bypassing the JVM interpreter.
The JVM uses the available runtime information to deliver higher
performance than would be possible from purely interpreted
execution. In fact, the optimizations that the JVM uses now in many
cases produce performance that surpasses compiled C and C++
code.
The standard that describes how a properly functioning JVM must
behave is called the JVM Specification.

What Is the Java Ecosystem?


The Java language is easy to learn and contains relatively few
abstractions, compared to other programming languages. The JVM
provides a solid, portable, high-performance base for Java (or other
languages) to execute on. Taken together, these two connected
technologies provide a foundation that businesses can feel confident
about when choosing where to base their development efforts.
The benefits of Java do not end there, however. Since Java’s
inception, an extremely large ecosystem of third-party libraries and
components has grown up. This means that a development team
can benefit hugely from the existence of connectors and drivers for
practically every technology imaginable—both proprietary and open
source.
In the modern technology ecosystem, it is now rare indeed to find a
technology component that does not offer a Java connector. From
traditional relational databases, to NoSQL, to every type of
enterprise monitoring system, to messaging systems, to Internet of
Things (IoT)—everything integrates with Java.
It is this fact that has been a major driver of adoption of Java
technologies by enterprises and larger companies. Development
teams have been able to unlock their potential by making use of
preexisting libraries and components. This has promoted developer
choice and encouraged open, best-of-breed architectures with Java
technology cores.

NOTE
Google’s Android environment is sometimes thought of as being “based on
Java.” However, the picture is actually rather more complicated. Android code is
written in Java (or the Kotlin language) but originally used a different
implementation of Java’s class libraries along with a cross compiler to convert to
a different file format for a non-Java virtual machine.

The combination of a rich ecosystem and a first-rate virtual machine


with an open standard for program binaries makes the Java platform
a very attractive execution target. In fact, there are a large number
of non-Java languages that target the JVM and also interoperate
with Java (which allows them to piggyback off the platform’s
success). These languages include Kotlin, JRuby, Scala, Clojure, and
many others. While all of them are small compared to Java, they
have distinct niches within the Java world and provide a source of
innovation and healthy competition to Java.
The Lifecycle of a Java Program
To better understand how Java code is compiled and executed, and
the difference between Java and other types of programming
environments, consider the pipeline in Figure 1-1.

Figure 1-1. How Java code is compiled and loaded

This starts wth Java source and passes it through the javac
program to produce class files—which contain the source code
compiled to Java bytecode. The class file is the smallest unit of
functionality the platform will deal with and the only way to get new
code into a running program.
New class files are onboarded via the classloading mechanism (see
Chapter 10 for a lot more detail on how classloading works). This
makes the new code (represented as a type) available to the
interpreter for execution, and execution begins in the main()
method.
The performance analysis and optimization of Java program is a
major topic, and interested readers should consult a specialist text,
such as Optimizing Java (O’Reilly).
Frequently Asked Questions
In this section, we’ll discuss some of the most frequently asked
questions about Java and the lifecycle of programs written in the
Java environment.

What is a virtual machine?


When developers are first introduced to the concept of a virtual
machine, they sometimes think of it as “a computer inside a
computer” or “a computer simulated in software.” It’s then easy to
imagine bytecode as “machine code for the CPU of the internal
computer” or “machine code for a made-up processor.” However, this
simple intuition can be misleading.

What is bytecode?
In fact, JVM bytecode is actually not very similar to machine code
that would run on a real hardware processor. Instead, computer
scientists would call bytecode a type of intermediate representation
—a halfway house between source code and machine code.

Is javac a compiler?
Compilers usually produce machine code, but javac produces
bytecode, which is not that similar to machine code. However, class
files are a bit like object files (like Windows .dll files, or Unix .so
files)—and they are certainly not human readable.
In theoretical computer science terms, javac is most similar to the
front half of a compiler—it creates the intermediate representation
that can then be used later to produce (emit) machine code.
However, because creation of class files is a separate build-time step
that resembles compilation in C/C++, many developers consider
running javac to be compilation. In this book, we will use the terms
“source code compiler” or "javac compiler” to mean the production
of class files by javac.
We will reserve “compilation” as a standalone term to mean JIT
compilation—as it’s JIT compilation that actually produces machine
code.

Why is it called “bytecode”?


The instruction code (opcode) is just a single byte (some operations
also have parameters that follow them in the bytestream), so there
are only 256 possible instructions. In practice, some are unused—
about 200 are in use, but some of them aren’t emitted by recent
versions of javac.

Is bytecode optimized?
In the early days of the platform, javac produced heavily optimized
bytecode. This turned out to be a mistake.
With the advent of JIT compilation, the important methods are going
to be compiled to very fast machine code. It’s therefore very
important to make the job of the JIT compiler easier—as there are
much bigger gains available from JIT compilation than there are
from optimizing bytecode, which will still have to be interpreted.

Is bytecode really machine independent? What about things


like endianness?
The format of bytecode is always the same, regardless of what type
of machine it was created on. This includes the byte ordering
(sometimes called “endianness”) of the machine. For readers who
are interested in the details, bytecode is always big-endian.

Is Java an interpreted language?


The JVM is basically an interpreter (with JIT compilation to give it a
big performance boost). However, most interpreted languages
directly interpret programs from source form (usually by constructing
an abstract syntax tree from the input source file). The JVM
interpreter, on the other hand, requires class files—which, of course,
require a separate source code compilation step with javac.
In fact, the modern version of many languages that were
traditionally interpreted (such as PHP, Ruby, and Python) now also
have JIT compilers, so the divide between “interpreted” and
“compiled” languages is increasingly blurred. Once again, Java’s
design decisions have been validated by their adoption in other
programming environments.

Can other languages run on the JVM?


Yes. The JVM can run any valid class file, so this means that non-
Java languages can run on the JVM in several ways. First, they could
have a source code compiler (similar to javac) that produces class
files, which would run on the JVM just like Java code (this is the
approach taken by languages like Kotlin and Scala).
Alternatively, a non-Java language could implement an interpreter
and runtime in Java and then interpret the source form of their
language directly. This second option is the approach taken by
languages like JRuby (but JRuby has a very sophisticated runtime
that is capable of secondary JIT compilation in some circumstances).

Comparing Java to Other Languages


In this section, we’ll briefly highlight some differences between the
Java platform and other programming environments you may be
familiar with.

Java Compared to JavaScript


Java is statically typed; JavaScript is dynamically typed.
Java uses class-based objects; JavaScript is prototype based
(the JS keyword class is syntactic sugar).
Java provides good object encapsulation; JavaScript does not.
Java has namespaces; JavaScript does not.
Java is multithreaded; JavaScript is not.

Java Compared to Python


Java is statically typed; Python is dynamically typed (with
optional, gradual typing).
Java is an OO language with functional programming (FP)
features; Python is a hybrid OO / procedural language with
some FP support.
Java and Python both have a bytecode format—Java uses JVM
class files; Python uses Python bytecode.
Java’s bytecode has extensive static checks; Python’s bytecode
does not.
Java is multithreaded; Python allows only one thread to execute
Python bytecode at once (the Global Interpreter Lock).

Java Compared to C
Java is object-oriented; C is procedural.
Java is portable as class files; C needs to be recompiled.
Java provides extensive instrumentation as part of the runtime.
Java has no pointers and no equivalent of pointer arithmetic.
Java provides automatic memory management via garbage
collection.
Java currently has no ability to lay out memory at a low level
(no structs).
Java has no preprocessor.

Java Compared to C++


Java has a simplified object model compared to C++.
Java’s method dispatch is virtual by default.
Java is always pass-by-value (but one of the only possibilities for
Java values is object references).
Java does not support full multiple inheritance.
Java’s generics are less powerful (but also less dangerous) than
C++ templates.
Java has no operator overloading.

Answering Some Criticisms of Java


Java has had a long history in the public eye and, as a result, has
attracted its fair share of criticism over the years. Some of this
negative press can be attributed to some technical shortcomings
combined with rather overzealous marketing in the first versions of
Java.
Some criticisms have, however, entered technical folklore despite no
longer being very accurate. In this section, we’ll look at some
common grumbles and the extent to which they’re true for modern
versions of the platform.

Overly Verbose
The Java core language has sometimes been criticized as overly
verbose. Even simple Java statements such as Object o = new
Object(); seem to be repetitious—the type Object appears on
both the left and right side of the assignment. Critics point out that
this is essentially redundant, that other languages do not need this
duplication of type information, and that many languages support
features (e.g., type inference) that remove it.
The counterpoint to this argument is that Java was designed from
the start to be easy to read (code is read more often than written)
and that many programmers, especially novices, find the extra type
information helpful when reading code.
Java is widely used in enterprise environments, which often have
separate dev and ops teams. The extra verbosity can often be a
blessing when you are responding to an outage call, or when you
need to maintain and patch code that was written by developers
who have long since moved on.
In recent versions of Java, the language designers have attempted
to respond to some of these points by finding places where the
syntax can become less verbose and by making better use of type
information. For example:

// Files helper methods


byte[] contents =
Files.readAllBytes(Paths.get("/home/ben/myFile.bin"));

// Diamond syntax for repeated type information


List<String> l = new ArrayList<>();

// Local variables can be type inferred


var threadPool = Executors.newScheduledThreadPool(2);

// Lambda expressions simplify Runnables


threadPool.submit(() -> { System.out.println("On
Threadpool"); });

However, Java’s overall philosophy is to make changes to the


language only very slowly and carefully, so the pace of these
changes may not satisfy detractors completely.
Slow to Change
The original Java language is now well over 20 years old and has not
undergone a complete revision in that time. Many other languages
(e.g., Microsoft’s C#) have released backward-incompatible versions
in the same period, and some developers criticize Java for not doing
likewise.
Furthermore, in recent years, the Java language has come under fire
for being slow to adopt language features that are now
commonplace in other languages.
The conservative approach to language design that Sun (and now
Oracle) has taken is an attempt to avoid imposing the costs and
externalities of misfeatures on a very large user base. Many Java
shops have made major investments in the technology, and the
language designers have taken seriously the responsibility of not
disrupting the existing user and install base.
Each new language feature needs to be very carefully thought about
—not only in isolation but in terms of how it will interact with all the
existing features of the language. New features can sometimes have
impacts beyond their immediate scope—and Java is widely used in
very large codebases, where there are more potential places for an
unexpected interaction to manifest.
It is almost impossible to remove a feature that turns out to be
incorrect after it has shipped. Java has a couple of misfeatures (such
as the serialization mechanism) that have been all-but-impossible to
remove safely without impacting the install base. The language
designers have taken the view that extreme caution is required
when evolving the language.
Having said that, the new language features that have arrived in
recent versions are a significant step toward addressing the most
common complaints about missing features, and they should cover
many of the idioms that developers have been asking for.
Performance Problems
The Java platform is still sometimes criticized for being slow—but of
all the criticisms that are leveled at the platform, this is probably the
one that is least justified. It is a genuine myth about the platform.
Release 1.3 of Java brought in the HotSpot Virtual Machine and its
JIT compiler. Since then, there have been over 15 years of continual
innovation and improvement in the virtual machine and its
performance. The Java platform is now blazingly fast, regularly
winning performance benchmarks on popular frameworks, and even
beating native-compiled C and C++.
Criticism in this area appears to be largely caused by a folk memory
that Java was slow at some point in the past. Some of the larger,
more sprawling architectures that Java has been used within may
also have contributed to this impression.
The truth is that any large architecture will require benchmarking,
analysis, and performance tuning to get the best out of it—and Java
is no exception.
The core of the platform—language and JVM—was and remains one
of the fastest general-use environments available to the developer.

Insecure
Some people have historically criticized Java’s record of security
vulnerabilities.
Many of these vulnerabilities involved the desktop and GUI
components of the Java system and wouldn’t affect websites or
other server-side code written in Java.
The truth is that Java has been designed from the ground up with
security in mind; this gives it a great advantage over many other
existing systems and platforms. The Java security architecture was
designed by security experts and has been studied and probed by
many other security experts since the platform’s inception. The
consensus is that the architecture itself is strong and robust, without
any security holes in the design (at least none that have been
discovered yet).
Fundamental to the design of the security model is that bytecode is
heavily restricted in what it can express—there is no way, for
example, to directly address memory. This cuts out entire classes of
security problems that have plagued languages like C and C++.
Furthermore, the VM goes through a process known as bytecode
verification whenever it loads an untrusted class, which removes a
further large class of problems (see Chapter 10 for more about
bytecode verification).
Despite all this, however, no system can guarantee 100% security,
and Java is no exception.
While the design is still theoretically robust, the implementation of
the security architecture is another matter, and there is a long
history of security flaws being found and patched in particular
implementations of Java. In all likelihood, security flaws will continue
to be discovered (and patched) in Java VM implementations.
All programming platforms have security issues at times, and many
other languages have a comparable history of security vulnerabilities
that have been significantly less well publicized. For practical server-
side coding, Java remains perhaps the most secure general-purpose
platform currently available, especially when kept patched up to
date.

Too Corporate
Java is a platform that is extensively used by corporate and
enterprise developers. The perception that it is too corporate is
therefore not surprising—Java has often been perceived as lacking
the “freewheeling” style of languages that are deemed to be more
community oriented.
In truth, Java has always been, and remains, a very widely used
language for community and free or open source software
development. It is one of the most popular languages for projects
hosted on GitHub and other project-hosting sites. Not only that, but
the Java community is regularly held up as one of the real strengths
of the ecosystem—with user groups, conferences, journals, and all
of the most visible signs of an active and healthy user community.
Finally, the most widely used implementation of the language itself is
based on OpenJDK—which is itself an open-source project with a
vibrant and growing community.

A Brief History of Java and the JVM


Java 1.0 (1996)
This was the first public version of Java. It contained just 212
classes organized in eight packages.

Java 1.1 (1997)


This release of Java more than doubled the size of the Java
platform. This release introduced “inner classes” and the first
version of the Reflection API.

Java 1.2 (1998)


This was a very significant release of Java; it tripled the size of
the Java platform. This release marked the first appearance of
the Java Collections API (with sets, maps, and lists). The many
new features in the 1.2 release led Sun to rebrand the platform
as “the Java 2 Platform.” The term “Java 2” was simply a
trademark, however, and not an actual version number for the
release.

Java 1.3 (2000)


This was primarily a maintenance release, focused on bug fixes,
stability, and performance improvements. This release also
brought in the HotSpot Java Virtual Machine, which is still in use
today (although heavily modified and improved since then).

Java 1.4 (2002)


This was another fairly big release, adding important new
functionality such as a higher-performance, low-level I/O API;
regular expressions for text handling; XML and XSLT libraries;
SSL support; a logging API; and cryptography support.

Java 5 (2004)
This large release of Java introduced a number of changes to the
core language itself, including generic types, enumerated types
(enums), annotations, varargs methods, autoboxing, and a new
for loop. These changes were considered significant enough to
change the major version number and to start numbering as
major releases. This release included 3,562 classes and interfaces
in 166 packages. Notable additions included utilities for
concurrent programming, a remote management framework, and
classes for the remote management and instrumentation of the
Java VM itself.

Java 6 (2006)
This release was also largely a maintenance and performance
release. It introduced the Compiler API, expanded the usage and
scope of annotations, and provided bindings to allow scripting
languages to interoperate with Java. There were also a large
number of internal bug fixes and improvements to the JVM and
the Swing GUI technology.

Java 7 (2011)
The first release of Java under Oracle’s stewardship included a
number of major upgrades to the language and platform, as well
as being the first release to be based on the Open Source
reference implementation. The introduction of try-with-
resources and the NIO.2 API enabled developers to write much
safer and less error-prone code for handling resources and I/O.
The Method Handles API provided a simpler and safer alternative
to reflection; in addition, it opened the door for invokedynamic
(the first new bytecode since version 1.0 of Java).

Java 8 (2014) (LTS)


This was a huge release—​potentially the most significant changes
to the language since Java 5 (or possibly ever). The introduction
of lambda expressions provided the ability to significantly
enhance the productivity of developers, the Collections were
updated to make use of lambdas, and the machinery required to
achieve this marked a fundamental change in Java’s approach to
object orientation. Other major updates include a new date and
time API and major updates to the concurrency libraries.

Java 9 (2017)
Significantly delayed, this release introduced the new platform
modularity feature, which allows Java applications to be
packaged into deployment units and modularize the platform
runtime. Other changes include a new default garbage collection
algorithm, a new API for handling processes, and some changes
to the way that frameworks can access the internals. This release
also changed the release cycle itself, so that new versions arrive
every 6 months, but only the LTS releases have gained traction.
Accordingly, we only record the LTS releases beyond this point.

Java 11 (September 2018) (LTS)


This release was the first modular Java to be considered as a
long-term support (LTS) release. It adds a few new features that
are directly visible to the developer—​primarily improved support
for type inference (var), JDK Flight Recorder (JFR), and the new
HTTP/2 API. There were some additional internal changes and
substantial performance improvements, but this LTS release was
primarily intended for stabilization after Java 9.

Java 17 (September 2021) (LTS)


The current version LTS release. Includes important changes to
Java’s OO model (Sealed classes, Records, and Nestmates) as
well as Switch Expressions, Text Blocks, and a first version of
language Pattern Matching. The JVM had additional performance
improvements and better support for running in containers. The
internal upgrades continued, and two new garbage collectors
were added.

As it stands, the only current production versions are the LTS


releases, 11 and 17. Due to the highly significant changes that are
introduced by modules, Java 8 was retrospectively declared to be an
LTS release to provide extra time for teams and applications to
migrate to a supported modular Java. It is now considered a
“classic” release, and teams are strongly encouraged to migrate to
one of the modern LTS versions.

Summary
In this introductory chapter, we’ve placed Java in context within the
overall landscape and history of programming languages. We’ve
compared the language to other popular alternatives, taken a first
look at the basic anatomy of how a Java program is compiled and
executed, and tried to dispel some of the popular myths about Java.
The next chapter covers Java’s language syntax—primarily from a
bottom-up perspective, focusing on the individual basic units of
lexical syntax and building upwards. If you are already familiar with
the syntax of a language similar to Java (such as JavaScript, C or
C++), you may choose to skim or skip this chapter and refer to it
when you encounter any syntax that is unfamiliar to you.

1 Java ME was an older standard for feature phones and first-generation


smartphones. Android and iOS dominate the market on phones today, and
Java ME is no longer being updated.
2 Java EE has now been transferred to the Eclipse Foundation, where it
continues its life as the Jakarta EE project.
Another Random Scribd Document
with Unrelated Content
– Ugyan, édesfiam, már minek hoztad ezt a házhoz, mikor
magunknak is alig van kenyerünk?!
– Soh’ se bántsa kend, édesszülém, annál több jószág van a
háznál, aztán majd veszek én ennek egy kis tejet!
Azzal aztán elment, vett a macskának tejet. Odaadta a kis
macskának a tejet, elment dolgozni.
A másik hetivásárig ismét tákolt össze egynéhány edényt, kivitte
s megint eladta mind. Hát jön hazafelé a pénzzel, megint meglátja a
pajtásait, odamegy hozzájok, kérdi tőlük:
– Mit csináltok, pajtás?
– Hát, nem látod, ezt a kis kutyát akarjuk agyonütni.
– Ugyan ne bántsátok szegényt, inkább adjátok nekem, adok érte
egy garast.
Vette a kutyát, vitte hazafelé; amint hazaért, meglátta az anyja,
rákiáltott:
– Hát, már meg hol vetted azt a kis kutyát?
Kis Jankó elmondta, hogy miként jutott a kutyához, mire azután
elkezdett az anyja sopánkodni:
– Ugyan édesfiam, már minek hoztad a házhoz ezt a kutyát,
mikor magunknak is alig van mit enni.
– Soh’ se bántsa, édesszülém, majd veszek én ennek egy kis
tejet, aztán majd elélősködik valahogy!
Azzal elment, vett a kutyának tejet és dolgozott tovább. Másik
héten megint kivitte az edényeit a hetivásárra, amit eddig dolgozott,
aztán megint eladta mind. Amint hazafelé ment, ismét meglátta
pajtásait, most meg már kígyót akartak agyonütni.
– Mit csináltok, pajtás?
– Hát, nem látod, hogy ezt a kis kígyót akarjuk agyonütni, e!
– Ugyan ne bántsátok, inkább adjátok nekem egy garasért!
Odaadták. Kis Jankó hazavitte a kis kígyót. Hát, amint otthon
meglátja az anyja, rákiált:
– Ugyan, édesfiam, már minek hozod azt a förtelmes állatot a
házhoz, tán bizon azt is fel akarod nevelni?
– Föl bizon, édesanyám, csak aztán ne haragudjék kend! Annál
több jószág lesz a háznál, aztán majd veszek én ennek egy kis tejet.
Azután ismét dolgozott s a jövő hetivásárra megint kivitte az
edényeit, el is adta, de amint hazafelé jött, ekkor már nem talált a
falu végén senkit, hazament! Dolgozgatott még ő azután is és úgy
tartogatta jószágait. A kígyó félesztendő mulva annyira megnyőlt,
hogy a kuczkóba nem fért többé, egyszer azután felszólította Kis
Jankót:
– Édes gazdám, ülj rám!
Kis Jankó ráült, azután a kígyó kivitte őt a falu végén levő
kocsmához és azt mondta Kis Jankónak, hogy töltessen a
kocsmárosnéval egy iccze bort! Kis Jankó megparancsolta s mikorára
a kocsmárosné megtöltötte az icczés palaczkot, akkorára a kis kígyó
megkerülte vele a fél falut, azután így szólott:
– No, édes gazdám, tartsál még félesztendeig úgy, amint eddig
tartottál; akkor megkerülöm veled a falut mire a kocsmárosné egy
iccze bort kitölt!
Ezzel hazamentek és Kis Jankó ezután még jobban tartotta a
kígyót. Ekkor már a kutyából komondor lett, még pedig akkora, hogy
egy kétéves bornyúnál nagyobb volt; a kis macskából pedig akkora
kandúr lett, mint egy félakós fazék. Ekkor azt mondta a kígyó Kis
Jankónak:
– No, édes gazdám, most ülj rám!
Kis Jankó ráült.
Ismét kimentek a falu kocsmájához, mire a kocsmárosné
megtöltötte az icczés palaczkot, akkor már rég megkerülte a kígyó
Kis Jankóval a falut.
Elindultak vándorolni. Kis Jankó ráült a kígyóra, a kutya meg a
macska pedig egyik az egyik oldalán, másik a másik oldalán nyargalt
a kígyónak.
Mentek, mentek, mendegéltek hetedhétország ellen, még az
Óperencziás-tengeren és az üveghegyeken is túl mentek, végre
elértek sűrű fákkal bekerített, hegyes-völgyes vidékre, ahol a hegy
oldala különféleképen ki volt czifrázva és lyukakkal volt tele. Minden
lyukból kövér egér kukucskált ki, az útczákon is sok egér járt
parádéba öltözve fegyveresen. Kis Jankó elcsodálkozott, nem tudta,
hogy hol van? Addig a kutya megszólított egy parádés ruhás egeret:
– Ugyan földi, mond meg nekünk, micsoda ország ez s hol
vagyunk mi most?
– Bizony, atyafi, most az egerek országában vannak kendtek; itt
mostan igen nagy dolgok vannak készülőben, polgárháború ütött ki a
királyválasztás miatt. Kettő is van, aki király akar lenni, az egyik
princz Görbicze, ennek van tulajdonképen joga a trónushoz, ennek
vagyok én is katonája, a másik princz Fortunátus, aki pártot ütött a
király ellen, hizelkedett a népnek, nagyon sokan mentek a zászlója
alá, sokkal többen vannak, mint mi.
Eközben beértek az egerek fővárosába, ahol azután Kis Jankót
elvezették a király palotájába. Az ajtó előtt egy díszruhás kövér egér
sétált föl s alá fegyverrel kezében, ez vezette be őt a király elébe;
amint bement, így szólítá meg őt a király:
– Mit keresel itt, az én országomban?
Mire Kis Jankó elmondta, hogy ő országon, világon át utazik s
megkérte a királyt, hogy eressze át békességgel az országán, de a
király azt mondta, hogy nem ereszti, ha csak előbb nem segíti princz
Fortunátus ellen őt. Nohát, Kis Jankónak mit volt tennie,
beleegyezett s másnap megütköztek princz Fortunátus seregeivel.
Kis Jankó a kutyájával meg a macskájával rettenetes pusztítást tett
az egerek közt; úgyannyira, hogy nemsokára szét volt verve az egész
sereg, sőt Kis Jankó magát Fortunátust is elfogta s fölötte rögtön
ítéletet tartottak, kivégezték. Ezután volt nagy mulatság; ettek, ittak
amennyi csak beléjök fért, Kis Jankót is tovább eresztették a
mulatság után.
Megint mentek, mendegéltek, míg végre elértek egy nagy
erdőbe, ahol addig mentek befelé, míg elértek oly helyre, ahol a
fákon mindenütt nagy lyukak voltak. A fákból iszonyú nagy macskák
jártak ki, egyik fából a másikba mentek. Kis Jankó elámult, mikor
meglátta. Egyszer csak egy nagy macska odaugrik melléjök s rájuk
kiált, hogy mit keresnek itt? Minden szószaporítás nélkül megfogta a
Kis Jankó kezét s vezetni kezdte. Kis Jankó egy ideig hagyta magát
szó nélkül vezetni, de aztán kérdezte, hova akarja vezetni.
– Jösz a király elébe! – mondja a macska – számot adsz, hogy
mit keresel itt?!
Azután mentek egy darabig, míg oly helyre értek, ahol egy nagy
tölgyfát találtak magányosan állani, körülötte nagy, zöldszemű
macska járt le s föl fegyverben. Ide vezették a Kis Jankót, mert ez
volt a macskák királyának a lakása; be is ment Kis Jankó, a kutyáját,
macskáját kívül hagyta.
Alighogy belépett, a király mindjárt kérdőre vonta; Kis Jankó
könyörgésre fogta a dolgot, hogy ők akaratlanul tévedtek ide és
semmit sem akarnak, csak keresztül-útazni a tartományon. Erre a
király áteresztette őket s így tovább vándoroltak.
Már három nap, három éjszaka útaztak, mikor egyszer csúnya
helyen találták magukat; olyan sok redves kutya közt voltak, hogy
no! Hanem itt meggyűlt a bajuk, mert a sok kutya mind rájuk rohant
és szét is tépte volna őket, ha egy szép kis tarka kutya nem ugatott
volna közöttük és csendet nem parancsolt volna. A többi kutya mind
elcsendesült, mikor a kis kutyát meglátta, mert az volt a
princzesznéjök. Kis Jankóék csak bámultak és nem tudták mire vélni
a dolgot; hanem most a princzeszné Kis Jankó kutyájának a nyakába
borult, össze-vissza csókolta:
– Ó, édes, kedves bátyám, hol voltál eddig? hol növekedtél fel
ilyen szépen? már azt gondoltam, hogy rég elvesztél!
Persze, volt azután vendégség, hogy a princzeszt megtalálták;
egész hétig mulattak Kis Jankóék, úgy folytatták tovább útjokat.
Mentek, mendegéltek, hát egyszer csak előttök egy nagy
üveghegy áll; no most ezen hogy menjenek keresztül?
Eszébe jutott Kis Jankónak a síp, amit princz Görbiczétől kapott,
azonnal megfujta, hát mindjárt ott termett egy kis egér, egy kis
skatulyát adott Kis Jankónak és eltűnt. Kis Jankó kinyitotta a
skatulyát, hát sok, kis, apró hegyesvégű garádicsot talált benne meg
egy kis kalapácsot; hirtelen beverték az üveghegybe és felmásztak rá
szerencsésen.
Mikor felértek, a kígyó így szólott Kis Jankóhoz:
– Édes gazdám, látod amott azt a szép palotát, az az én
atyámnak, a kígyók királyának a palotája, mert ez itt a kígyók
országa!
Bezzeg láttak ám itt sok szép bőrű, tarka kígyót, szinte örült bele
a lelkük. Azután bementek a palotába, a kígyó bemutatta Kis Jankót
az apjának, aki mikor megtudta, hogy ő nevelte fel a fiát, nagyon
megörült s azt mondta Kis Jankónak, kívánjon tőle akármit, mindent
meg fog neki adni! de Kis Jankónak a kígyója már megmondta, hogy
semmit se kívánjon tőle mást, mint azt a gyűrűt, amelyik az apjának
a kis ujján van, mert az olyan gyűrű, hogy ha annak a kövibe néz az
ember, mindene van, amit csak ki tud gondolni. Azért hát csak azt
kívánta Kis Jankó a kígyók királyától, az pedig azt mondta:
– Minek az neked, inkább kívánj mást, aminek több hasznát
veheted! Adok annyi aranyat, amennyit tizenkét esztendeig tizenkét
nyolczökrös szekérrel el bírsz tőlem hordani!
De Kis Jankónak semmi sem kellett, csak a gyűrű. Amikor ezt
látta a kígyókirály, odaadta neki a gyűrűt.
Együtt mulattak még egy ideig, azután hazakisérte őt a kígyó a
kutyával s macskával együtt.
Nem sok időre az anyja meghalt, még meg nem halt, azt mondta
az édesanyjának:
– Édesanyám, én meg akarok házasodni, menjen és kérje meg
nekem feleségül a király leányát!
– Ó, édes fiam, hogy gondolhatsz olyant, hogy a király adja
neked a leányát feleségül, hiszen mi oly szegények vagyunk, hogy
alig van megevő falatunk és egy szem búzánk sincs!
– Dehogy nincs! – Azzal elővette gyűrűjét, belenézett, mindjárt
mengjelent neki tizenkét, fekete Lélek és így szólt az egyik:
– Mit kívánsz tőlünk, jó urunk?
Mire Kis Jankó felelt:
– Azt parancsolom, hogy tüstént annyi búzát teremtsetek a
házamba, hogy még a szeg lyuka is tele legyen!
Ekkor a Lelkek eltűntek s úgy szaporodott a búza, hogy Kis
Jankóéknak ki kellett menni a házból.
Azután Kis Jankó megint előhivatta a Lelkeket és megparancsolta
nekik, hogy egy kétvékás nagyságú aranycsészébe hozzanak neki
mindenféle drágaköveket, gyémántokat és egyéb drágaságokat.
Ezzel azután elküldte édesanyját megkérni a király leányát. Mikor
beért a király rezidencziájába, minden ajtónállónak egy-egy drága
gyémántot kellett adni, hogy beeresszék. Amint bement a király elé,
mindjárt elmondta, hogy mi járatban van és odaadta az ajándékot.
A király elbámult a sok drágaságon, de mindjárt nem akarta
odaadni neki a leányát, hanem meg akarta próbálni, hogy milyen
gazdag az, aki ily sok drágaságot bír ajándékozni, azért azt mondta
Kis Jankó anyjának:
– Tudja kend mit, én odaadom a leányomat a kend fiának
feleségül, de csak úgy, ha ezen az éjszakán az enyémnél hétszerte
szebb palotát bír magának csináltatni és onnan az én palotámig húsz
öl szélességű útat bír gyémántkövekkel kirakni és a szélét minden
három lépésre zöldelő fügefákkal beültetni, hogy minden fügefán hét
fülemile verjen; akkor odaadom a leányomat!
Ezzel Kis Jankó anyja hazament és ezt mind elmondta a fiának, a
fia pedig azt mondta:
– Az semmi baj se, édesanyám, az mind meglehet!
És azzal elővette a gyűrűt s megparancsolta a Lelkeknek, hogy
hajnalra mind, amit a király mondott, készen legyen és hogy őt az
anyjával együtt mikor ő alszik, abba a palotába tegyék át.
Már korán reggel nem tudott a király aludni, úgy vertek a
fülemilék, amin nagyon megörült a király is, a leánya is s odaadta
leányát Kis Jankónak feleségül.
Nagy lakodalmat csaptak, három esztendeig mulattak, boldogul
éltek; a király halála után az egész ország Kis Jankóra szállott.
(Ipolyi A. gyüjteményében 609. sz. Kalmár Bertalan gyüjt.
Félegyháza.)

28. Az itélő róka, a hálátlan ember és a csalfa


kígyó.
Egyszer egy ember leemelte a követ a kígyóról, a kígyó meg
akarta ölni az embert. Könyörgött az ember, hogy eressze el; de a
kígyó bírótól akarta az igazságot megnyerni.
Lóhoz mentek először, a ló azt mondta:
– Az ember hálátlan.
Az ökör hasonlóképen beszélt.
Végre elmentek a rókához, kinek az ember tyúklevest igért.
Kérdezte a róka, hogy volt a dolog? Meghallván pedig, hogy az
ember leemelte a követ a kígyóról, azt kérdezte:
– Hogy feküdt a kígyó a kő alatt?
A kígyó elmondta, de a róka természetben kivánta látni a dolgot.
A kígyó odafeküdt. A követ rátették, kérdezte a róka:
– Igy volt?!
Ráfelelték:
– Igy!
– Ha így volt, maradjon így! – mondotta a róka. A kígyó tehát
tehetetlen lett.
Akkor a róka az embertől kérte a jutalmát. Az ember hazavezette
s tyúkot akart vágatni; de a felesége felbosszankodván, egy darab
fával letörte a derekát.
(Ipolyi A. gyüjteményében 557. sz. Szluha Ágoston gyüjt. Szeged.)

29. A gyűrűcske.
(A 27. sz. változata.)
Volt egyszer egy szegény özvegyasszony, ennek volt egy lomha
fia, ki sehol sem szolgálhatott, mindenünnett hazahajtották, már
szegény anyjának magának sem volt mit ennie és ő mégis mindig a
nyakára járt ételért. Egyszer az anyja megharagudott és így szólt
fiához, ki éppen akkor a tűzhelyen lomháskodott:
– Óh, bárcsak elmennél már (– ha) a pokolba is – szolgálni!
Amint ezt mondá, felugrott lomha fia:
– Nohát elmegyek! – és elment.
Ment, mendegélt, előtalált egy vörös szakállú embert és ez volt
az Ördög, kérdi őt:
– Hát, hova mégy, úgy-e, a pokolba szolgálni?
– Bizony talán Ördögöd van, hogy eltaláltad?
– Van bizony, gyere, én elvezetlek!
Elvezette az Ördög s a pokolban szívesen látták az Ördögök és
mondták neki, más dolga nem lesz, mint három vén kanczát
zsindelyszegekkel tömni:
– Béred az lesz, amit kívánsz!
Elment a fiú a dolgát megtenni s jól megtömte a két kanczát
zsindelyszegekkel, de amikor a harmadikat kezdte tömni, ez
megszólalt:
– Óh, ne tömj engem, hiszen én a te öreganyád vagyok s
háladatos leszek, ha megkímélsz!
Nem is tömte a fiú őt többé.
Harmadik nap azt mondja neki a vén kancza:
– Most ha bemégy, azt mondják, hogy ki van az esztendőd és
hogy amit kérsz bérül, azt fogod kapni, mit kívánsz? s fognak
mindenfélét kínálni, de te mást ne kérj, mint azt a gyűrűt, amely
annak a Sánta-Ördögnek az ujján lesz, aki az asztalhoz van kötve.
Bemegy a fiú, mindjárt kérdik:
– Mit kívánsz bérül? mert az esztendőd kitölt!
– Semmit mást, – mond a fiú – mint azt a gyűrűt, ami ennek az
Ördögnek az ujján van! – s a Sánta-Ördögre mutatott, ki az asztal
lábához volt kötve.
– Óh, – kiáltottak az Ördögök – ezt a hitvány ólomgyűrűt
akarnád, miért nem inkább valami kincset?
De a fiú erősen kötődött és nem akart a kincsek felől hallani,
mert tudta, hogy ha ezt elfogadná, a másvilágon mind ganajra
változna; utoljára tehát mégis odaadták az ólomgyűrűt.
Most bement a kanczához és kérdezte, hogy most mit csináljon
ezzel az ólomgyűrűvel?
– Valahányszor azt fogod neki mondani: »Prestiny csek, pri pravaj
sa!« akkor mindjárt elő fognak jönni az Ördögök és fognak kérdezni:
»Csoksess, pane?« te pedig mit csak kívánsz, meg fog történni.
Örült a lomha, ballagott hazafelé.
Amint látta az anyja, hogy ballag hazafelé, így kiált:
– No, talán az Ördögök hoztak, de hamar kiszolgáltál!
– Ne szóljon, anyám, semmit, hanem főzzön jó túróshaluskát!
– Nem tudom, hol venném? Csak legalább kenyerem volna!
Az anyja kiment, a fiú pedig fogta a gyűrűt és: »Prestiny csek, pri
pravaj sa!« »Csoksess, pane?« és az Ördögök ott voltak.
– Azt akarom, hogy addig, még az anyám a kamrába jut, ott
minden: liszt és zsír is legyen!
Amint ment az anyja a kamrába, hát alig tudta kinyitni az ajtót,
úgy meg volt liszttel a kamrája töltve; mindjárt főzött haluskát, a fia
pedig az ágyra dőlt és aludt.
Azután az anyja felébresztette enni. A fiú felkelt, jóllakott s azt
mondta az anyjának:
– Anyám, én meg akarok házasodni!
– És kit akarsz elvenni, fiam?
– Csak menjen ide a szomszédba és kérje meg a király legifjabb
leányát!
– Ugyan, fiam, megbolondultál? Nem megyek én, mert még majd
kitaszigálnak!
De a fia nem hagyott neki békét, el kellett neki menni. Amint
belépett a királyhoz, a király kérdezi:
– Mit kívánsz?
– Óh, felséged, van egy fiam, olyan, mint a bolond, ide küldött,
hogy megkérjem a legifjabb leányát neki feleségül!
Hát, mindnyájan hahotára fakadtak.
– Óh, hány herczeg könyörgött már érte és senkihez sem akart
menni, nem hogy ilyen nyomorulthoz menjen.
Hazament az anyja.
– No, hát mit mondtak?
– Azt, hogy jól kinevettek és azt mondták, hogy ne menjek
többet.
– Menjen, menjen mindjárt most és kérje meg még egyszer!
Ment a szegény anya és a király alig akarta maga elébe ereszteni,
de midőn az anya térden állva könyörgött, beeresztették:
– Hát, mit akarsz, te vén bolond? Hol van a te fiad, aki oly
merész, hogy még az én leányomat is meg merte kérni?
– Ott a létra alatt!
Kinéztek, ott látták a létra alatt, vigyorgott, erre ismét elkezdtek
mindnyájan nevetni és a király megparancsolta az őröknek, ha még
egyszer eljön ez a vén boszorkány, lőjjék le az őrök.
Amint hazaért az anya, mindjárt kérdezte a fiú:
– Mi hír?
– Az, hogy ha még egyszer odamegyek, meglövet a király!
– Csak menjen kend, csak menjen kend!
– Óh, hát a halálomat akarod?
De a fiú nem hagyott békét, elment a szegény asszony, látta
mikor már ráfogták a puskákat, de a fiú ekkor elővette a gyűrűt és:
»Prestiny csek, pri pravaj sa!« »Csoksess, pane?«
– Azt akarom, hogy az őrök mind kővé váljanak és anyám
bemehessen a királyhoz!
Meg is történt.
– Hát, te megint itt vagy? No, mondd meg a fiadnak, ha holnap
reggelig olyan kastélyt épít, mint az enyém, akkor odaadom a
leányomat neki!
Hazajött az anya.
– No, mit mondtak?
– Azt, hogy még csak oly kastélyt nem építesz reggelig, mint a
királyé, nem kapod meg a király leányát!
– Jól van, – mond a fiú – feküdjön le, édesanyám!
Elment az öregasszony feküdni, a lomha pedig elővette a gyűrűt,
megforgatta az ujján: »Preztiny csek, pri pravaj sa!« »Csoksess,
pane!«
– Azt, hogy holnap itt százszorta szebb kastély legyen, mint a
királyé és amellett még egy aranyalma legyen a ház tetején, mely
hét mérföldre látszék és én reggel gyönyörűséges aranyruhába
öltözve egy szép lovon nyargaljak a ház körül, utánam tizenkét
huszár; ez mind reggelig megtörténjék!
Reggel amint felébred a királykisasszony, alig lát a nagy
fényességtől, kitekint az ablakon, hát mit lát? Azt a szép lovagot;
beszalad atyjához:
– Nézd csak, édesatyám, ehhez szeretnék én férjhez menni!
– Jól van, édesleányom, az könnyen megtörténhet!
Mindjárt odaküldötte a király az inasát:
– Nem tetszik a lovag úrnak fölöstökömre feljönni?
Felment, megkapta a király leányát, ma is élnek, ha meg nem
haltak.
(Ipolyi A. gyüjteményében 42. sz.)

30. Nemtutka.
Hol volt, hol nem volt, még az Óperencziás-tengeren is túl volt,
ott volt egy nagy fa, annak a fának volt kilenczvenkilencz ága, a
kilenczvenkilenczedik ágán volt egy szoknya, annak a szoknyának
volt kilenczvenkilencz ráncza, a kilenczvenkilenczedik ránczában volt
egy bolha, annak a bolhának a veséjéből veszem ki a mesémet.
Egyszer volt egy embernek tizenkét fia, de egyik sem volt oly
bátor, hogy világot mert volna próbálni, mindenik otthon maradt,
csak a legkisebbik hagyta el atyja házát és elment.
Ment, mendegélt és legelőször egy erdőbe ért, ott lakott egy
ember, ehhez bemenvén, kérte, hogy ha szüksége volna cselédre, ő
szívesen ajánlkozik.
– Jól van, – mondotta az erdő ura – én befogadlak, itt ennivaló
lesz, amennyit csak akarsz, dolgod pedig egyéb nem lesz, mint
három ló van az istállóban, azoknak mindennap früstököt, ebédet,
uzsonnát és vacsorát adsz vasdoronggal, de becsületeset, továbbá
adok egy pár papucsot és addig szolgálsz, ameddig az tart, ha
elszakad, fizetésül azt kapod, amit akarsz!
Hozzáfogott tehát mindjárt másnap a cseléd a dologhoz és
becsületesen megvasdorongolta a lovakat, így ment ez egy hétig, de
egy hét után megszólamlottak a lovak és fölvilágosították, hogy az
erdő ura, kinél szolgál: Ördög, ők pedig lelkek, kiket elfogván,
ártatlanul kínozgat, továbbá, hogy oly papucsot kapott urától, hogy
soha sem szakad el és így örökké kénytelen szolgálni. De – mondják
a lelkek – nem te vagy az első, ki ily hálóba került, többnek is adtunk
mi már tanácsot, tehát azt mondjuk neked is, ha meg akarsz
szabadulni ettől a mi urunktól, itt van ez a kenyőcs, ezzel kenyegesd
meg mindennap a papucsodat, akkor nemsokára el fog szakadni; ha
pedig elszakad, uradtól bérül csak a mi ganénkat kérd, mert az mind
arany! Továbbá az első ló adott neki a szőréből három szálat
mondván:
– Ha te ezt akárhol megrázod, mindjárt egészen aranyruhában
leszel, még a paripád is, ha úgy akarod; ha pedig a régi állapotodat
akarod visszakapni, ismét rántsd meg a szőrt és elmúlik minden!
A másik ló adott neki szinte három szálat a szőréből mondván:
– Ha ezt a három szálszőrt akárhol megrázod, mindjárt
ezüstruhában jelenhetsz meg, ahol akarsz, ha pedig a régi
állapotodat akarod visszakapni, ismét rántsd meg a szőrt és elmúlik
minden!
A harmadik ló adott neki egy sípot, mondván:
– Ha te ezt akárhol megfúvod, mindjárt egy regement katona
terem előtted, ha pedig beszívod, eltűnik a regement katona!
Mindenik pedig meghagyta neki a lovak közül, hogy ha urát
elhagyja, akárkivel fog összejönni és akármit fognak tőle kérdezni,
csak azt felelje: nem tudom.
Elkövetkezett ezután a jövő hét is, de akkor csak igen gyöngén
verte a lovakat és a papucsot szorgalmatosan kenyte, míg végre a
papucs elszakadt. Megmutatta az urának a papucsot és az ura igen
csodálkozott, de látván, hogy úgy van, azt mondta neki:
– Mit kívánsz hát fáradságodért?
– Én, – mondá a szolga – mivel szegény gyermek vagyok, s egy
néhány zsák alávaló silány földem van, csak a lovaknak a ganéját
kérem.
Az ura eleget beszélt neki, hogy minek kéri azt, miért nem kér
pénzt, vagy valami becsesebb dolgot, de a szolga el nem állt
kérésétől, kénytelen volt tehát odaadni neki; mivel a szolga el nem
vihette, ott hagyta addig, míg majd kocsival eljön érte.
Ment, mendegélt most már tovább, maga sem tudta merre, sok
viszontagság után végre egy városba ért és az útczában föl s alá
járt. Abban a városban az emberek igen nagy fülűek voltak; amint
járkál, meglátja őt a király barátja, mindjárt bejelenti a királynak,
hogy gyüjteményében, ahol mindenféle emberek voltak: úgymint
egyfülűek, azután háromszeműek, háromkezűek és több ilyenfélék;
olyan még nincs, mint amilyent ő látott.
Mindjárt behívatta a király és kérdezte, hogy honnan jön, mi a
neve? És más kérdéseket is tett, de ez mindig csak úgy felelt:
– Nem tudom.
Elnevezte tehát őt a király Nemtutkának és minthogy minden
csodálatos embernek volt valami foglalatossága, őt a kertajtóba tette
felvigyázónak, hogy a kutyákat vagy más állatokat be ne eressze a
kertbe.
Egyszer mindnyájan elmentek a templomba a király udvarából,
csak a királyleány maradt otthon meg a Nemtutka. Mikor látta
Nemtutka, hogy senki sincs otthon, megrázta a három szálszőrt,
hogy ő aranyruhában és aranyparipán ülve legyen, meglett. Akkor
bement a kertbe és a veteményeket mind összetiportatta, mikor ez
megvolt, ismét megrázta a szőrt és minden elmult.
A királyleány pedig ezeket látta és nagyon beleszeretett a
Nemtutkába.
Mikor mindnyájan hazajöttek a templomból, csodálkozva nézte
kertjét a kertész, mindenfélét kérdezett a Nemtutkától, de ez csak
azt mondotta:
– Nem tudom.
Igy hát reá szörnyen megbosszankodván, ott hagyta.
A király gyönyörű szép leánya már férjhezmenő volt, jöttek tehát
királyfiak sorban megkérni; mikor már sokan voltak, két részre
ültette őket a király a szobában és a királyleánynak egy fehér
keszkenőt adott a kezébe, hogy a királyfiak között fel s alá sétálván,
amelyiknek az ölébe dobja a fehér keszkenőt, az lesz az ura; de a
királyleány egynek sem dobta az ölébe. Jöttek ismét új királyfiak,
ezek közül sem dobta egynek sem az ölébe.
Egyszer a legokosabbik királyfi föláll és azt mondja:
– Hívjuk be a cselédeket, azokat a csodálatos embereket is mind,
hátha ezek közül szeretett valamelyikbe?
Behívták az egész házinépet, még a Nemtutkát is és alig sétált a
királyleány egyszer közöttük, mindjárt a Nemtutkának az ölébe dobta
a fehér keszkenőt. Mindnyájan csodálkoztak ezen és eszük ágában
sem volt, hogy a házasságból valami legyen.
Most nagy vadászatot hirdetett a király, hogy azon minden királyfi
jelenjék meg és aki legtöbb és legszebb vadat hoz, azé legyen a
királyleány.
Mindnyájan szép paripán mentek és hogy a Nemtutka is részt
vegyen a vadászatban, annak is adtak egy sánta lovat. Bicczegett,
bicczegett utánok, mikor pedig már jól elhagyták őt a királyfiak,
leszállt lováról, odakötötte azt egy fához, megrázta a szőrt,
mondván:
– Legyek én, paripám, aranyban és mindenféle aranymadarak a
nyereg körül!
Úgy lett.
A királyfiak egész nap vadásztak, de csak egy fél vadat sem
lőhettek, haragudtak, káromkodtak is már némelyek, kivált a jó
vadászok, nagy vígasztalásukra szolgált tehát, midőn messziről
megláttak egy urat aranyruhában, aranyparipával és különféle
aranymadarakkal, ez pedig a Nemtutka volt. Megállították és
rimánkodva kértek tőle aranymadarakat; adott is háromnak.
Az első királyfinak, ha a gyűrűjét ideadja, a másodiknak, ha
aranyszélű keszkenőjét, a harmadiknak pedig legtöbbet igért, ha
hátára hagyja hagyja sütni a lova patkóját.
Mindnyájan megtettek szívesen mindent, csakhogy madarok
lehessen. Nemtutka azután eltűnt közülök, hogy nyomát se látták.
Mikor a sánta lovához ért, megrázta a szőrt, elmult minden, felült
a rossz lovára és hazafelé czammogott.
Útjában gúnyolták a királyfiak: ki egy kis farkat vágott le a
madarakból és nekiadta, ki egy kis szárnyat; ő elvette és hazavitte.
Mikor hazamentek, nagy vacsora lett, megsütötték az
aranymadarakat és akinek legtöbb volt, már ittak is tust az
egészségéért, mint vőlegénynek. Azonban Nemtutka megrázta a
szőrt, mondván, hogy csak ő maga legyen gyönyörű aranyruhában,
mi megtörtént, magához vevén a gyűrűt, keszkenőt, a madárkák
szárnyát, lábát, farkát, belépett a szobába; mindjárt megismerte őt a
három királyfi s pirulni kezdtek.
Ezután kijelentette, hogy ő a Nemtutka, hogy ő nyargalt
aranyparipán az erdőben, megmutatta a gyűrűt meg a keszkenőt és
a többit, mi vele volt; a királyfinak is meg kellett mutatnia a hátát s
mindnyájan csodálkoztak, a királyleány pedig örült és hozzáment,
meg is esküdtek.
A király az egész jószágának a felét nekik ajándékozta; ekkor
azután elküldöttek a ganajért is, ahol egykor szolgált a Nemtutka,
elhozták mind és alig rakták le, mind arannyá változott.
Együtt éltek azután sokáig; meghalt nemsokára az öreg király és
utána Nemtutka ült gyönyörű feleségével a trónusba. Éltek, éltek és
még most is élnek, ha meg nem haltak.
(Ipolyi A. gyüjteményében 76. sz. Fehér Ferdinánd gyüjt. Vajka.)

31. Bendebukk.
Hol volt, hol nem volt, még az Óperenciás-tenger dombján is túl,
volt egy öreg ember meg egy öreg asszony, volt nekik két fiok:
Bendebukk meg egy másik; nagyon szegények voltak az istenadták.
Az öreg ember nemsokára meghalt, Bendebukknak hagyott
csatakos kis bundát, meg egy csizmavakaró vaskót, a másik fiának
egy bocskortákot.
Mikor az öreg ember meghalt, azt mondta az anyjok nekik, hogy:
– Már megnyőltettek annyira, hogy szolgálhattok, hát menjetek
Isten hírével, mert én nem tudlak benneteket ruházni, eltartani.
Elindult hát a két fiú.
Mentek, mendegéltek, amint egy erdőbe értek, egy nagy nyárfa
alatt kétfelé ment az út, az egyik jobb-, a másik balfelé.
Itt a két testvér nagy sírás-rívás közt elvált egymástól;
Bendebukk ment balfelé, a másik jobbfelé szerencsét keresni.
Amint ment Bendebukk szomorkodva, egyszer úgy hallotta,
mintha messzire veszekednének, lármáznának; elszánta magát, hogy
ha az Ördögök lármáznak is ott, mégis elmegy arra. Amint közeledik,
hát látja, hogy három Ördőgfiú egy bocskortákon veszekedik,
amelyet az apjokól kaptak örökségbe, de hárman nem tudtak
megosztozkodni rajta, mert nem volt késök, amivel elvágták volna
háromfelé. Amint az Ördögök meglátták Bendebukkot, mindjárt
odahívták; azt mondja neki a legnagyobbik:
– Te kis fiú, adjál egy kést, adok neked egy sapkát, amit ha
fejedbe teszesz, előtted világosság, utánad setétség lesz és senki
sem fog látni!
Azt mondja a középső Ördögfiú:
– Én meg adok olyan lámpást, hogy ha kinyitod, akármit
parancsolsz neki, megteszi.
A harmadik azt mondja:
– Én meg adok olyan bakót (= táska, tarisznya), hogy ha az
egész világot beleteszed, sem fog meglátszani!
No, jól van! hanem Bendebukk azzal a gyanuperrel élt, hogy
hátha elveszik tőle azokat. Amint hát mindegyik átadja neki az igért
valamit, ő is odaadja a rossz vaskót, nem sokat gondolt a vaskóval,
ha ottmarad is. A sapkát a fejébe nyomta, nem látták többet az
Ördögök, odább ment a kis csatakos bundában.
Amint ment, mendegélt hetedhétország ellen, egyszer elér egy
nagy városba, egyet gondolt, elment a király kapujához, azt mondja
az őröknek:
– Eresszenek be, bácsi! Azt hallottam, hogy az udvari szabónak
meghalt az inasa, szeretnék szabóinas lenni.
A kapuőrök rátámadtak, mit akar abban a rossz, kis bundában,
nem annak való ő, de mégis addig-meddig kunyorált ott,
beeresztették.
Bement tehát a szabóhoz és azt mondja neki:
– Ha nem bánná maiszter úr, lennék én inasa, úgyis meghalt a
másik!
Azt mondja neki a szabó:
– Jó, én nem bánom, hanem tudod, mi lesz a kötelességed!?
Reggel, mikorára felkelünk, az udvar ki legyen seperve, a konyhán
égjen a tűz, a tűz mellett a fazokakban forrjon a tiszta víz, ha ezt
megteszed, akkor szeretni foglak!
Bendebukk megigérte, hogy teljesíteni fogja.
Másnap reggel, mikorára felkeltek, az udvar tiszta volt, a konyhán
égett a tűz, a fazokakban a víz már csak félig volt a régi fövés
következtében. Meglátja mindezt a szabóné, mondja Bendebukknak:
– Máskor ne rakj olyan jókor tüzet, mert látod, most is már lefőtt
a fazekakban a víz!
Bendebukk szótfogadott, mindent jól csinált, rendesen és nagyon
szerették. Vagy négy nap mulva azt mondja a szabónak:
– Maiszter úr, engedje meg, hogy lemehessek a műhelybe is már,
hadd foldoznék ott valami ócskát!
Megengedte a szabó, lemegy hát Bendebukk a műhelybe, volt ott
egy öreg szabólegény, Jánosnak hívták, odamegy hozzá Bendebukk,
azt mondja neki:
– Adjon valami foldoznivalót, János!
– Hogy tudnád te megfoldani, mikor még tű sem volt a kezedben
sohasem!
De mégis addig-meddig kérte, hogy odaadott neki egy
katonanadrágot, hogy foldja meg a két térdjét. Bendebukk az ajtó
háta megé megy a nadrággal, kinyitja azt a lámpást, amelyiket az
Ördög adott neki, azt mondja:
– Olló szabjad, tű varrjad, vasaló vasaljad, úgy hogy még az
írígység se leljen benne hibát!
Mikorára kimondta, készen is volt, még pedig úgy, hogy János
sem tudta volna jobban meg szebben megfoldani és mikor odavitte
hozzá, csak elcsodálkozott, hogy hogy’ megvarrta.
Másnap megint lement Bendebukk a műhelybe, odamegy
Jánoshoz, látja, hogy búsul, kérdi tőle:
– Mit búsul, János?
– Hej, öcsém, hogy ne búsulnék, mikor huszonnégy óra alatt száz
katonakitlit kell megvarrni magamnak!
– Soh’se búsuljon rajta, majd megcsinálom én, egyék, igyék,
feküdjék le!
János is megfogadta a jó szót és úgy tett; Bendebukk is
hozzálátott a dologhoz, nem csinált egyebet, csak mindig azt
mondta:
– Olló szabjad, tű varrjad, vasaló vasaljad!
Mikor ezt elmondta, már akkor mindig kész volt egy kitli. Mikor
János felébredt, kész volt a száz mondur és másnap Bendebukknak
adta a maga früstökjét, amiért vele oly jót tett.
Azután való napon megint látta Bendebukk, hogy János
szomorkodik, kérdi tőle, mi baja?
Azt mondja:
– Már meg kétszáz kitlit kell huszonnégy óra alatt elkészíteni!
Azt mondja Bendebukk:
– Egyék, igyék, aludjék, majd megcsinálom én!
János lefeküdt és mikorára felkelt, készen volt a kétszáz mondur.
Ekkor János Bendebukkot ebédkor az asztalhoz ültette a maga
helyére, váltig szabadkozott Bendebukk, hogy nem ül oda, de
muszáj volt. Amint bemegy ebédelni a maiszter, látja, hogy hol ül
Bendebukk, mindjárt haragra gyulladt, hogy hogy’ mert odaülni,
haragjának vége is az lett, hogy Bendebukkot elhajtotta magától.
Elment Bendebukk a kis, csatakos bundában egy nagy városba
megint, a király kertészéhez bement és azt mondta, hogy kertészinas
akar lenni, a kertész mindjárt meg is fogadta, mert szüksége volt
kertészinasra és kiküldte a kertbe, hogy a virágokról hajtogassa a
legyeket és bogarakat. Bendebukknak nem volt egyéb dolga, mindig
járkált a kertben föl s alá, legyezve a virágokat. Egyszer vasárnap a
legkisebb királykisasszony nézett ki a kertbe a kastély ablakán, – a
másik két kisasszony a templomban volt – látja, hogy egy kis fiú
legyezi a virágokat egy, csatakos bundában. De amint észre sem
veszi, csak egy rézpáncélos vitéz rézszőrű lovon felvágatja a lovával
az egész kertet olyan pusztára, mint a pádimentom és azután
rézvirágokkal beülette az egész kertet.
A király mikor meglátta, megörült és jól megajándékozta a
kertészt, jóllehet a kertész maga sem tudta, ki ültette a virágokat és
megtiltotta Bendebukknak, hogy hozzájok nyuljon. Bendebukk
nevetett magában, mert ő vágatta fel az egész kertet és ő ültette be
is.
A következő vasárnap a középső királykisasszony maradt otthon a
templomból; akkor már ezüstpánczélos vitéz ezüstszőrű lovon
vágatta fel a kertet és ezüstvirágokat ültetett, de ez a kisasszony
nem is gondolt arra, hogy talán a kis bundás fiú csinálta azt? A
harmadik vasárnap a legnagyobbik kisasszony maradt otthon, ekkor
pedig aranypánczélú vitéz vágta fel az egész kertet aranyszőrű lovon
és aranyvirágokat ültetett. Még akkor ajándékozta meg igazán a
kertészt, mikor látta, hogy valamennyi virág a kertjében van, mind
hárompróbás aranyból készült; de ez a legnagyobbik királykisasszony
sem tudta, hogy Bendebukk volt az aranypánczélos vitéz.
A negyedik vasárnap megint otthon akart maradni a legkisebbik
kisasszony a templomból, azt hazudta, hogy beteg, de az atyja azt
mondta, ha halálán van is, el kell menni.
– No, jól van!
Azt mondja a kertésznek:
– Kertész bácsi, mondja meg az inasának, hogy kössön
háromunknak három bokrétát!
Bendebukk kötött is olyan szép bokrétákat, hogy
hetedhétországra szólott és úgy kitudta a virágból csinálni a három
kisasszony képét, hogy pingálni sem lehetett volna jobban. Felvitte a
kis, csatakos bundában, a kertész el akarta tőle venni, hogy majd ő
viszi be, de Bendebukk csak azon volt, hogy majd beviszi ő. Amint
hát bemegy a királykisasszonyok szobájába csatakos bundával, a két
nagyobbik kisasszony kiabál rá:
– Eredj ki, takarodj!
De a legkisebbik azt mondja:
– Hozd elő a bokrétámat, kis öcsém!
Amint odaadja neki Bendebukk, egy aranyat nyomott a markába
a kisasszony.
Nemsokára csináltatott a király a három leányának három
aranyalmát, összehívatta az egész birodalmában levő grófokat,
herczegeket és azt mondta a leányainak:
– Akinek akarjátok, annak lökjétek az aranyalmát, ahhoz kell
férjhez mennetek!
Egy nagy szobában ott voltak a herczegek, grófok, a királynak
minden cselédjei, csak Bendebukk nem. Egyszer ő is bejött a
csatakos bundában, odaállott az ajtóhoz egy gróf háta megé.
A két nagyobbik királykisasszony odahajítja a két aranyalmát két
herczegnek, a legkisebbik pedig odagöngöríti Bendebukkhoz; a
Bendebukk előtt álló gróf azt gondolta, hogy neki löki és fel akarta
venni, de azt mondja a királykisasszony:
– Nem magának löktem ám! – azzal Bendebukk felvette.
Volt azután lakodalom, de a király haragudott a legkisebbik
leányára, hogy miért ment ahhoz a nyavalyás kölyökhöz.
Bendebukknak meg a feleségének nem is volt szabad az asztalhoz
ülni, csak az ajtó háta megett voltak mind a ketten.
Másnap a két herczeg vadászni ment lóháton, azt kérdik
Bendebukktól:
– Nem jön vadászni, kis sógor?
Bendebukk azt mondta, hogy elmegy, csak lovat adjanak alá;
adtak is egy rossz, girhes, szemeten hízott lovat, hogy alig tudott
lépni. Amint a város végén mennek, nagyon nagy sárban kellett
menni, a szegény Bendebukk lova bentmaradt a sárban, a két
herczeg pedig kényesen nevetve elvágtatott.
Akkor azt mondja a ló Bendebukknak, mert tátos volt:
– Mit csináljak, kis gazdám?
Azt mondja neki Bendebukk:
– Rézszőrű ló légy, én rézpánczélú vitéz, rézszőrű eleven nyúl
viczkándozzék oldalamon!
Meglett! Akkor megint azt kérdi a ló:
– Hogy menjek, mint a szél, vagy mint a gondolat?
Azt mondja Bendebukk:
– Mint a gondolat, a két herczeg előtt teremj!
Úgy is lett. Mikor észrevette magát, Bendebukk látja, hogy itt jön
a két herczeg elébe, persze nem ismerték, prezentíroztak neki és
azután beszédbe eredtek egymással. Azt kérdi a két herczeg:
– Mennyiért adod nekünk azt a nyulat?
Bendebukk, mintha nem tudná, azt mondja:
– Nektek adom egy olyan sárga karikáért, amilyen az ujjatokon
van!
Az egyik herczeg azt súgja a másiknak:
– Odaadom én. Majd azt hazudom otthon, hogy eltört, azután
elvesztettem!
Oda is adta, azután elváltak egymástól, egyik egyik felé, másik
másik felé. Amint a két herczeg a város végire ér, látják, hogy
szegény Bendebukk még most is ott kínlódik a nagy sárban; azután
nagy nehezen hazavergődött, a felesége megmosta a sártól egy
nagy dézsa vízben. Másnap megint elhívta a két herczeg
Bendebukkot vadászni, még rosszabb lovat adtak alá, a város végin
megint ott maradt a nagy sárban lovastól, a két herczeg pedig
nevetve elnyargalt.
Azt kérdi a ló:
– Mit csináljak, kis gazdám?
Azt mondja Bendebukk:
– Ezüstszőrű ló légy, én ezüstpánczélú vitéz, ezüstszőrű nyúl
viczkándozzék az oldalamon és mint a gondolat, a két herczeg előtt
teremj!
Alig mondta ki, úgy lett; a két herczeg itt jött vele szemben,
köszöntek egymásnak; a két herczegnek megint megtetszett az
ezüstnyúl, kérdik tőle:
– Miért adnád azt nekünk?
Azt mondja a vitéz:
– Egy másik sárga karikáért!
Most a másik herczeg adta oda a jegygyűrűjét; azzal elmentek.
Mikor a város végin vannak, látják, hogy Bendebukk mégis ott
vergődik a sárban lovastól; azután kijött valahogy; hazament, otthol
megmosta.
Harmadik nap megint kiment a két herczeg vadászni, elhívták
Bendebukkot is, még rosszabb lovat adtak neki. Szegény, annak
rendi és módja szerint ott maradt a sárban! Amint a két herczeg
elmegy, azt mondja a lovának:
– Aranyszőrű ló légy, aranypánczélos vitéz legyek, aranyos szőrű
nyúl viczkándozzék oldalamon, mint a gondolat a két herczeg előtt
teremj!
Úgy lett, a két herczeg alig tudta, hogy’ köszönjön ennek a
vitéznek. Beszédbe eredtek, megint kérdezte a két herczeg:
– Miért adod nekünk azt a nyulat?
Azt mondja Bendebukk:
– Nektek adom, ha valamelyitök a sódarára hagyja nyomni a
pecsétet!
Az egyik ráhagyta nyomni, azután elváltak. Mikor a két herczeg a
városba ért, szokás szerint ott vergődött Bendebukk, azután
hazament, megmosta a felesége.
Egyszer a király összegyüjti a birodalmában levő mágnásokat
bemutatására azoknak a nyulaknak, amelyeket az ő két veje fogott.
Mikor vendégeskednek legjobban, a két herczeg pedig beszéli, hogy
hogy’ és miképen fogták a nyulat, bejön egy ezüstpánczélú vitéz, azt
gondolták, valami mágnás, ezt is leültették. Egyszer azt mondja:
– Hazudtok herczeg sógorok, mert nem a réznyulat ezért a
gyűrűért, az ezüstnyulat ezért a másikért adtam én Bendebukk, a
harmadikat pedig azért adtam, hogy a sódarodra nyomtam a
pecsétet? ha nem hiszik, nézzék meg!
Megnézték és csakugyan úgy volt. Akkor feláll Bendebukk, azt
mondja:
– Isten áldjon meg király atyám, Isten áldjon meg feleségem! –
azzal elment.
Ment, mendegélt a kis, csatakos bundában, egyszer elér egy
királyhoz, bemegy nálla, azt mondja neki:
– Azt hallottam, felséges király, hogy van felségednek egy leánya,
aki minden éjszaka tizenkét pár czipőt nyű el, azután még eddig ki
nem tudta senki se tudni, hogy hogy’ esik az? Én is szeretném
megpróbálni; mert ha ördöggel czimborázik is, meg fogom én tudni.
Azt mondja neki a király:
– Az mind igaz, édes fiam, hanem úgy vigyázz, hogy ha ki nem
találod az okát, már kilencvenkilencz embernek van a feje karóban
érte, a tied a századik lesz.
Bendebukk megmaradt feltétele mellett.
Este lefekszik a királykisasszony ajtajában a csatakos bundában;
amint ott fekszik, egyszer tíz óra tájban, ihen jön egy tüzes szekér az
udvarra, kiszáll belőle egy, nagy szakállas úr, bemegy a kisasszony
szobájába, a kisasszonyt kivezeti, fel a szekérre ülnek mind a ketten;
Bendebukk is kapja magát, a sapkáját a fejébe nyomja, hátul
felugrik a bakra, sebesen elmennek.
Amint mennek, egyszer elérnek egy rézerdőbe, ott egy
rézforrásnál megállanak, esznek, isznak, beszélnek, fürdenek,
mozsdanak. Bendebukk is evett a nagy szakállas úr tányérjából.
Mikor el akarnak indulni, Bendebukk megfog egy rézpoharat,
beleteszi a bakójába, megfog egy rézágat, letöri, annak azt mondja:
– Menjék kend is a bakóba!
De amint a rézágat letörte, az egész erdő megcsendült bele. Azt
mondja a királykisasszony nagy ijedten:
– Jaj, felséges férjem és királyom, a kis bundás ember csinál
valamit!
Nosza Plutó is, – mert az volt a nagy szakállas úr – leugrik,
össze-visszafujja tűzzel a szekérnek minden zegét-zugát, még a
tengely végszeglyukát is; nem lelt semmit. Akkor azt mondja a
kocsisnak:
– Sem ló, sem ostor nem a tied, hajts!
Mentek sebesen, egyszer elérnek egy ezüsterdőbe, ott is az
ezüstforrásnál esznek, isznak; Bendebukk egy ezüstpoharat, egy
ezüstfaágat megint a bakóba tett.
Onnan elmentek, elérnek az aranyerdőbe, ott is az aranyforrásnál
esznek, isznak; ott is beletett Bendekukk egy aranypoharat, egy
aranyágat a bakójába.
Amint innen kiérnek, mennek sebesen egy keskeny szekérúton,
egyszer elének egy rucalábon forgó várba; amint le akar szállani a
királykisasszony, két szép kisleány kiszalad elébe, azt kérdik tőle:
– Mit hoztál, mit hoztál, édesanyám?
Bementek mind a várba, leültek vacsorálni, Bendebukk pedig a
pitarban volt az ajtó háta megett. Amint az inas hozta kifelé a jóféle
ételmaradékokat, Bendebukk mindent kivesz a kezéből, a bakójába
teszi, a királykisasszony hozott magával tizenkét pár czipőt, azt is a
bakóba tette.
Amint megvacsoráltak, kimegy a kisasszony egy beretvával
kirakott pádimentomú szobába; persze amint kettőt lépett, vége lett
mindjárt a czipőknek, kiáltja az inasnak, hogy hozza be a többit! Hát
sehol sem találják. A királykisasszony is megijed, azt mondja
Plutónak:
– Jaj, felséges férjem és királyom, a kis bundás ember csinál
valamit, tovább nem maradok, megyek haza!

You might also like