Complete Download (Ebook) Java 17 Recipes - A problem-solution approach by Josh Juneau PDF All Chapters
Complete Download (Ebook) Java 17 Recipes - A problem-solution approach by Josh Juneau PDF All Chapters
com
https://ebooknice.com/product/java-17-recipes-a-problem-
solution-approach-38503542
OR CLICK HERE
DOWLOAD EBOOK
ebooknice.com
ebooknice.com
https://ebooknice.com/product/java-ee-7-recipes-a-problem-solution-
approach-55585796
ebooknice.com
ebooknice.com
(Ebook) Java EE 7 Recipes: A Problem-Solution Approach by
Josh Juneau (auth.) ISBN 9781430244257, 9781430244264,
1430244259, 1430244267
https://ebooknice.com/product/java-ee-7-recipes-a-problem-solution-
approach-4241208
ebooknice.com
https://ebooknice.com/product/jakarta-ee-recipes-a-problem-solution-
approach-53793222
ebooknice.com
ebooknice.com
ebooknice.com
https://ebooknice.com/product/oracle-pl-sql-recipes-a-problem-
solution-approach-1756442
ebooknice.com
CHAPTER 1
Note Java 17 Recipes is not intended as a complete tutorial. Rather, it covers key
concepts of the Java language. If you are truly new to Java, you may want to pick
up Java 17 for Absolute Beginners by Iuliana Cosmina (Apress, 2022).
1
© Josh Juneau, Luciano Manelli 2022
J. Juneau and L. Manelli, Java 17 Recipes, https://doi.org/10.1007/978-1-4842-7963-2_1
Chapter 1 Getting Started with Java 17
Solution
Install Java Development Kit 17 (JDK), which provides the language and a compiler.
Nothing runs without Java. The runtime environment (JRE) lets you execute Java.
The JDK lets you compile Java sources into executable classes. There are two main
distributions: Oracle JDK and OpenJDK. We chose the second one under the GNU
General Public License because the Oracle JDK license changed for releases starting
in April 2019, permitting only certain uses at no cost. However, you can download the
commercial builds of JDK from Oracle under a non-open-source license at the Oracle
Technology Network.
Download the OpenJDK release for your platform from https://jdk.java.net/17/,
shown in Figure 1-1 and extract the archive file on your PC.
2
Chapter 1 Getting Started with Java 17
How It Works
Java is a trademark owned by the Oracle Corporation. The language itself is open source,
and its evolution is controlled by the Java Community Process (JCP). You can read about
it at www.jcp.org/en/home/index. While Oracle Corporation does not own the language,
its core development tends to be steered by that company. It is Oracle Corporation that
runs the JCP and owns the jcp.org domain.
The Java home folder has the bin subfolder that help you to develop and execute
programs in Java language (with tools and utilities) and that supports the execution of
programs written in the Java programming language (with an implementation of the Java
Runtime Environment (JRE), class libraries, and other files). Since Java 11, Oracle and
the OpenJDK team decided to distribute only the JDK and stop duplicating some of the
things in JDK in the JRE folder.
There are many editions of Java, such as the Mobile Edition (ME) (www.oracle.com/
java/technologies/javameoverview.html) and the Enterprise Edition (EE)
(www.oracle.com/it/java/technologies/java-ee-glance.html). Java SE is the
Standard Edition and represents the heart of the language. We built the recipes in this
book for Java SE programmers. Those interested in developing embedded applications
for devices may be interested in learning more about Java ME. Similarly, those interested
in developing web applications and working with enterprise solutions may be interested
in learning more about Java EE.
OpenJDK and Oracle JDK binaries are compatible and close to each other, but there
are some differences.
• The output of Java the version in Oracle JDK includes the Oracle-
specific identifier. OpenJDK does not include the Oracle-specific
identifier.
• Oracle JDK uses the Java Cryptography Extension (JCE) Code Signing
Certificate. OpenJDK allows unsigned third-party crypto providers.
3
Chapter 1 Getting Started with Java 17
Go to www.oracle.com/java/technologies/javase/17-relnote-issues.html for
more information on the Oracle JDK.
Solution
Add the JDK path to the PATH environment variable. You should have the jdk-17 folder
at the root of your OS drive or a custom location.
In Windows, search and for select the control panel. Click the Advanced System
settings and then Environment Variables. In the System Variables section, find the PATH
environment variable and select it. In the Edit System Variable field or the New System
Variable field, insert the text C:\jdk-17\bin; in the field “Variable value”. You can also set
the JAVA_HOME with the value of C:\jdk-17 and, then, set in the Path the value %JAVA_
HOME%\bin). The semicolon at the end of the text is essential because it separates the
new path from the existing ones. Do not insert additional spaces before or after.
In Unix and Linux systems, you edit the environment file and modify the PATH
variable. In this case, you execute a command such as the following.
At last, to find out if the path is properly set, open a command-line window, go to the
command prompt, and type the following command.
java -version.
If you see a screen like the one shown in Figure 1-2, the correct Java version is
installed.
4
Chapter 1 Getting Started with Java 17
How It Works
To compile and execute a Java program, you must add the JDK path to the PATH
environment variable (a string of paths separated by semicolons in Windows and colons
in Unix OS). All operating systems use the PATH environment variable to determine
where executable files are located on your system to execute any stored or downloaded
file on your personal computer. This variable tells the operating systems where the to-
run programs reside when a user executes a file. The environment variables can also be
stored information used by applications or operating systems.
PATH contains a string of directories separated by semicolons in Windows and
colons in Unix OS. PATH is used because any executable file in the directories listed
in PATH can be executed without specifying the full path to the file. This allows you
to run those executables with only the file name from the command line or for other
applications to run those executables without knowledge of their directory path.
So, when you execute a file, you need to specify the full path to that file, but if the
command does not include the path, the OS uses the executable file that matches your
file in the PATH.
Solution
Use the little application shown in Listing 1-1. You can use a smart editor like Notepad++
or a different text editor in this example.
5
Chapter 1 Getting Started with Java 17
To create the source code for your first Java program, you must do the following.
Now, save the file as Hello.java in your working folder. Open the command window.
After changing to your work directory, enter the following to compile the application.
javac Hello.java
It should return the prompt without saying anything. It also means that you have
correctly updated the Path system variable. If you want to know more about what the
javac compiler is doing, type -verbose between javac and the name of the file (javac
-verbose Hello.java). You see a file named Hello.class in your work directory.
Enter the following in the command prompt to run the application (see Figure 1-3).
java Hello
6
Chapter 1 Getting Started with Java 17
Note All the code described in this book is available for download from github
.com/apress/java17-recipes. In this case, you can simply type the code;
in others, you don’t need to retype it. It is important that you improve your
programming skills using the Eclipse Environment, which is a famous free and
open source Java IDE, containing a workspace for developing applications, that
you can download at www.eclipse.org. You can find the examples in folders
with the same names as the corresponding chapters.
How It Works
Java is an object-oriented programming language based on classes and objects with
attributes and methods. A class is necessary for creating objects. To create a Java
program (i.e., a .class file), you must create a .java file. A .java file is a readable text file,
while a .class file is a binary file, which is a file containing Java bytecode that can be
executed on the Java Virtual Machine (JVM), and that is produced by a Java compiler
from the .java file.
Tip You must compile source code. Source code is kept in files with a .java
suffix, so your operating system’s file and directory path notation are appropriate.
One executes a class. A class is an abstract concept in the language, so its dot-
notation becomes appropriate (i.e., it is necessary to write a dot (.) after the name
of the instance of a class followed by the method to be used). Keep this distinction
in mind to help yourself remember when to use which notation.
7
Chapter 1 Getting Started with Java 17
Solution
Install the Eclipse IDE to provide a more productive working environment.
First, you need to download the package. Go to www.eclipse.org/downloads/
packages/ and click Eclipse IDE for Java Developers, as shown in Figure 1-4.
8
Chapter 1 Getting Started with Java 17
The website suggests a mirror site for the download. The installation of Eclipse is
very easy: expand the downloaded file in the root of your personal computer. When you
execute Eclipse, it asks you to select a workspace. The workspace is the folder where
Eclipse stores your development projects. Therefore, it makes sense to place it on a drive
or in a directory that you back up regularly. Before clicking the OK button, select the Use
this as the default and do not ask again check box. It makes your life easier. You can
choose the root and use the eclipse-workspace default folder, which is the user’s home
directory. The first time it executes, Eclipse displays a Welcome screen. To enter the
screen where you do development, click the Workbench icon, as shown in Figure 1-5.
The IDE is ready. You should see a workspace resembling the one in Figure 1-6.
9
Chapter 1 Getting Started with Java 17
Next, you need to tell Eclipse what version of JDK to use. In Windows OS, go to the
Windows menu and select Preferences. Select Java and then Installed JREs. You see the
dialog shown in Figure 1-7. Click Edit and select the installed JDK.
You can verify that Eclipse uses the correct JDK. Go to Help ➤ About Eclipse IDE and
click the Installation Detail button. You can see the path and the name of the installed
and used JDK, as shown in Figure 1-8.
How It Works
Although it’s possible to build web applications by compiling Java modules from the
command line, it’s more efficient to use an IDE. This way, you can concentrate on the
more creative part of developing software rather than fix inconsistency and fiddle with
folder hierarchies.
An IDE integrates all the applications that you need to develop software—from
a source editor and a compiler to tools to automate the application building process
and a debugger—into a single application. When developing in Java or another object-
oriented language, an IDE also includes tools to visualize class and object structure and
inheritance and containment. Another advantage of using an IDE is that it propagates
changes you make to individual modules. For example, if you rename a class, the IDE
can automatically update its occurrences throughout your project files.
11
Chapter 1 Getting Started with Java 17
As the applications you develop become more complex, it makes more and more
sense to use an IDE. That’s why, before continuing to the next project, let’s discuss how
to install and configure Eclipse.
Eclipse is an extremely powerful and extensible IDE, well suited for web application
development. The Eclipse Foundation makes a new release four times a year (in March,
June, September, and December) due to continuous integration and delivery in the
software industry (called the rolling release). Once you’ve installed Eclipse to develop
your applications, you can also use it for any other software development task, such as
developing and debugging applications written in Java, C++, Python through a plug-in,
or Fortran, which is widely used in the scientific community.
Furthermore, whatever task related to software development you need to perform,
it’s likely that somebody has already developed an Eclipse plug-in for it. The Eclipse
Marketplace website (http://marketplace.eclipse.org) lists about 2,000 plug-ins
organized in dozens of categories. Eclipse consists of a core platform that executes
plug-ins, plus a series of plug-ins that implement most of its functionality. Therefore, the
standard packages available for download from the Eclipse website include dozens of
plug-ins.
Solution
Begin by opening the Eclipse IDE. You may see some projects in the left pane if you’ve
already been working on projects within the IDE.
12
Chapter 1 Getting Started with Java 17
Go to the File menu and select New ➤ Java Project, as shown in Figure 1-9.
13
Chapter 1 Getting Started with Java 17
Name your project java17Recipes. Enter the project name in the text box at the top
of the dialog, as shown in Figure 1-10.
In the JRE section, select the installed JDK (i.e., the JavaSE-17 that you just
configured). Press Finish to complete the wizard and create a skeleton project.
Now, create a new package. Go to the File menu and select New ➤ Package, as
shown in Figure 1-11.
14
Chapter 1 Getting Started with Java 17
Next, create a new class. Go to the File menu, select New ➤ Class, and name the class
HelloWorld, as shown in Figure 1-13.
15
Chapter 1 Getting Started with Java 17
16
Chapter 1 Getting Started with Java 17
Tip You can create package and class in the same configuration window by
simply creating a new class and typing package and class name in the Name field.
Moreover, by convention, class names usually start with an uppercase letter.
Make sure that you enter the project name, the package name, and the class
name exactly as we provide them here because the code to follow depends on your
doing so. Make sure the project name is java17Recipes. Make sure the package is
org.java17recipes.chapter01.recipe01_05. Make sure the class is HelloWorld.
Next, you should look at a Java source file. Skeleton code is generated for you, and
your Eclipse IDE window should resemble the one shown in Figure 1-14.
Place your cursor anywhere in the source code pane. Press Ctrl+A to select all the
skeleton code. Then press Delete to get rid of it. Replace the deleted code with that from
Listing 1-2. Then, create another class, name it HelloMessage, and copy the code from
Listing 1-3.
You can find the code in Listing 1-2 and Listing 1-3 as part of our example download
for the book. There are two files named HelloMessage.java and HelloWorld.java, which
reside in a Java package named org.java17recipes.chapter01.recipe01_05. Note that
all recipe solutions of substance throughout this book are in that example download.
The class is named HelloWorld, and it initiates the program.
package org.java17recipes.chapter01.recipe01_05;
public class HelloWorld {
/* The main method begins in this class */
public static void main(String[] args) {
17
Chapter 1 Getting Started with Java 17
HelloMessage hm;
hm = new HelloMessage();
System.out.println(hm.getMessage());
hm.setMessage("Hello, World");
System.out.println(hm.getMessage());
}
}
package org.java17recipes.chapter01.recipe01_05;
public class HelloMessage {
private String message = "";
public HelloMessage() {
this.message = "Default Message";
}
Make sure you have pasted (or typed) the code. Compile and run the program.
Right-click in the project and select Run As ➤ Java Application, as shown in Figure 1-15.
18
Chapter 1 Getting Started with Java 17
DEFAULT MESSAGE
HELLO, WORLD
This output appears in a new view named Console, which Eclipse opens at the
bottom of the IDE window, as shown in Figure 1-16.
19
Chapter 1 Getting Started with Java 17
How It Works
You can run almost all the solutions in this chapter using the same general technique
shown in this recipe. For that reason, we show the step-by-step screenshots this
one time.
Packages
The solution example begins by creating a Java package.
package org.java17recipes.chapter01.recipe01_05;
Packages are a way of grouping related classes together into a shared namespace.
The idea is to achieve universal uniqueness by working your way down your
organization’s domain name in reverse order. It is also customary to write package
names in all lowercase.
Eclipse creates a directory structure to imitate your package path. In this case,
Eclipse created the following directory path.
C:\eclipse-workspace\java17Recipes\src\org\java17recipes\chapter01\
recipe01_05
• Any source files you create go into the src directory. Eclipse creates
other directories at this level. For example, Eclipse creates a bin
directory, and then underneath it is a classes subdirectory to hold
your compiled class files.
• The directories mirroring the package path that you specify are
last, in this case, org\java17recipes\chapter01\recipe01_05. An
identical structure is created under the bin\classes directory when
you compile your code. Note that if using another IDE, you may see
differences in the directories that are created.
20
Chapter 1 Getting Started with Java 17
JavaBeans-style Classes
Next in the solution example is a class definition following the JavaBeans pattern.
The definition of HelloMessage follows a pattern that you often encounter in Java
programming, and we include it for that reason. The class is simple, capable of holding a
single string field named message.
Three methods are defined in the class.
Note Accessor methods are used in JavaBeans classes to access any privately
declared class members. In this case, the private variable identified as message
can be accessed using these methods. Accessor methods are more commonly
referred to as getters and setters.
Methods beginning with set and get are the setter and getter methods. The IDE
generates these methods. The message variable is private to the class, which means you
have no direct access to message from outside the class.
You see the this keyword used in the class. It is a special keyword in Java that
references the current object. Its use is redundant but would be needed if any of the
methods happened to create variables of their own that were also named message: the
21
Chapter 1 Getting Started with Java 17
setter is mandatory due to the parameter name. It is common practice to use the this
keyword to reference the class members from within the getter and setter methods,
mostly for the latter.
It is common in Java to mediate access to class variables through setter and getter
methods like in our example. Those methods represent a contract of sorts with other
classes and your main program: public methods let the class state to be read or written,
but the external code is unaware of the mapping. Their benefit is that you can change
the storage implementation of HelloMessage however you like. It has its fields and state
information saved and restored independently from the type of storage. The other code
that depends on HelloMessage continues to work properly so long as you maintain the
external behavior of setMessage() and getMessage().
22
Chapter 1 Getting Started with Java 17
The pattern in the solution is common in Java programming. The main() method
is where execution begins. Variables are defined, and objects are created using the new
operator. Object variables are often set and retrieved using setter and getter methods.
Solution
Set the CLASSPATH variable equal to the directory location of the user-defined Java classes
or Java Archive (JAR) files you need to have access to to execute your application. Let’s
say that you have a directory named JAVA_DEV located at the root of your OS drive, and
all the files your applications need to access are located in this directory. If this is the
case, you would execute a command such as the following.
set CLASSPATH=C:\JAVA_DEV\some-jar.jar
export CLASSPATH=/JAVA_DEV/some-jar.jar
Alternately, the javac command provides an option for specifying the location of
resources to be loaded for an application. On all platforms, setting the CLASSPATH using
this technique can be done via the -classpath option as follows.
Of course, the file path uses the backslash (\) on Microsoft Windows machines.
Note The javac –cp option may be used, rather than specifying the
-classpath option.
23
Chapter 1 Getting Started with Java 17
How It Works
Java implements the concept of a classpath. This is a directory search path that you can
specify system-wide using the CLASSPATH environment variable. You can also specify the
classpath for a specific invocation of the JVM via the java command’s -classpath option.
When executing Java programs, the JVM finds and loads classes as needed using the
following search order.
1. The classes that are fundamental to the Java platform and are
contained in the Java installation directory
2. Any packages or JAR files that are located within the extension
directory of the JDK
You may need to access more than one directory or JAR file for an application. This
could be the case if your dependencies are located in more than one location. To do so,
simply use the delimiter for your operating system (a ; for Windows and a : for Unix OS)
as a separator between the locations specified by the CLASSPATH variable. The following
is an example of specifying multiple JAR files in the CLASSPATH environment variable on
Unix and Linux systems.
export CLASSPATH=/JAVA_DEV/some-jar.jar:/JAVA_LIB/myjar.jar
When loading the resources for a Java application, the JVM loads all the classes
and packages specified in the first location, followed by the second, and so on. This is
important because the order of loading may make a difference in some instances to
avoid interfering with one another.
Note JAR files package applications and Java libraries into a distributable
format. If you have not packaged your application in that manner, you may simply
specify the directory or directories in which your .class files reside.
24
Chapter 1 Getting Started with Java 17
Sometimes you want to include all JAR files within a specified directory. Do that
by specifying the wildcard character (*) after the directory containing the files. The
following is an example.
Specifying a wildcard tells the JVM that it should only load JAR files. It does not load
class files located in a directory specified with the wildcard character. You need to specify
a separate path entry for the same directory if you also want the class files. The following
is an example.
Subdirectories within the classpath are not searched. To load files contained within
subdirectories, those subdirectories and/or files must be explicitly listed in the classpath.
However, Java packages that are equivalent to the subdirectory structure are loaded.
Therefore, any Java classes that reside within a Java package that is equivalent to the
subdirectory structure are loaded.
Note It is a good idea to organize your code; it is also good to organize where
you place your code on the computer. A good practice is to place all your Java
projects within the same directory; it can become your workspace. Place all the
Java libraries that are contained in JAR files into the same directory for easier
management. You can also use tools like Maven and Gradle to organize your
project.
25
Chapter 1 Getting Started with Java 17
Solution
Create Java packages and place source files within them. Java packages can organize
logical groups of source files within an application. Packages can help organize code,
reduce naming conflicts among different classes and other Java-type files, and provide
access control. To create a package, simply create a directory within the root of your
application source folder and name it. Packages are usually nested within each other and
conform to a standard naming convention. For this recipe, assume that the organization
is named JavaBook and makes widgets. To organize all the code for the widget
application, create a group of nested packages conforming to the following directory
structure.
/org/javabook
Any source files placed within a package must contain the package statement as the
first line in the source. The package statement lists the name of the package in which
the source file is contained. For instance, suppose that the main class for the widget
application is named JavaBookWidgets.java. To place this class into a package named
org.javabook, physically move the source file into a directory named javabook, which
resides within the org directory, which resides within the root of the source folder for the
application. The directory structure should look like the following.
/org/javabook/JavaBookWidgets.java
package org.javabook;
/**
* The main class for the JavaBook Widgets application.
* @author
*/
public class JavaBookWidgets {
public static void main(String[] args){
System.out println("Welcome to my app!");
}
}
26
Chapter 1 Getting Started with Java 17
The first line in the source contains the package statement, which lists the name of
the package that the source file is located within. The entire package path is listed in the
statement, and dots separate the names in the path.
Note A package statement must be the first statement listed within the Java
source. However, a comment or JavaDoc comment may be written before the
package statement.
How It Works
Java packages are useful for organizing source files, controlling access to different
classes, and ensuring that there are no naming conflicts. Packages are represented by
a series of physical directories on a file system, and they can contain any number of
Java source files. Each source file must contain a package statement before any other
statements in the file. This package statement lists the name of the package in which the
source file resides. The source included the following package statement in the solution
to this recipe.
package org.javabook;
This package statement indicates that the source file resides within a directory
named javabook, which resides within a directory named org. Package naming
conventions can vary by company or organization. However, words must be in all
lowercase so that they do not conflict with any Java class file names. Many companies
or organizations use the reverse of their domain name for package naming. However,
underscores should be used if a domain name includes hyphens.
27
Chapter 1 Getting Started with Java 17
Packages are very useful for establishing levels of security as well as organization. By
default, different classes that reside within the same package have access to each other.
If a source file resides within a package different from another file it needs to use, an
import statement must be declared at the top of the source file (underneath the package
statement) to import that other file. And the source file must declare the class/interface/
enum element type as public; otherwise, the fully qualified package.class name must
be used within the code. Classes may be imported separately, as demonstrated in the
following import statement.
import org.javabook.JavaBookWidgets;
However, it is often likely that all classes and type files that reside within a package
need to be used. A single import statement utilizing a wildcard character (*) can import
all files within a named package as follows.
import org.javabook.*;
28
Chapter 1 Getting Started with Java 17
Any substantial Java application includes packages. Any Java library or application
programming interface (API) that you use includes packages. When you import classes
or types from those libraries and APIs, you are really importing packages.
Solution
Java implements eight primitive data types. There is also special support for the String
class type. Listing 1-4 shows an example declaration of each. Draw from the example to
declare the variables needed in your own application.
package org.java17recipes.chapter01.recipe01_08;
public class DeclarationsExample {
public static void main (String[] args) {
boolean booleanVal = true; /* Default is false */
29
Chapter 1 Getting Started with Java 17
Note If you’re curious about the Ukrainian letter in Listing 1-4, it is the Cyrillic
letter Ghe with upturn. You can read about its history at http://en.wikipedia
.org/wiki/Ghe_with_upturn. You can find its code point value in the chart
at www.unicode.org/charts/PDF/U0400.pdf. And the URL www.unicode
.org/charts/ is a good place to start whenever you need to find the code point
corresponding to a given character.
Variables are subject to the concept of visibility. Those created in Listing 1-5 are
visible from the main() method after being created, and they are deallocated when
the main() method ends. They have no “life” beyond the main() method and are not
accessible from outside of main().
Variables created at the class level are a different story. Such variables can be termed
as class fields or class members, as in fields or members of the class. The use of a member
can be restricted to objects of the class in which it is declared or to the package in which
it is declared, or it can be accessed from any class in any package.
package org.java17recipes.chapter01.recipe01_08;
class TestClass {
private long visibleOnlyInThisClass;
double visibleFromEntirePackage;
void setLong (long val) {
visibleOnlyInThisClass = val;
}
long getLong () {
return visibleOnlyInThisClass;
}
}
30
Chapter 1 Getting Started with Java 17
32768
3.1415926535
Members are typically bound to an object of a class. Each class object contains an
instance of each member in the class. However, you can also define static fields that
occur only once and with a single value that is shared by all instances of the given class.
Listing 1-6 illustrates the difference.
package org.java17recipes.chapter01.recipe01_08;
class StaticDemo {
public static boolean oneValueForAllObjects = false;
}
public class StaticFieldsExample {
public static void main (String[] args) {
StaticDemo sd1 = new StaticDemo();
StaticDemo sd2 = new StaticDemo();
System.out.println(sd1.oneValueForAllObjects);
System.out.println(sd2.oneValueForAllObjects);
sd1.oneValueForAllObjects = true;
System.out.println(sd1.oneValueForAllObjects);
System.out.println(sd2.oneValueForAllObjects);
}
}
31
Chapter 1 Getting Started with Java 17
false
false
true
true
The field oneValueForAllObjects was set to true only for the class instance named
sd1. Yet it is true, for instance, sd2 also. This is because of the keyword static used in
declaring that field. Static fields occur one time for all objects of their class. Moreover,
the compiler in the IDE raises a warning about that. In fact, it should be used through
StaticDemo.oneValueForAllObjects.
How It Works
Listing 1-6 illustrates the basic format of a variable declaration.
type variable;
It’s common to initialize variables when declaring them, so you often see the
following.
32
Chapter 1 Getting Started with Java 17
The String type is special in Java. It’s a class type, but syntactically you can treat it
as a primitive type. Java automatically creates a String object whenever you enclose
a string of characters within double quotes ("..."). You aren’t required to invoke a
constructor or specify the new keyword. Yet String is a class, and there are methods in
that class that are available to you. One such method is the replace() method shown at
the end of Listing 1-4.
Strings are composed of characters. Java’s char type is a two-byte construct for
storing a single character in Unicode’s UTF-16 encoding. You can generate literals of the
char type in two ways.
Some Unicode code points require five digits. These cannot be represented in
a single char value. See Chapter 12 if you need more information on Unicode and
internationalization.
Avoid using any of the primitive types for monetary values. Especially avoid either
of the floating-point types for that purpose. Refer instead to Chapter 12 and its recipe on
using the Java Money API to calculate monetary amounts (Recipe 12-10). BigDecimal
can also be useful anytime you need accurate, fixed-decimal arithmetic.
If you are new to Java, you may be unfamiliar with the String[] array notation, as
demonstrated in the examples. Please see Chapter 7 for more information on arrays. It
covers enumerations, arrays, and generic data types. Also in that chapter are examples
showing how to write iterative code to work with collections of values such as an array.
33
Chapter 1 Getting Started with Java 17
Solution
Follow one of the patterns from Listing 1-7. The listing shows the conversion from a
string to a double-precision floating-point value and shows two methods for getting back
to a string again.
package org.java17recipes.chapter01.recipe01_09;
pi = Double.parseDouble("3.14");
System.out.println(strval = String.valueOf(pi));
System.out.println(Double.toString(pi));
}
}
The output is 3.14.
How It Works
The solution illustrates some conversion patterns that work for all the primitive
types. First, there is converting a floating-point number from its human-readable
representation into the IEEE 754 format used by the Java language for floating-point
arithmetic.
pi = Double.parseDouble("3.14");
Notice the pattern. You can replace Double with Float or Long, or whatever other
type your target data type is. Each primitive type has a corresponding wrapper class by
the same name but the initial letter is uppercase. The primitive type here is a double, and
the corresponding wrapper is Double. The wrapper classes implement helper methods
such as Double.parseDouble(), Long.parseLong(), Boolean.parseBoolean(), and so
forth. These parse methods convert human-readable representations into values of the
respective types.
34
Chapter 1 Getting Started with Java 17
Going the other way, it is often easiest to invoke String.valueOf(). The String
class implements this method, which is overloaded for each of the primitive data types.
Alternatively, the wrapper classes also implement toString() methods that you can
invoke to convert values of the underlying type into their human-readable forms. It’s
your preference as to which approach to take.
Conversions targeting the numeric types require some exception handling to be
practical. You generally need to gracefully accommodate a case in which a character-
string value is expected to be a valid numeric representation, but it’s not. Chapter 9
covers exception handling in detail, and the upcoming Recipe 1-10 provides a simple
example to get you started.
Caution Literals for the Boolean type are "true" and "false". They
are case-sensitive. Any value other than these two is silently interpreted as
false when converting from a string using the Boolean parseBoolean()
conversion method.
Solution
Run the application using the java utility, and specify the arguments that you want to
pass into it after the application name. If you’re passing more than one argument, each
should be separated by a space. For example, suppose you want to pass the arguments to
the class created in Listing 1-8.
35
Chapter 1 Getting Started with Java 17
First, make sure to compile the program so that you have a .class file to execute.
You can do that via the javac utility at the command line or terminal.
Therefore, open a command prompt or a terminal window for compiling and
executing your Java class. Now issue a java command to execute the class and type
some arguments on the command line following the class name. The following example
passes two arguments.
Luciano
Manelli
Spaces separate arguments. Enclose strings in double quotes when you want to pass
an argument containing spaces or other special characters. The following is an example.
The double quotes translate the "Luciano Manelli" string into a single argument.
36
Chapter 1 Getting Started with Java 17
How It Works
All Java classes that are executable from the command line or terminal contain a main()
method. If you look at the signature for the main() method, you can see that it accepts
a String[] argument. In other words, you can pass an array of String objects into the
main() method. Command-line interpreters such as the Windows command prompt
and the various Linux and Unix shells build an array of strings out of your command-line
arguments and pass that array to the main() method on your behalf.
The main() method in the example displays each passed argument. First, the length
of the array named args is tested to see whether it is greater than zero. If it is, the method
loop through each of the arguments in the array executes a for loop, displaying each
argument along the way. If there are no arguments passed, the length of the args array
is zero, and a message indicating this is printed; otherwise, you see a different message
followed by a list of arguments.
Command-line interpreters recognize spaces and sometimes other characters as
delimiters. It’s generally safe to pass numeric values as arguments delimited by spaces
without bothering to enclose each value within quotes. However, as shown in the final
solution example, you should get into the habit of enclosing character-string arguments
in double quotes. Do that to eliminate any ambiguity over where each argument begins
and ends.
Note Java sees all arguments as character strings. If you pass numeric values as
parameters, they enter Java as character strings in human-readable form. You can
convert them into their appropriate numeric types using the conversion methods
shown in Recipe 1-9.
37
Chapter 1 Getting Started with Java 17
Solution
Use the java.io.BufferedReader and java.io.InputStreamReader classes to read
keyboard entry and store it into local variables. Listing 1-9 shows a program that keeps
prompting for input until you enter some characters representing a valid value of type long.
package org.java17recipes.chapter01.recipe01_11;
import java.io.*;
public class AcceptingInput {
public static void main(String[] args){
BufferedReader readIn = new BufferedReader(
new InputStreamReader(System.in)
);
String numberAsString = "";
long numberAsLong = 0;
boolean numberIsValid = false;
do {
/* Ask the user for a number. */
System.out.println("Please enter a number: ");
try {
numberAsString = readIn.readLine();
System.out.println("You entered " + numberAsString);
} catch (IOException ex){
System.out.println(ex);
}
/* Convert the number into binary form. */
try {
numberAsLong = Long.parseLong(numberAsString);
numberIsValid = true;
} catch (NumberFormatException nfe) {
System.out.println ("Not a number!");
}
} while (numberIsValid == false);
}
}
38
Chapter 1 Getting Started with Java 17
The first two inputs did not represent valid values in the long data type. The third
value was valid, and the run ended.
How It Works
Quite often, our applications need to accept user input of some kind. Granted, most
applications are not used from the command line or terminal nowadays, but having
the ability to create an application that reads input from the command line or terminal
helps lay a good foundation and may be useful in some applications or scripts. Terminal
input can also be useful in developing administrative applications that you or a system
administrator may use.
Two helper classes were used in the solution to this recipe. They are
java.io.BufferedReader and java.io.InputStreamReader. The early portion
of the code that uses those classes is especially important.
The innermost object in this statement is System.in. It represents the keyboard. You
do not need to declare System.in. Java’s runtime environment creates the object for you.
It is simply available to be used.
39
Chapter 1 Getting Started with Java 17
System.in provides access to raw bytes of data from the input device, which is the
keyboard in our example. The InputStreamReader class’s job is to take those bytes and
convert them into characters in your current character set. System.in is passed to the
InputStreamReader() constructor to create an InputStreamReader object.
InputStreamReader knows about characters but not about lines. The
BufferedReader class’s job is to detect line breaks in the input stream and enable you
to conveniently read a line at a time. BufferedReader also aids efficiency by allowing
physical reads from the input device to be done in different-size chunks than when your
application consumes the data. This aspect can make a difference when the input stream
is a large file rather than the keyboard.
The following shows how the program in Listing 1-9 uses an instance (named
readIn) of the BufferedReader class to read a line of input from the keyboard.
numberAsString = readIn.readLine();
I/O calls must be wrapped in try-catch blocks. These blocks catch any exceptions
that may occur. The try part in the example fails if a conversion is unsuccessful. A failure
prevents the numberIsValid flag from being set to true, which causes the do loop to
make another iteration so that the user can try again at entering a valid value. To learn
more about catching exceptions, please see Chapter 9.
The following statement at the top of Listing 1-9 deserves some attention.
import java.io.*;
This statement makes available the classes and methods defined in the java.io
package. These include InputStreamReader and BufferedReader. Also included is the
IOException class used in the first try-catch block. NumberFormatException (used in
the second try-catch block) belongs to the java.lang package.
40
Chapter 1 Getting Started with Java 17
Solution
Use JavaDoc to place comments before any package, class, method, or field that you
want to document. To begin such a comment, write the characters /**. Then begin each
subsequent line with an asterisk (*). Lastly, close the comment with the characters */ on
a line by themselves at the end. Listing 1-10 shows a method commented with JavaDoc.
package org.java17recipes.chapter01.recipe01_12;
import java.math.BigInteger;
public class JavadocExample {
/**
* Accepts an unlimited number of values and
* returns the sum.
*
* @param nums Must be an array of BigInteger values.
* @return Sum of all numbers in the array.
*/
public static BigInteger addNumbers(BigInteger[] nums) {
BigInteger result = new BigInteger("0");
for (BigInteger num:nums){
result = result.add(num);
}
return result;
}
/**
* Test the addNumbers method.
* @param args not used
*/
41
Chapter 1 Getting Started with Java 17
Comments can be added to the beginning of the package, classes, and fields in the
same way. The comments are helpful to you and other programmers maintaining the
code, and their specific format enables the easy generation of an HTML reference to
your code.
Generate the HTML reference by invoking the JavaDoc tool. This command-line
tool parses a named Java source file and formulates HTML documentation based on the
defined class elements and JavaDoc comments. The following is an example.
javadoc JavadocExample.java
This command produces several HTML files containing the documentation for the
package, class, methods, and fields. If no JavaDoc comments exist within the source,
some default documentation is still produced. To view the documentation, load the
following file into your browser.
index.html
The file is in the same directory as the class or package you are documenting. There
is also an index-all.html file giving a strict alphabetical listing of documented entities.
Keep in mind that the same rules apply when using the JavaDoc tool as when using
javac. You must reside within the same directory as the source file or prepend the file’s
name with the path to where the file is located.
The output is shown in Figure 1-17.
42
Chapter 1 Getting Started with Java 17
How It Works
Generating documentation for applications from scratch can be quite tedious.
Maintaining documentation can be even more troublesome. The JDK comes packaged
with an extensive system for documentation known as JavaDoc. Placing special
comments throughout your code source and running a simple command-line tool
makes it easy to generate useful documentation and keep it current. Even if some of the
classes, methods, or fields in an application are not specifically commented on by the
JavaDoc utility, default documentation is produced for these elements.
43
Chapter 1 Getting Started with Java 17
JavaDoc comments should begin with a short description of the class or method.
Fields are rarely commented using JavaDoc unless they are declared public static
final (constants), in which case it is a good idea to supply a comment. A comment
can be several lines long and can even contain more than one paragraph. If you want
to break comments into paragraphs, then separate those paragraphs using the <p> tag.
Comments can include several tags that indicate various details regarding the method
or class being commented. JavaDoc tags begin with an ampersand (@), and some of the
common tags are as follows.
You may also include inline links within JavaDoc to reference URLs. To include an
inline link, use the tag {@link My Link}, where link is the actual URL that you want
to point at, and My Link is the text that you want to appear. Many other tags can be
used within JavaDoc comments, including {@literal}, {@code}, {@value org}, and
many others.
javadoc org.luciano.beans
By default, the JavaDoc tool generates HTML and places it into the same package
as documented code. That result can become a cluttered nightmare if you like to have
source files separate from the documentation. Instead, you can set up a destination for
the generated documentation by passing the –d flag to the JavaDoc tool.
44
Another Random Document on
Scribd Without Any Related Topics
Angoulême, Périgueux, Limoges, Clermont même, et jusques à la
ville de Bourges, capitale du royaume d’Aquitaine.
CHAPITRE IX.
Comment, après que la France eut gémi trente ans environ sous l’oppression des
Païens, Hastings se rendant par mer à Rome pour la soumettre à la domination
de Bier, fut jeté par une tempête auprès de Luna, ville d’Italie.
A la suite de toutes ces calamités qui furent pour les Gaules une
sorte d’expiation qu’elles eurent à supporter durant près de trente
années, Hastings, desirant élever son seigneur à une plus haute
fortune commença avec une troupe de complices à viser plus
sérieusement au diadême impérial. A la fin, après avoir tenu conseil,
ces hommes lancèrent leurs voiles à la mer, résolus d’aller attaquer à
l’improviste la ville de Rome et de s’en rendre maîtres. Mais une
grande tempête [p. 18] s’étant élevée, ils furent poussés par le vent
vers la ville de Luna, qui était appelée de ce nom, à cause de sa
beauté. Les citoyens, étonnés de l’arrivée d’une telle flotte,
barricadèrent les portes de leur ville, fortifièrent leurs remparts et
s’encouragèrent les uns les autres à la résistance. Hastings, dès qu’il
fut informé de leurs hardis projets, crut qu’il avait devant lui la ville
de Rome, et se mit aussitôt à chercher avec le plus grand soin
comment il pourrait s’en rendre maître par artifice. Enfin, envoyant à
l’évêque et au comte de cette ville les ministres de sa perfidie, il leur
fit dire qu’il n’avait point abordé en ces lieux avec intention et que
son unique desir était de retourner dans sa patrie; qu’il ne voulait et
ne demandait que la paix, et que lui-même, accablé d’une maladie
mortelle, les faisait supplier humblement de vouloir bien le faire
chrétien. Ayant entendu ces paroles, l’évêque et le comte se livrèrent
aux transports de leur joie, conclurent la paix avec ce détestable
ennemi de toute paix, et le peuple normand fut admis à entrer dans
la ville, aussi bien que ses habitans.
CHAPITRE X.
Comment Hastings, croyant que la ville de Luna était Rome, et ne pouvant la
prendre de vive force, la prit par artifice et la détruisit.
CHAPITRE XI.
Comment les Païens, ayant découvert que cette ville n’était pas Rome, se
divisèrent. — Bier voulant retourner en Danemarck, mourut dans la Frise.
— Hastings ayant fait la paix avec le roi Charles, reçut de lui la ville de Chartres,
à titre de solde, et y habita.
LIVRE SECOND.
DES FAITS ET GESTES DE ROLLON, PREMIER DUC DE NORMANDIE.
CHAPITRE PREMIER.
CHAPITRE II.
Comment Rollon s’étant révolté contre le roi pendant cinq ans, le roi lui demande
et obtient la paix frauduleusement.
CHAPITRE III.
Comment le roi attaqua dans la nuit les villes de Rollon. — De la mort de Gurim
son frère, et de l’arrivée de Rollon dans l’île de Scanza avec six navires.
C H A P I T R E I V.
C H A P I T R E V.
CHAPITRE VI.
3
D’Alstem , roi très-chrétien des Anglais, avec lequel Rollon conclut un traité
d’amitié inviolable.
CHAPITRE VII.
CHAPITRE VIII.
Comment Rollon vainquit les Walgres, qui voulurent lui résister, ainsi que Rainier,
duc du Hainaut, et Radbold, prince de Frise. — De douze navires chargés de
vivres et d’autant de vaisseaux remplis de chevaliers, que le roi des Anglais
Alstem envoya à Rollon tandis qu’il était en ce pays.
CHAPITRE IX.
Comment, l’an du Verbe incarné 876, Rollon arriva à Jumiège et de là à Rouen; et
comment l’archevêque Francon lui demanda et en obtint la paix.
LES choses ainsi terminées, les Danois et leur duc Rollon livrèrent
leurs voiles au vent, et abandonnant le fleuve de l’Escaut pour
naviguer à travers la mer, l’an 876 de l’Incarnation du Seigneur, ils
entrèrent dans les eaux de la Seine, poussés par un vent favorable,
arrivèrent à Jumiège, et déposèrent le corps de la sainte vierge
Ameltrude, qu’ils avaient transporté de Bretagne, sur l’autel de la
chapelle de saint Waast, située au delà du fleuve. Cette chapelle a
porté jusqu’à présent le nom de cette vierge. Francon, archevêque
de Rouen, ayant appris leur arrivée, voyant les murailles de la ville
renversées par eux, avec une férocité ennemie, et n’attendant aucun
secours qui pût leur résister, jugea qu’il serait plus avantageux de
leur demander la paix que de les provoquer par une démarche
quelconque à compléter la [p. 42] ruine de la ville. Se rendant donc
auprès d’eux en toute hâte, il demanda la paix, obtint ce qu’il
desirait, et conclut avec eux un solide traité. Après cela, les Daces
empressés dirigèrent promptement vers les remparts de la ville leurs
navires chargés de nombreux chevaliers, et abordèrent à la porte qui
touche à l’église de Saint-Martin. Considérant, dans la sagacité de
leur esprit, que la citadelle de la ville était bien défendue par terre et
par mer, et pouvait être aisément approvisionnée avec les épargnes,
ils résolurent d’un commun accord d’en faire la capitale de tout leur
comté.
CHAPITRE X.
Comment Rollon et les siens étant arrivés le long de la Seine, à Arques, que l’on
appelle aussi Hasdans, y construisirent des retranchemens, combattirent contre
les Francs, et en ayant tué beaucoup, mirent en fuite Renaud, leur duc; après
quoi ils détruisirent le château de Meulan.
CHAPITRE XI.
C H A P I T R E X I V.
Comment Charles, ayant appris le retour de Rollon, lui demanda et obtint une paix
de trois mois, et comment, ce délai expiré, Rollon envoya les siens jusqu’en
Bourgogne, pour enlever du butin de tous côtés.
C H A P I T R E X V.
CHAPITRE XVI.
Comment une certaine portion de l’armée de Rollon monta sur une certaine
montagne, et comment Ebble, comte du Poitou, se cacha dans la maison d’un
foulon pour éviter les Normands.
CHAPITRE XVII.
CHAPITRE XVIII.
Comment, l’an du Verbe incarné 912, Rollon et son armée reçurent le baptême, et
Rollon donna une portion de son territoire aux églises les plus vénérables avant
d’en faire la distribution entre les grands, et comme quoi il donna Brenneval à
Saint-Denis l’Aréopagite.
CHAPITRE XIX.
Comment Rollon distribua le pays à ses hommes, releva les églises détruites et les
murailles des cités, et vainquit les Bretons révoltés contre lui.
CHAPITRE XX.
De la loi qu’il publia pour que nul n’eût à prêter assistance à un voleur. — Histoire
d’un paysan et de sa femme, qu’il ordonna de pendre à une potence, à cause
d’une serpe et d’un soc de charrue qui avaient été volés.
APRÈS cela, Rollon publia une loi dans les limites du pays de
Normandie, pour que nul n’eût à prêter assistance à un voleur,
ordonnant que, s’ils venaient à être pris, tous les deux seraient
pendus à la potence, Or, il arriva peu de temps après, dans le
domaine de Longuepète, qu’un certain agriculteur, voulant se
reposer, quitta son travail et rentra dans sa maison, laissant dans
son champ ses traits avec sa serpe et le soc de sa charrue. Sa
femme, aussi malheureuse qu’insensée, enleva tous ces objets à son
insu, voulant faire une épreuve au sujet de l’édit du duc. Le paysan
étant retourné dans son champ et n’y trouvant plus ses effets,
demanda à sa femme si elle les avait pris. Elle le nia, et le paysan
alla trouver le duc, lui demandant de lui faire rendre ses outils.
Touché de compassion, le duc ordonna d’indemniser cet homme en
lui donnant cinq sous, et de faire rechercher le fer dans toute la
population des environs. Mais tous [p. 57] ayant été délivrés par le
jugement de Dieu, on en vint à faire arrêter la femme du paysan, et,
à force de coups, on l’amena à se déclarer coupable. Le duc dit alors
au paysan: « Savais-tu auparavant que c’était elle qui avait volé? »
Et le paysan répondit: « Je le savais. » A cela le duc ajouta: « Ta
bouche te condamne, méchant serviteur; » et il ordonna aussitôt de
les pendre tous les deux à la potence.
On raconte encore dans le peuple au sujet de ce duc beaucoup
d’autres choses dignes d’être rapportées; mais je me bornerai au fait
suivant.
Après avoir chassé dans la forêt qui s’élève sur les bords de la
Seine tout près de Rouen, le duc, entouré de la foule de ses
serviteurs, mangeait et était assis au dessus du lac que nous
appelons en langage familier la mare, lorsqu’il suspendit à un chêne
des bracelets d’or. Ces bracelets demeurèrent pendant trois ans à la
même place et intacts, tant on avait une grande frayeur du duc; et
comme ce fait mémorable se passa auprès de la mare, aujourd’hui
encore cette forêt elle-même est appelée la Mare de Rollon. Ainsi
comprimant et effrayant le peuple par de telles sévérités, tant par
amour pour la justice, selon que le lui enseignait la loi divine, que
pour maintenir la concorde et la paix entre ses sujets, et pour jouir
lui-même de ses honneurs en toute tranquillité, le duc Rollon
gouverna long-temps et parfaitement en paix le duché que Dieu lui
avait confié.
[p. 58]
CHAPITRE XXI.
CHAPITRE XXII.
Comment le duc, après que sa femme fut morte sans lui laisser d’enfans, s’unit de
nouveau avec Popa, qu’il avait eue pour femme avant son baptême, et mourut
après avoir fait prêter serment de fidélité à son fils Guillaume par les Normands
et les Bretons.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com