JShell – Java Shell tool

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 jshett in a terminal window (see Figure 2.9).

JShell starts with a greeting, followed by a prompt:

| Welcome to JShell — Version 11.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,

jshett> 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 with the Math class:

Now type t and hit the Tab key again. The method name is completed to tog, and you get a shorter list:

jshett> Math.tog

tog( tog10( tog1p(

Now you can fill in the rest by hand:

jshett> Math.tog10(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.

Source: Horstmann Cay S. (2019), Core Java. Volume I – Fundamentals, Pearson; 11th edition.

Leave a Reply

Your email address will not be published. Required fields are marked *