Create A Class: PART V Appendixes
Create A Class: PART V Appendixes
1196 PART V Appendixes
Now that myMeth2( ) has been defined, you can call myMeth( ).
In addition to its use in a method, you can use a forward reference in a field initializer
in a class.
Create a Class
Although JShell automatically supplies a synthetic class that wraps code snippets, you can
also create your own class in JShell. Furthermore, you can instantiate objects of your class.
This allows you to experiment with classes inside JShell’s interactive environment. The
following example illustrates the process.
Start a new JShell session and enter the following class, line by line:
class MyClass {
double v;
MyClass(double d) { v = d; }
When you finish entering the code, JShell will respond with
Now that you have added MyClass, you can use it. For example, you can create a MyClass
object with the following line:
JShell will respond by telling you that it added ob as a variable of type MyClass. Next, try the
following line:
System.out.println(ob.reciprocal());
Use an Interface
Interfaces are supported by JShell in the same way as classes. Therefore, you can declare an
interface and implement it by a class within JShell. Let’s work through a simple example.
Before beginning, start a new JShell session.
The interface that we will use declares a method called isLegalVal( ) that is used to
determine if a value is valid for some purpose. It returns true if the value is legal and false
otherwise. Of course, what constitutes a legal value will be determined by each class that
implements the interface. Begin by entering the following interface into JShell:
interface MyIF {
boolean isLegalVal(double v);
}
double start;
double end;
Notice that MyClass implements isLegalVal( ) by determining if the value v is within the
range (inclusive) of the values in the MyClass instance variables start and end.
Now that both MyIF and MyClass have been added, you can create a MyClass object
and call isLegalVal( ) on it, as shown here:
Part V
MyClass ob = new MyClass(0.0, 10.0);
System.out.println(ob.isLegalVal(5.0));
In this case, the value true is displayed because 5 is within the range 0 through 10.
Because MyIF has been added to JShell, you can also create a reference to an object of
type MyIF. For example, the following is also valid code:
MyIF ob2 = new MyClass(1.0, 3.0);
boolean result = ob2.isLegalVal(1.1);
In this case, the value of result will be true and will be reported as such by JShell.
One other point: enumerations and annotations are supported in JShell in the same way
as classes and interfaces.
1198 PART V Appendixes
$1 ==> 0.1875
As you can see, the result of the expression is computed and displayed. However, note that this
value is also assigned to a temporary variable called $1. In general, each time an expression is
evaluated directly, its result is stored in a temporary variable of the proper type. Temporary
variable names all begin with a $ followed by a number, which is increased each time a new
temporary variable is needed. You can use these temporary variables like any other variable.
For example, the following displays the value of $1, which is 0.1875 in this case.
System.out.println($1);
double v = $1 * 2;
$1 = -$1
$1 ==> -0.1875
Expressions are not limited to numeric values. For example, here is one that concatenates
a String with the value returned by Math.abs($1).
Importing Packages
As described in Chapter 9, an import statement is used to bring members of a package into
view. Furthermore, any time you use a package other than java.lang, you must import it. The
situation is much the same in JShell except that by default, JShell imports several commonly
used packages automatically. These include java.io and java.util, among several others. Since
these packages are already imported, no explicit import statement is required to use them.
For example, because java.io is automatically imported, the following statement can
be entered:
int i;
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
This is the same basic code that was discussed in Chapter 13, but no explicit import java.io
statement is required.
Keep in mind that JShell automatically imports only a handful of packages. If you want to
use a package not automatically imported by JShell, then you must explicitly import it as you
do with a normal Java program. One other point: you can see a list of the current imports by
using the /imports command.
Exceptions
In the I/O example shown in the preceding section on imports, the code snippets also
illustrate another very important aspect of JShell. Notice that there are no try/catch blocks
that handle I/O exceptions. If you look back at the similar code in Chapter 13, the code that
opens the file catches a FileNotFoundException, and the code that reads the file watches for
an IOException. The reason that you don’t need to catch these exceptions in the snippets
shown earlier is because JShell automatically handles them for you. More generally, JShell
Part V
will automatically handle checked exceptions in many cases.
1200 PART V Appendixes
You can save a session by using /save. Its simplest form is shown here:
/save filename
Here, filename specifies the name of the file to save into. By default, /save saves your current
source code, but it supports several options, of which two are of particular interest. By
specifying -all you save all lines that you enter, including those that you entered incorrectly.
You can use the -history option to save your session history (i.e., the list of the commands
that you have entered).
You can load a saved session by using /open. Its form is shown next:
/open filename
Here, filename is the name of the file to load.
JShell provides several commands that let you list various elements of your work. They
are shown here:
Command Effect
/types Shows classes, interfaces, and enums.
/imports Shows import statements.
/methods Shows methods.
/vars Shows variables.
int start = 0;
int end = 10;
int count = 5;
| int start = 0;
| int end = 10;
| int count = 5;
Another often useful command is /history. It lets you view the history of the current
session. The history contains a list of what you have typed at the command prompt.
APPENDIX
C
Compile and Run Simple
Single-File Programs
in One Step
In Chapter 2, you were shown how to compile a Java program into bytecode using the javac
compiler and then run the resulting .class file(s) using the Java launcher java. This is how Java
programs have been compiled and run since Java’s beginning, and it is the method that you will
use when developing applications. However, beginning with JDK 11, it is possible to compile
and run some types of simple Java programs directly from the source file without having to
first invoke javac. To do this, pass the name of the source file, using the .java file extension, to
java. This causes java to automatically invoke the compiler and execute the program.
For example, the following automatically compiles and runs the first example in this book:
java Example.java
In this case, the Example class is compiled and then run in a single step. There is no need
to use javac. Be aware, however, that no .class file is created. Instead, the compilation is
done behind the scenes. As a result, to rerun the program, you must execute the source file
again. You can’t execute its .class file because one won’t be created.
One use of the source-file launch capability is to facilitate the use of Java programs in
script files. It can also be useful for short one-time-use programs. In some cases, it makes it
a little easier to run simple example programs when you are experimenting with Java. It is
not, however, a general-purpose substitute for Java’s normal compilation/execution process.
Although this new ability to launch a Java program directly from its source file is appealing,
it comes with some restrictions. First, the entire program must be contained in a single source
file. However, most real-world programs use multiple source files. Second, it will always
execute the first class it finds in the file, and that class must contain a main( ) method. If the
first class in the file does not contain a main( ) method, the launch will fail. This means that
you must follow a strict organization for your code, even if you would prefer to organize it
otherwise. Third, because no .class files are created, using java to run a single-file program
does not result in a class file that can be reused, possibly by other programs. As a result of these
restrictions, using java to run a single-file source program can be useful, but it constitutes what
is, essentially, a special-case technique.
1201
1202 PART V Appendixes
As it relates to this book, it is possible to use the single source-file launch feature to try
many of the examples; just be sure that the class with the main( ) method is first in your file.
That said, it is not, however, applicable or appropriate in all cases. Furthermore, the discussions
(and many of the examples) in the book assume that you are using the normal compilation
process of invoking javac to compile a source file into bytecode and then using java to run that
bytecode. This is the mechanism used for real-world development, and understanding this
process is an important part of learning Java. It is imperative that you are thoroughly familiar
with it. For these reasons, when trying the examples in this book, it is strongly recommended
that in all cases you use the normal approach to compiling and running a Java program. Doing
so ensures that you have a solid foundation in the way Java works. Of course, you might find it
fun to experiment with the single source-file launch option!
NOTE It is possible to execute a single-file program from a file that does not use the .java extension. To do so, you
must specify the --source APIVer option, where APIVer specifies the JDK version number.
Index
& =, 31, 48, 81, 83–84
bitwise AND, 72, 73, 74–75 = = (Boolean logical operator), 81
Boolean logical AND, 81, 82, 83 = = (relational operator), 32, 80, 81, 278, 284
and bounded type declarations, 359 versus equals( ), 492–493
&& (short-circuit AND), 81, 83 !, 81, 82, 761
* !=, 80, 81
and glob syntax, 790–791 /, 67, 68
multiplication operator, 31, 67, 68 /* */, 28, 1183
regular expression quantifier, 1033 /** */, 37, 1183, 1189
used in import statement, 206, 341–342 //, 29, 1183
used with createFilter( ), 761 <, 32, 80
** (glob syntax), 791 argument index syntax, 689–690
@ <>
annotation syntax, 37, 295 diamond operator (type inference), 382–383
used with tags (javadoc), 1184, 1189 and generic type parameter, 350
| <?>, 296, 298, 360
bitwise OR, 72, 73, 74–75 <<, 72, 75–77
Boolean logical OR, 81, 82 <=, 80
|| (short-circuit OR), 81, 83 –, 67, 68
[ ], 37, 55, 56, 58, 62, 64, 67 format flag, 686
character class specification, 1033, 1037 –>
^ lambda expression arrow operator, 18, 67,
bitwise exclusive OR (XOR), 72, 73, 74–75 85, 392
Boolean logical exclusive OR (XOR), 81, 82 used with a case statement, 450, 454–459
character class specification, 1033 – –, 34, 67, 70–71
: %
used with case, 454, 458 used in format conversion specifier syntax, 677
used with a label, 112 modulus operator, 67, 69
:: ( format flag, 686, 688
constructor reference, 37, 414, 418 ( ), 29, 37, 86, 121, 131
method reference, 37, 406, 412 used in a lambda expression, 392, 396, 397
, (comma), 37, 101–102, 397 used to raise the precedence of operations,
format flag, 686, 688 37, 45, 85, 488
{ }, 29, 30, 34, 37, 49, 50, 57, 60, 87, 88, 95, 99, 231, . (period)
306, 398, 422 and calling static interface methods, 223
used with javadoc tags, 1184 dot operator, 85, 119, 125, 154, 180, 206, 223
{…} anonymous inner class syntax, 849 in import statement, 206
$ used in temporary variable name, 1198 in multileveled package statement, 200, 206
1203
1204 Index
Index 1205
Algorithms, collection, 573, 625–630, 636 areFieldsSet Calendar class instance variable, 662
allMatch( ), 1030 Argument(s), 124, 128
allocate( ), 765, 776, 778 command-line, 29, 162–163
anchor constraint field, 915–916 index, 689–690
AND expression, using instanceof in a logical, lambda expressions passed as, 401–403
474–475 and overloaded constructors, 142
AND operator passing, 144–146
bitwise (&), 72, 73, 74–75 type. See Type argument(s)
Boolean logical (&), 81, 82, 83 variable-length. See Varargs
and bounded type declarations (&), 359 wildcard. See Wildcard arguments
short-circuit (&&), 81, 83 Arithmetic operators, 67–72
AnnotatedElement interface, 301, 303, 313, 569 ArithmeticException, 229, 230, 240, 551
Annotation interface, 295, 301, 568 Array class, 569, 1040
Annotation member, 295 Array(s), 29, 55–62, 155, 196
assigning a value to an, 295, 304, 305 boundary checks, 57
default values for an, 302–303, 305 and collections, 631
obtaining the value of an, 297, 298 constructor reference for, 418
Annotation(s), 16, 294–314, 568 converting collections into, 576, 587–588
built-in, 305–307 copying with arraycopy( ), 539, 541
container, 312, 313 declaration syntax, alternative, 62
declaration example, 295 declaration using var, 64, 65
and JShell, 1197 dynamic, 585–587, 594, 637–641
marker, 303–304 and the for-each loop, 103–107
member. See Annotation member and generics, 388–389
obtaining all, 300–301 implemented as objects, 155
reflection to obtain, using, 296–301 indexes, 55, 56
repeated, 301, 312–314 initializing, 57, 60–61
restrictions on, 314 length instance variable of, 155–157
retention policies, 295–296 multidimensional, 58–62, 105–106
single-member, 304–305 one-dimensional, 55–58
type, 307–312 serialPersistentFields, 755
annotationType( ), 295 and spliterators, 634
anyMatch( ), 1030 and a stream API stream, 1009
Apache Software Foundation, 1158 string using a byte, initializing a, 485
Apache Tomcat, 1158. See also Tomcat of strings, 65, 162
APPEND, 538 and valueOf( ), 499
append( ), 505, 566, 744, 903 and varargs, 164
Appendable interface, 566, 679, 737, 744, 751 ArrayBlockingQueue class, 983
appendTo( ), 538 arraycopy( ), 540, 542
Applet, 8–9 ArrayDeque class, 585, 594–595, 643
API deprecated for removal, 11, 20 ArrayIndexOutOfBoundsException, 233,
deprecated, 11, 19 240, 632
removal of support for the, 9, 11, 19, 1065 ArrayList class, 585–588, 604, 637, 638, 1009
Applet class, 854 example using an, 598–599
Applet, Swing, 1065, 1066, 1071 examples using a stream API stream,
Application launcher (java). See java 1009–1013, 1018–1022, 1023–1024,
(Java application launcher) 1026–1029
apply( ), 419, 708, 709, 710, 1013–1014, 1018 Arrays class, 631–636, 1009
applyAsDouble( ), 708, 709, 710, 1021 ArrayStoreException, 240, 632
AreaAveragingScaleFilter class, 940 arrive( ), 970–971