Home > Articles

  • Print
  • + Share This
This chapter is from the book

Trying Java Statements in JShell

Java 9 debuts a fun-filled, new tool to make the language easier for beginners to learn. JShell, a command-line program included in the Java Development Kit (JDK), can be used to type in a single Java statement and see what it does.

JShell is a language shell, an interactive environment that makes it possible to play with Java by entering commands. Each command is a Java statement. Once you hit Enter, the statement is executed by the JVM as if it was part of a complete Java program.

To run JShell, in your file system find the folder where you installed the JDK. This folder has a subfolder called bin. Open that folder and double-click jshell.

A window opens where you can enter Java code and see what it does.

A JShell window is shown in Figure 4.6.

FIGURE 4.6

FIGURE 4.6 Playing in the Java sandbox using JShell.

JShell commands are typed at the jshell> prompt. In Figure 4.6, a series of three statements are entered:

  1. System.out.println(Math.sqrt(19600));, which displays the square root of an integer.

  2. int x = 100;, which sets the x variable’s value.

  3. System.out.println(x);, which displays the square root of x.

After each command, JShell shows the value produced by that statement. When a variable is created, it stays in memory and can appear in subsequent statements, like how the x integer was used in Figure 4.6.

The statements in JShell don’t have to end with a semi-colon “;” character, unlike the ones in a full Java program.

When you’re ready to exit JShell, use the command /exit.

A language shell such as JShell also is called a REPL, an acronym that stands for Read-Eval-Print Loop. The term comes from the Lisp language, which featured an interactive shell beloved by programmers.

A REPL is a great hands-on way to experiment with the programming techniques you learn in this book. Take a statement you read about and try creating a similar one to see what it does.

  • + Share This
  • 🔖 Save To Your Account