Using Blocks in Java’s JShell

By Barry A. Burd

Java 9 comes complete with an interactive JShell environment. You type a statement, and JShell responds immediately by executing the statement. That’s fine for simple statements, but what happens when you have a statement inside of a block?

In JShell, you can start typing a statement with one or more blocks. JShell doesn’t respond until you finish typing the entire statement — blocks and all. To see how it works, look over this conversation that took place with Jshell:

jshell> import static java.lang.System.out

jshell> import java.util.Random

jshell> int randomNumber = new Random().nextInt(10) + 1

randomNumber ==> 4

jshell> int inputNumber = 4

inputNumber ==> 4

jshell> if (inputNumber == randomNumber) {

...> out.println("*You win.*");

...> }

*You win.*


In this dialogue, the text that was typed is in bold. JShell’s responses aren’t set in bold.

When you type if (inputNumber == randomNumber) { and press Enter, JShell doesn’t do much. JShell only displays a …> prompt, which indicates that whatever lines you’ve typed don’t form a complete statement. You have to respond by typing the rest of the if statement.

When you finish the if statement with a close curly brace, JShell finally acknowledges that you’ve typed an entire statement. JShell executes the statement and (in this example) displays *You win.*.

Notice the semicolon at the end of the out.println line:

  • When you type a statement that’s not inside of a block, JShell lets you omit the semicolon at the end of the statement.
  • When you type a statement that’s inside of a block, JShell doesn’t let you omit the semicolon.

When you type a block in JShell, you always have the option of typing the entire block on one line, with no line breaks, like so:
if (inputNumber == randomNumber) { out.println("*You win.*"); }