2.4 JShell
In the preceding section, you saw how to compile and run a Java program. Java 9 introduces another way of working with Java. The JShell program provides a “read-evaluate-print loop,” or REPL. You type a Java expression; JShell evaluates your input, prints the result, and waits for your next input. To start JShell, simply type jshell in a terminal window (see Figure 2.9).
Figure 2.9 Running JShell
JShell starts with a greeting, followed by a prompt:
| Welcome to JShell -- Version 9.0.1 | For an introduction type: /help intro jshell>
Now type an expression, such as
"Core Java".length()
JShell responds with the result—in this case, the number of characters in the string “Core Java”.
$1 ==> 9
Note that you do not type System.out.println. JShell automatically prints the value of every expression that you enter.
The $1 in the output indicates that the result is available in further calculations. For example, if you type
5 * $1 - 3
the response is
$2 ==> 42
If you need a variable many times, you can give it a more memorable name. However, you have to follow the Java syntax and specify both the type and the name. (We will cover the syntax in Chapter 3.) For example,
jshell> int answer = 6 * 7 answer ==> 42
Another useful feature is tab completion. Type
Math.
followed by the Tab key. You get a list of all methods that you can invoke on the generator variable:
jshell> Math. E IEEEremainder( PI abs( acos( addExact( asin( atan( atan2( cbrt( ceil( class copySign( cos( cosh( decrementExact( exp( expm1( floor( floorDiv( floorMod( fma( getExponent( hypot( incrementExact( log( log10( log1p( max( min( multiplyExact( multiplyFull( multiplyHigh( negateExact( nextAfter( nextDown( nextUp( pow( random() rint( round( scalb( signum( sin( sinh( sqrt( subtractExact( tan( tanh( toDegrees( toIntExact( toRadians( ulp(
Now type l and hit the Tab key again. The method name is completed to log, and you get a shorter list:
jshell> Math.log log( log10( log1p(
Now you can fill in the rest by hand:
jshell> Math.log10(0.001) $3 ==> -3.0
To repeat a command, hit the ↑ key until you see the line that you want to reissue or edit. You can move the cursor in the line with the ← and → keys, and add or delete characters. Hit Enter when you are done. For example, hit and replace 0.001 with 1000, then hit Enter:
jshell> Math.log10(1000) $4 ==> 3.0
JShell makes it easy and fun to learn about the Java language and library without having to launch a heavy-duty development environment and without fussing with public static void main.
In this chapter, you learned about the mechanics of compiling and running Java programs. You are now ready to move on to Chapter 3 where you will start learning the Java language.