Full Download Learn Java Fundamentals A Primer for Java Development and Programming 1st Edition Jeff Friesen PDF DOCX
Full Download Learn Java Fundamentals A Primer for Java Development and Programming 1st Edition Jeff Friesen PDF DOCX
com
https://ebookfinal.com/download/learn-java-fundamentals-a-
primer-for-java-development-and-programming-1st-edition-
jeff-friesen/
OR CLICK BUTTON
DOWNLOAD EBOOK
https://ebookfinal.com/download/learn-java-for-web-development-modern-
java-web-development-1st-edition-vishal-layka/
ebookfinal.com
https://ebookfinal.com/download/simply-java-an-introduction-to-java-
programming-programming-series-1st-edition-james-levenick/
ebookfinal.com
https://ebookfinal.com/download/java-programming-exercises-volume-two-
java-standard-library-1st-edition-christian-ullenboom/
ebookfinal.com
https://ebookfinal.com/download/learn-java-in-a-weekend-1st-edition-
joseph-p-russell/
ebookfinal.com
Learn Objective C for Java Developers 1st Edition James
Bucanek (Auth.)
https://ebookfinal.com/download/learn-objective-c-for-java-
developers-1st-edition-james-bucanek-auth/
ebookfinal.com
https://ebookfinal.com/download/beginning-programming-with-java-for-
dummies-third-edition-barry-burd/
ebookfinal.com
https://ebookfinal.com/download/java-servlet-programming-second-
edition-jason-hunter/
ebookfinal.com
https://ebookfinal.com/download/object-oriented-programming-and-java-
second-edition-danny-poo/
ebookfinal.com
https://ebookfinal.com/download/wireless-java-programming-
with-j2me-1st-edition-yu-feng/
ebookfinal.com
Learn Java
Fundamentals
A Primer for Java Development and
Programming
—
Jef f F riesen
Learn Java Fundamentals
A Primer for Java Development
and Programming
Jeff Friesen
Learn Java Fundamentals: A Primer for Java Development and Programming
Jeff Friesen
Dauphin, MB, Canada
v
Table of Contents
Chapter 3: Expressions������������������������������������������������������������������������������������������� 31
Introducing Expressions�������������������������������������������������������������������������������������������������������������� 31
Simple Expressions��������������������������������������������������������������������������������������������������������������������� 31
Compound Expressions��������������������������������������������������������������������������������������������������������������� 33
Operator Examples���������������������������������������������������������������������������������������������������������������� 36
Playing with Expressions������������������������������������������������������������������������������������������������������������ 54
What’s Next?������������������������������������������������������������������������������������������������������������������������������� 59
Chapter 4: Statements�������������������������������������������������������������������������������������������� 61
Introducing Statements�������������������������������������������������������������������������������������������������������������� 61
Assignment Statements�������������������������������������������������������������������������������������������������������������� 61
Simple-Assignment Statement���������������������������������������������������������������������������������������������� 61
Compound-Assignment Statement��������������������������������������������������������������������������������������� 62
Decision Statements������������������������������������������������������������������������������������������������������������������� 62
If Statement��������������������������������������������������������������������������������������������������������������������������� 62
If-Else Statement������������������������������������������������������������������������������������������������������������������� 63
Switch Statement������������������������������������������������������������������������������������������������������������������ 66
Loop Statements������������������������������������������������������������������������������������������������������������������������� 68
For Statement������������������������������������������������������������������������������������������������������������������������ 68
While Statement�������������������������������������������������������������������������������������������������������������������� 70
Do-While Statement�������������������������������������������������������������������������������������������������������������� 72
Loop-Branching Statements������������������������������������������������������������������������������������������������������� 73
Break Statement�������������������������������������������������������������������������������������������������������������������� 73
Continue Statement��������������������������������������������������������������������������������������������������������������� 75
Additional Statements����������������������������������������������������������������������������������������������������������������� 77
Assert Statement������������������������������������������������������������������������������������������������������������������� 77
Empty Statement������������������������������������������������������������������������������������������������������������������� 78
Import Statement������������������������������������������������������������������������������������������������������������������ 78
Method-Call Statement��������������������������������������������������������������������������������������������������������� 78
Package Statement��������������������������������������������������������������������������������������������������������������� 79
Return Statement������������������������������������������������������������������������������������������������������������������ 79
vi
Table of Contents
Try Statement������������������������������������������������������������������������������������������������������������������������ 79
Try-with-resources Statement���������������������������������������������������������������������������������������������� 79
Playing with Statements������������������������������������������������������������������������������������������������������������� 79
What’s Next?������������������������������������������������������������������������������������������������������������������������������� 84
Chapter 5: Arrays���������������������������������������������������������������������������������������������������� 85
Introducing Arrays����������������������������������������������������������������������������������������������������������������������� 85
One-Dimensional Arrays������������������������������������������������������������������������������������������������������������� 85
Creating a 1D Array��������������������������������������������������������������������������������������������������������������� 86
Accessing 1D Array Elements������������������������������������������������������������������������������������������������ 88
Searching and Sorting���������������������������������������������������������������������������������������������������������������� 89
Linear Search������������������������������������������������������������������������������������������������������������������������ 90
Binary Search������������������������������������������������������������������������������������������������������������������������ 91
Bubble Sort���������������������������������������������������������������������������������������������������������������������������� 94
Two-Dimensional Arrays������������������������������������������������������������������������������������������������������������� 96
Creating a 2D Array��������������������������������������������������������������������������������������������������������������� 96
Accessing 2D Array Elements������������������������������������������������������������������������������������������������ 98
Ragged Arrays��������������������������������������������������������������������������������������������������������������������� 100
Matrix Multiplication����������������������������������������������������������������������������������������������������������������� 102
What’s Next?����������������������������������������������������������������������������������������������������������������������������� 105
vii
Table of Contents
viii
Table of Contents
ix
Table of Contents
x
Table of Contents
StringBuffer������������������������������������������������������������������������������������������������������������������������������� 335
Creating String Buffers�������������������������������������������������������������������������������������������������������� 335
Exploring StringBuffer Methods������������������������������������������������������������������������������������������ 336
Text Reversal����������������������������������������������������������������������������������������������������������������������� 341
What’s Next?����������������������������������������������������������������������������������������������������������������������������� 342
Index��������������������������������������������������������������������������������������������������������������������� 379
xi
About the Author
Jeff Friesen is a freelance teacher and software developer
with an emphasis on Java. In addition to authoring several
books on Java and Android for Apress such as Java I/O,
NIO and NIO.2 and Java XML and JSON, Jeff has written
numerous articles on Java and other technologies for
JavaWorld (now known as InfoWorld), InformIT, Java.net,
SitePoint, and other websites.
xiii
About the Technical Reviewer
Massimo Nardone is a seasoned cyber, information, and
operational technology (OT) security professional with
28 years of experience working with companies such as
IBM, HP, and Cognizant, with IT, OT, IoT, and IIoT security
roles and responsibilities including CISO, BISO, IT/OT/IoT
Security Architect, Security Assessor/Auditor, PCI QSA, and
ICS/SCADA Expert. He is the founder of Massimo Security
Services, a company providing IT-OT-IoT security consulting
services, and member of ISACA, ISF, Nordic CISO Forum,
and Android Global Forum and owns four international
patents. He is coauthor of five Apress IT books.
xv
Introduction
Java is a popular programming language and environment. Because it is used in the
Information Technology departments of many companies, learning Java is a great way to
boost your career (and earn more money in these difficult financial times).
If you have never worked with Java, this 14-chapter book is for you. Chapter 1 starts
you on a gentle journey to learn Java fundamentals.
Chapters 2 through 11 focus mainly on language syntax, although a few APIs that are
closely related to syntax are also presented.
Chapter 2 focuses on comments, identifiers, types, variables, and literals. These
features are fundamental to many languages, and this chapter also shows you where Java
differs from other languages in their implementation.
Chapter 3 focuses on expressions (and operators), and Chapter 4 focuses on
statements. Again, these features are found in many languages. You will use these
building blocks to construct simple Java programs and will learn where Java’s
implementations of expressions (and operators) and statements diverge from other
languages.
Chapter 5 focuses on arrays. You will use this fundamental data structure to create
programs that work with sequences of data items. For example, you might want to search
a sequence of employee IDs for a specific identifier.
If this was all that Java had to offer, you would be able to create sophisticated
structured programs. In a structured program, data and operations that manipulate the
data are separated. However, Java goes beyond its ability to create structured programs,
as revealed in Chapters 6 through 8.
Chapter 6 introduces you to classes and objects. A class is a template from
which objects are manufactured. It provides an architecture for structuring data and
associating that data with code that manipulates the data. An object is an instance of a
class (kind of like a cookie is an instance of a cookie cutter). It stores data that can be
manipulated by the code that the object receives from its class. (Don’t worry if this seems
complicated. After reading Chapter 6, you’ll have a much better understanding.)
Java and other languages that support classes and objects are known as object-
based languages. To go beyond object based and become an object-oriented language,
xvii
Introduction
a language must also support inheritance. Java supports inheritance, which you’ll learn
about in Chapter 7.
Programs can be made more efficient through polymorphism, which is based on
inheritance. The idea behind polymorphism is that a single symbol can represent many
different types (e.g., the + symbol can represent integer addition, floating-point addition,
or string concatenation). You’ll learn about polymorphism in Chapter 8.
There are a few more language features that you need to learn about before you can
tour Java’s many APIs. Chapter 9 begins by introducing you to static, non-static, local,
and anonymous classes. These features let you logically organize your code, making it
more readable and maintainable.
Packages let you organize related classes in the equivalent of a file folder. This feature
helps you avoid name conflicts by organizing a library of classes under a single prefix.
Check out Chapter 10 to learn about packages.
Java provides a robust exception-handling mechanism for dealing with flawed
code or unexpected difficulties, such as attempting to open a nonexistent file. This
mechanism is covered in Chapter 11.
The final three chapters tour some fundamental APIs that you’ll use in many Java
programs. Chapter 12 focuses on the Math class and related types, Chapter 13 focuses
on String and StringBuffer, and Chapter 14 focuses on System. After you explore
these types, you’ll be able to explore additional APIs on your own to increase your Java
knowledge.
Two appendixes round out this book. Appendix A provides a quick reference to
Java’s supported reserved words, and Appendix B provides a quick reference to Java’s
supported operators.
xviii
CHAPTER 1
What Is Java?
Java is like a two-sided coin. From one side, it’s a computer programming language.
Conversely, it’s a virtual platform (the hardware and software context in which a
program runs) for running programs written in that language.
1
© Jeff Friesen 2024
J. Friesen, Learn Java Fundamentals, https://doi.org/10.1007/979-8-8688-0351-2_1
Chapter 1 Getting Started with Java
Note Java has an interesting history. Check out Wikipedia’s “Java (programming
language)” (http://en.wikipedia.org/wiki/Java_(programming_
language)#History) and “Java (software platform)” (http://en.wikipedia.
org/wiki/Java_ (software_platform)#History) entries to learn more.
• Various identical reserved words are found in Java and C/C++, such
as if, while, for, and switch. Various other reserved words are found in
Java and C++ but not in C, such as try, catch, class, and public.
• Many of the same operators are shared between Java and C/C++.
Arithmetic operators (such as * and +) and relational operators
(such as == and <=) are examples.
Java also differs from C/C++ in many ways. Here are a few of the many differences:
• Java provides reserved words that are not found in C/C++. Examples
include strictfp and transient.
2
Chapter 1 Getting Started with Java
• Java’s character type is larger than the character type in C and C++.
In those languages, a character occupies one byte of memory. In
contrast, Java’s character type occupies two bytes.
• Java doesn’t support all of C/C++’s operators. For example, you won’t
find the C/C++ sizeof operator in Java. Also, the >>> (unsigned right
shift) operator is exclusive to Java.
3
Chapter 1 Getting Started with Java
A Java program is run by a special executable, which I call the program launcher.
Because a program consists of one or more class files, the launcher receives the name
of the main class file (the class file where execution begins). After loading the JVM into
memory, it tells the JVM to use its class loader component to load the main class file
into memory. The JVM then verifies that the class file’s bytecode is safe to run (e.g., no
viruses) and runs it.
During execution, a class file might refer to another class file. When this happens, the
JVM uses the class loader to load the referenced class file into memory and then verifies
and (if okay to run) executes that class file’s bytecode.
4
Chapter 1 Getting Started with Java
2. In the Run dialog box, enter cmd in the text field and click the OK
button. On the Windows operating system, you should observe a
window similar to that shown in Figure 1-1.
5
Chapter 1 Getting Started with Java
Figure 1-1. The upper portion of a console as seen on a Windows 8.1 machine
class HelloWorld
{
public static void main(String[] args)
{
System.out.println("hello, world");
}
}
Listing 1-1 declares a HelloWorld class (I explain classes in Chapter 6) that serves as
a placeholder for the main() method (a named sequence of instructions that executes in
the context of a class).
6
Chapter 1 Getting Started with Java
The main() method serves as the entry point to the application. When the
application runs, main()’s code is executed.
The main() method header (public static void main(String[] args)) exhibits
some interesting features:
• The method is declared with a void return type that signifies the
method returns nothing.
Don’t worry if concepts such as return type and parameter list are confusing. You’ll
learn about these concepts later in this book.
The main() method executes System.out.println("hello, world"); to output
hello, world on the console’s window. I explore System.out and its System.err and
System.in counterparts in Chapter 14.
Programmers often follow one style when indenting source code, another style when
positioning a block’s open brace character, and a third style when using blank lines to separate
segments of source code. (I briefly discuss blocks, which are sequences of code surrounded
by { and } characters, in Chapter 4.)
Listing 1-1 demonstrates the first two style categories. It shows my tendency to indent, by
three spaces, all lines in a block. I find that doing so makes it easier to follow the organization
of my source code when updating it as requirements change.
7
Chapter 1 Getting Started with Java
Also, Listing 1-1 shows my tendency to align the open ({) and close (}) brace characters, so
I can more easily locate the start and end of a block. Many programmers prefer the following
brace character alignment instead:
class HelloWorld {
public static void main(String[] args) {
System.out.println("hello, world");
}
}
Another style issue involves inserting blank lines to separate segments of code, where each
segment consists of statements that work collectively on some aspect of the program. Here is
a contrived example, involving a pair of classes, A and B:
class A
{
void method1()
{
for (int i = 0; i < 10; i++)
System.out.println(i);
while (true)
{
// ... do something here
}
}
void method2()
{
for (int i = 0; i < 10; i++)
System.out.println(i);
while (true)
{
// ... do something here
}
}
}
8
Chapter 1 Getting Started with Java
class B
{
void method1()
{
for (int i = 0; i < 10; i++)
System.out.println(i);
while (true)
{
// ... do something here
}
}
void method2()
{
for (int i = 0; i < 10; i++)
System.out.println(i);
while (true)
{
// ... do something here
}
}
}
Each of classes A and B declares two methods: method1() and method2(). Furthermore,
each of method1() and method2() declares a for statement followed by a while
statement.
Don’t worry about classes, methods, and statements. I cover classes and methods in
Chapter 6 and cover statements in Chapter 4.
For now, pay attention to the blank line styles in each of A and B. A’s style is to place a blank
line between each method and between each group of related statements. B’s style is to
eliminate the blank line from between the methods and from between the statements.
Form your own styles for indentation, brace character placement, and code separation.
Although these styles don’t impact the generated code, adhering to them religiously sets you
apart from other programmers and can make your source code easier to read and maintain.
I tend to vary my code-separation style, which you’ll discover throughout this book’s code
listings.
9
Chapter 1 Getting Started with Java
Compile the source code as follows (you must include the .java file extension):
javac HelloWorld.java
If everything goes well, you should observe a HelloWorld.class file in the current
directory.
Now, execute the following command to run HelloWorld.class (you must not
include the .class file extension):
java HelloWorld
hello, world
Congratulations! You’ve just run your first Java application. You should feel proud.
Application Architecture
An application consists of at least one class, and this class must declare a main() entry-
point method, as you saw in Listing 1-1. However, many applications will consist of
multiple classes. All of these classes might be declared in a single source file, or each
class might be declared in its own source file. Consider Listing 1-2.
class A
{
static void a()
{
System.out.println("a() called");
}
}
class B
{
static void b()
10
Chapter 1 Getting Started with Java
{
System.out.println("b() called");
}
}
class C
{
public static void main(String[] args)
{
A.a();
B.b();
}
}
Listing 1-2 declares three classes (A, B, and C) in the same source file – Classes.java.
Class C is the entry-point class because it declares the main() method.
Compile Classes.java as follows:
javac Classes.java
You should observe A.class, B.class, and C.class class files in the current
directory.
Run this application as follows:
java C
a() called
b() called
If you try to execute A (java A) or B (java B), you’ll discover an error message
because neither class declares the main() entry-point method.
This brings up an interesting point. You could declare main() methods in A and B
and run these classes as applications. However, this could get confusing.
You might want to declare a main() method in each of A and B to test these classes,
but there’s probably no other good reason to do so. It’s best to avoid confusion by
declaring main() in the entry-point class only.
11
Chapter 1 Getting Started with Java
What’s Next?
Now that you’ve had a taste of Java, it’s time to build on that knowledge by exploring
language features. Chapter 2 begins this process by focusing on the most basic language
features: comments, identifiers (and reserved words), types, variables, and literals.
12
CHAPTER 2
Comments, Identifiers,
Types, Variables,
and Literals
When learning a new programming language, starting with the most basic of language
features is best. These features are comments, identifiers (with reserved words as a
subset), types, variables, and literals. This chapter introduces you to these features in a
Java context.
Comments
It’s important to document your source code so that you and anyone else who might
maintain it in the future can understand the code’s purpose. Our brains tend to forget
things as we age, and we may not understand why we wrote the code the way we did.
Source code should be documented when it is written. This documentation might have
to be modified whenever the code is changed so that it accurately explains the new code.
Java provides comments for documenting source code. Whenever you compile the
source code, the compiler ignores the comments – no bytecode is generated. Single-line,
multiline, and Javadoc (documentation) comments are supported.
13
© Jeff Friesen 2024
J. Friesen, Learn Java Fundamentals, https://doi.org/10.1007/979-8-8688-0351-2_2
Chapter 2 Comments, Identifiers, Types, Variables, and Literals
Single-Line Comments
A single-line comment appears on one line of source code. It begins with the // character
sequence and continues to the end of the line. The compiler ignores everything on this
line starting with the // characters. The following example demonstrates a single-line
comment:
Single-line comments are useful for specifying short but meaningful information.
They shouldn’t be used to insert unhelpful information, for example, // This is a
comment.
Multiline Comments
A multiline comment typically extends over multiple lines of source code although
it can appear on a single line. This comment begins with /* and ends with */. The
compiler ignores everything in between (including /* and */). The following example
demonstrates a multiline comment:
You cannot nest a multiline comment inside of another multiline comment. For
example, the compiler generates an error when it encounters the following nested
comments:
/*
/*
Nested multiline comments are illegal.
*/
*/
14
Chapter 2 Comments, Identifiers, Types, Variables, and Literals
Javadoc Comments
A Javadoc comment is a variation of the multiline comment. It begins with /** (instead
of /*) and (like a multiline comment) ends with */. All characters from /** through */
are ignored by the compiler. The following example presents a Javadoc comment:
/**
* Application entry point
*
* @param args array of command-line arguments passed to this method
*/
public static void main(String[] args)
{
// TODO code application logic here
}
Listing 2-1 presents updated source code to Listing 1-1’s HelloWorld application.
This source code includes a pair of Javadoc comments that document the HelloWorld
class and its main() entry-point method.
15
Chapter 2 Comments, Identifiers, Types, Variables, and Literals
/**
A simple class for introducing Java applications.
Apart from the Javadoc comments, Listing 2-1 differs from Listing 1-1 in that it
prefixes class HelloWorld with the public keyword, which makes HelloWorld accessible
outside of its package. (I will discuss public in Chapter 6 and packages in Chapter 10.)
I use the javadoc tool to generate HTML-based documentation for HelloWorld.
java. This tool requires that the public keyword be prefixed to the HelloWorld class.
Furthermore, the .java file extension is required:
javadoc HelloWorld.java
16
Chapter 2 Comments, Identifiers, Types, Variables, and Literals
17
Chapter 2 Comments, Identifiers, Types, Variables, and Literals
The javadoc tool was also used to generate the documentation for JDK 21’s reference
type library. This documentation’s start page is located at http://docs.oracle.com/en/
java/javase/21/docs/api/index.html. Figure 2-2 shows you part of this start page.
Identifiers
Variables, statements, classes, and other language features need to be named to be
referenced from elsewhere in the code. Java supports this capability through identifiers.
18
Chapter 2 Comments, Identifiers, Types, Variables, and Literals
Almost any valid identifier can be used to name a language feature. However, some
identifiers are reserved for special use by Java. These reserved identifiers are known as
reserved words. Figure 2-3 reveals Java’s 53 reserved words.
19
Chapter 2 Comments, Identifiers, Types, Variables, and Literals
JDK 9 added a single underscore character (_) to Java’s list of reserved words. It’s an
error to use a single underscore to name anything. However, it’s okay to use multiple
underscores (although you probably shouldn’t).
Note Most of Java’s reserved words are also known as keywords. The three
exceptions are false, null, and true. They are examples of literals (values
expressed verbatim).
Also, const and goto are reserved by Java but are not used.
Types
Computers process different types of data: integers, characters, floating-point values,
Boolean true/false values, strings of characters, and so on. Java associates a type with
each data category.
A type identifies a set of values (and their representation in memory) and a set of
operations that transform these values into other values of that set. For example, the
floating-point type identifies numeric values with fractional parts and floating-point-
oriented math operations, such as adding two floating-point values to produce another
floating-point value that represents their sum.
Java supports primitive types, user-defined types, and array types. I discuss primitive
and user-defined types here. I discuss array types in Chapter 5.
20
Chapter 2 Comments, Identifiers, Types, Variables, and Literals
Primitive Types
A primitive type (also known as a value type) is a basic type from which user-defined
types (discussed later in this chapter) are built. It identifies a set of values (such as
integers) and operations (such as addition) that are performed on these values. These
operations are built into the Java Virtual Machine (JVM).
More specifically, a primitive type consists of a reserved word that describes the
memory organization of an instance of this type. The reserved word also implies the
operations that can be performed on this type. For example, the Boolean primitive type
consists of reserved word boolean and implies operations such as logical negation (!),
which converts from true to false and false to true.
Java supports the Boolean, character, byte integer, short integer, integer, long integer,
floating-point, and double-precision floating-point primitive types. They are described
in Table 2-1.
Boolean boolean -- -- --
Character char 16-bit Unicode 0 Unicode 216 - 1
Byte integer byte 8-bit -128 +127
Short integer short 16-bit -32768 +32767
Integer int 32-bit -231 +231 - 1
Long integer long 64-bit -263 +263 - 1
Floating-point float 32-bit IEEE 754 IEEE 754
Double-precision floating-point double 64-bit IEEE 754 IEEE 754
Table 2-1 describes each primitive type in terms of its reserved word, size, minimum
value, and maximum value. A -- entry indicates that the column in which it appears does
not apply to the primitive type described in the entry’s row.
The size column identifies the number of bits required to hold a value. Except for
Boolean, whose size is JVM dependent, each type’s implementation has a specific size.
21
Chapter 2 Comments, Identifiers, Types, Variables, and Literals
The minimum and maximum size columns identify the smallest and largest values
that the type represents. Besides Boolean, which has only true and false values, each
type has minimum and maximum values.
The character type’s minimum and maximum values refer to Unicode, a standard for
consistently encoding, representing, and handling text expressed in most of the world’s
writing systems (see http://en.wikipedia.org/wiki/Unicode for more information).
Note The character type is unsigned, which its limits suggest (the smallest value
is 0). In contrast, the byte integer, short integer, integer, and long integer types
are signed.
The minimum and maximum values for the four integer types reveal one more
negative value than positive value (0 is usually not regarded as positive). This
imbalance has to do with how integers are represented in two’s-complement (http://
en.wikipedia.org/wiki/Two's_complement) format. In contrast, the minimum and
maximum values for the floating-point types are defined by the IEEE 754 (http://
en.wikipedia.org/wiki/IEEE_754) specification.
User-Defined Types
A user-defined type is a combination of primitive types and user-defined types. For
example, a user-defined type for representing the concept of man might combine a user-
defined, string-based name along with a primitive integer-based age. The following code
fragment shows how you would specify man as a user-defined type:
class Man
{
// implementation of the structure for representing a set of Man values
String name;
int age;
22
Chapter 2 Comments, Identifiers, Types, Variables, and Literals
int getName()
{
return name;
}
int getAge()
{
return age;
}
• age stores a man’s age. This field’s type is int, which is a primitive
type that represents a 32-bit integer.
23
Chapter 2 Comments, Identifiers, Types, Variables, and Literals
The operations consist of four methods (functions that execute in the context
of a class – see Chapter 6 for an introduction to methods). Man provides get and set
operations:
• get returns a Man value by retrieving the values of its name and age
fields. It provides getName() and getAge() methods for this purpose.
• set changes a Man value by changing the values of its name and age
fields. It provides setName() and setAge() methods for this purpose.
User-defined types are also known as reference types because a variable (discussed
shortly) whose type is user defined stores a reference (a memory address or other
location identifier) to a value of that type. In contrast, a variable of a primitive type stores
the type’s value instead of a reference to a value.
Variables
Data items are stored in variables, which symbolically (via their names) identify memory
locations where these items are stored. For a primitive type, the data item is stored
directly in the variable. For a user-defined type, a data item is an object stored elsewhere
in memory and a reference to the object is stored in the variable.
Variables must be declared before they are used. A declaration minimally consists of
a type name followed by an identifier that names the variable. Here are some examples:
The first example declares a Boolean variable named first. The second example
declares an integer variable named counter. The third example declares a character
variable named gradeLetter. The fourth example declares a double-precision floating-
point variable named temperature. The fifth example declares a String variable named
direction.
24
Chapter 2 Comments, Identifiers, Types, Variables, and Literals
When a variable is declared and not explicitly initialized (demonstrated later in this
chapter), it is implicitly initialized to a default value. A Boolean variable is initialized
to false, variables of the four integer types are initialized to 0, a character variable is
initialized to Unicode character 0, variables of the floating-point types are initialized to
0.0, and String variables are initialized to null.
I use the term declaration when introducing an identifier and associated syntax for a new
variable, method, or other relevant language feature into a program’s source code. (I use
declaration regardless of whether or not I initialize the variable, specify a non-abstract
method, and so on. [I cover methods in Chapter 6 and abstract methods in Chapter 8.] Some
programmers prefer the term definition over declaration, which has led to confusion. If you
are wondering what’s the big deal, remember that being precise in terminology can minimize
mistakes and clear up confusion – you’ll save yourself many headaches that arise from
arguments over seemingly trivial matters. However, such matters cannot be trivial if you spend
time getting worked up and angry while trying to defend your position.)
Regarding Java, the best resource for addressing this issue is probably The Java® Language
Specification (http://docs.oracle.com/javase/specs/jls/se21/jls21.pdf).
Chapter 6 (which covers names) uses the term declaration. In contrast, the most popular
answer to stackoverflow’s “What is the difference between declaration and definition
in Java” topic (http://stackoverflow.com/questions/11715485/what-is-
the-difference-between-declaration-and-definition-in-java) states that
declaration deals with the existence of a variable, method, and so on, whereas definition deals
with “how something is implemented” – what it is. The answer goes on to state that there is
little difference between declaration and definition in Java. Furthermore, the answer states
that “a declaration not only includes the identifier, but also its definition.”
25
Chapter 2 Comments, Identifiers, Types, Variables, and Literals
Literals
A literal is a value expressed verbatim in source code. Java supports literals for its
primitive types, initializing reference type variables, and a special reference type known
as String (discussed in Chapter 13).
A Boolean literal consists of either the keyword true or the keyword false.
A character literal consists of a single Unicode character surrounded by single quotes
(e.g., '6').
An integer literal consists of a sequence of digits. The type of an integer literal is int
(a 32-bit value). You can change the type to long by suffixing the literal with l or L (which
is easier to read).
Integer literals can be specified in the decimal, hexadecimal, octal, and binary
formats:
• The octal format requires that the literal be prefixed with 0 and
continue with octal digits (0–7), for example, 0276.
26
Chapter 2 Comments, Identifiers, Types, Variables, and Literals
Caution The compiler reports an error when you attempt to assign null to a
variable that has a primitive (value) type (such as int).
It’s possible to run into trouble when working with null. For example, when a user-
defined variable contains the null reference instead of a reference to an object, and
you attempt to access a field or invoke (call) a method, you will encounter the dreaded
NullPointerException. (I will discuss objects, fields, and methods in Chapter 6. Also, I
will discuss exceptions and mention NullPointerException in Chapter 11.)
Note You can learn more about the concept of nullness (being null) and
NullPointerException by reading Yoshitaka Shiotsu’s excellent article “Null
In Java: Understanding the Basics” (www.upwork.com/resources/what-is-
null-in-java).
27
Chapter 2 Comments, Identifiers, Types, Variables, and Literals
The following escape sequences are supported: \\ (backslash), \" (double quote),
\' (single quote), \b (backspace), \f (form feed), \n (newline), \r (carriage return), and
\t (tab).
A string literal might also contain Unicode escape sequences, which are a special
syntax for representing Unicode characters. A Unicode escape sequence starts with \u
and continues with four hexadecimal digits (0–9, A–F, or a–f) with no intervening space.
For example, \u0043 represents the capital letter C, and \u20ac represents the European
Union currency symbol.
The following examples use literals to initialize the previously presented variables:
class VarInit
{
public static void main(String[] args)
{
boolean first = true;
int counter = 10;
char gradeLetter = 'A';
double temperature = 37.9;
String direction = "East";
System.out.println(first);
System.out.println(counter);
28
Chapter 2 Comments, Identifiers, Types, Variables, and Literals
System.out.println(gradeLetter);
System.out.println(temperature);
System.out.println(direction);
}
}
javac VarInit.java
java VarInit
true
10
A
37.9
East
VAR
JDK 10 introduced var, a shortcut to declaring and initializing variables. To save keystrokes,
you no longer have to enter a variable’s type name because the compiler infers the variable’s
type from the literal’s (or other expression’s) type during initialization. For example, in var ch
= 'C';, the compiler infers that variable ch has type char because the type of 'C' is char.
Without var, you would specify char ch = 'C';. Although you saved one keystroke, which
doesn’t seem like much, you could save more keystrokes in longer syntactic contexts, such as
var amount = 10.0; instead of double amount = 10.0;.
• You must always use var in an initialization and not a declaration-only context.
In other words, you must always assign a literal or other expression to the
variable. If you specify var and a variable name by themselves, as in var ch;,
the compiler will report an error because it cannot infer a type for ch.
29
Chapter 2 Comments, Identifiers, Types, Variables, and Literals
• The var identifier might seem like a reserved word (or keyword, if you like),
but that is not the case. You cannot use a reserved word to name a variable.
However, the following declaration is legal: var var = 10.0;. In this
example, var is a double-precision floating-point variable initialized to 10.0.
I recommend not using var to name a variable (as in var var) because the result might
confuse someone who is reading your source code. Also, var might become a reserved word
someday.
What’s Next?
Now that you’ve mastered comments, identifiers, types, variables, and literals, you’re
ready to explore operators and expressions. These language features let you manipulate
data items to produce new data items, which is done in every kind of program, from a
business payroll application to a machine-learning demo.
30
CHAPTER 3
Expressions
Computer programs manipulate data via expressions. This chapter introduces you to
expressions in terms of simple and compound expressions.
Introducing Expressions
An expression is a combination of literals, variable names, method calls (discussed in
Chapter 6), and operators. At runtime, the expression evaluates to a type referred to as
the expression’s type.
If an expression is being assigned to a variable, their types must agree (it must be
possible to convert from one type to the other without losing information) or else the
compiler will report an error.
Simple Expressions
A simple expression is a literal value, a variable name (containing a value), or a method
call (returning a value) – I cover methods and method calls in Chapter 6. The following
examples demonstrate these simple expressions being used to initialize variables:
The first example assigns literal 2 to variable i. The literal and variable have the same
type: int.
The second example assigns variable i to variable j. Both variables have the same
int type.
31
© Jeff Friesen 2024
J. Friesen, Learn Java Fundamentals, https://doi.org/10.1007/979-8-8688-0351-2_3
Chapter 3 Expressions
The third example calls an open() method, passing to this method the name of a file
to open, and assigns the result to variable success. Let’s assume that open()’s return
type is boolean, which matches success’s return type.
These examples assume that only expressions whose types match the types of the
variables that they are initializing can be assigned to those variables. However, it is
possible to assign a simple expression having a different type. For example, Java lets you
assign various int literals to a variable of type short, as in short x = 90;, and assign a
short to an int variable, as in int y = x;.
The former assignment is okay because 90 can be represented as a short integer – the
largest short that can be represented is 32767, so 90 fits into a short. In contrast, the
compiler would complain when encountering short x = 80000; because 80000 cannot
be represented in 16-bit space, and information would be lost.
The latter assignment is acceptable because there is no loss of information when
you convert from a type with a lesser set of values to a type with a greater set of values. A
short’s range of values can easily fit into an int’s greater range of values.
Java uses widening conversion rules to support the following primitive-type
conversions:
When converting a smaller integer to a longer integer, Java copies the smaller
integer’s sign bit into the larger integer’s extra bits (on the left). If you would
like to understand signed integer representation, check out Wikipedia’s “Signed
number representations” (http://en.wikipedia.org/wiki/Signed_number_
representations) entry.
The previous examples focus on simple expressions in a variable-declaration
context. One of these simple expression categories, the method call, can also appear in a
non-variable-declaration context. Here is an example:
success = open("file.txt");
32
Chapter 3 Expressions
Compound Expressions
A compound expression is a sequence of simple expressions connected to each other via
operators, which are symbolically represented sequences of instructions that transform
their operands into new values. For example, -1 is a compound expression where - is an
operator and int literal 1 is its operand. This expression transforms 1 into its negative
equivalent: -1. Also, 4 * y is a compound expression where * is an operator and 4 and
y are its operands. When this expression is evaluated, y’s value is fetched and multiplied
by 4. The expression’s value becomes the result of the multiplication.
Note If x’s type is byte or short, the variable’s value is widened to an int.
However, if the type is long, double, or float, 4 is widened to the appropriate
type. The addition is performed after the widening is carried out.
Java classifies its operators via the number of operands that they take:
33
Chapter 3 Expressions
Table 3-1 presents all of Java’s operators in terms of their symbols, descriptions,
precedences, and associativity.
34
Chapter 3 Expressions
35
Exploring the Variety of Random
Documents with Different Content
Tres españoles, Hoz, Camargo y Valdivia, acariciaron al mismo
tiempo la idea de proseguir la abandonada empresa. Mas
Te quitaré la corona;
Pisarála Carlos Quinto;
Pondré en tus bárbaros templos
Lo estandartes de Cristo.
Pondré la planta en tu cuello,
Después que te haya vencido:
Y al subir á mi caballo
Me servirás por estribo.
En ocasiones semejantes, Orbea suele abandonar el culteranismo
y hablar el lenguaje propio de los afectos del alma. No así en las
descripciones y relatos, en los cuales vierte el caudal de sus
tinieblas, como, pongo por caso, en la relación que hace Tundama
de su victoria sobre los popayanos, que es larga y tenebrosa como
noche de invierno.
Para concluir, La Conquista de Bogotá es una de tantas comedias
de descubrimientos y conquistas, en las cuales ni éstas ni aquéllos
se nos muestran con la verdad y poesía que tuvieron. Toda la
realidad y la vida con que aparecen en los monumentos históricos,
desaparecen al ser convertidas en alegorías artificiales, batallas de
teatro ó enredos de damas y galanes, ni más ni menos que en las
comedias de capa y espada.
Digámoslo de una vez: los hechos del descubrimiento y conquista
del Nuevo Mundo no caben en el teatro. Caben, sí, en la Historia,
que puede presentarlos en su propia grandeza y con su natural
hermosura.
EL ALFÉREZ DOÑA CATALINA DE
ERAUSO
EL Capitán Miguel de Erauso, vecino de San Sebastián, á fines del
siglo xvi y principios del xvii hubo en su mujer María Pérez de
Galarraga tres hijos, militares los tres, otras tantas hijas, todas
monjas profesas, y, además, el sér extraño vulgarmente conocido
con el nombre de La Monja Alférez, militar como sus hermanos,
monja como sus hermanas, en el claustro Soror Catalina de Erauso,
y en los ejércitos de Chile y el Perú Alonso Díaz Ramírez de
Guzmán.
La existencia de este fenómeno antropológico consta del modo
más auténtico en documentos y testimonios fehacientes de su
época. Hablan de tan singular mujer: el Dr. Isasti, en su Compendio
histórico de la Provincia de Guipúzcoa; el maestro Gil González
Dávila, en su Historia de la vida del ínclito monarca, amado y santo
Don Felipe III; Pedro de la Valle, el Peregrino, en Carta á Mario
Schipano, fechada en Roma el 11 de Julio de 1626, y otros textos de
menor importancia, escritos, como los anteriores, en vida de la
célebre Monja.
Á los mismos días pertenece también la comedia de Montalbán La
Monja Alférez, compuesta el año en que ésta se hallaba en Roma,
que fué el de 1626.