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> <strong>import static java.lang.System.out</strong>

jshell> <strong>import java.util.Random</strong>

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

randomNumber ==> 4

jshell> <strong>int inputNumber = 4</strong>

inputNumber ==> 4

jshell> <strong>if (inputNumber == randomNumber) {</strong>

...> <strong>out.println("*You win.*");</strong>

...> <strong>}</strong>

*You win.*

jshell>

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.*"); }

About This Article

This article is from the book:

About the book author:

Dr. Barry Burd holds an M.S. in Computer Science from Rutgers University and a Ph.D. in Mathematics from the University of Illinois. Barry is also the author of Beginning Programming with Java For Dummies, Java for Android For Dummies, and Flutter For Dummies.

This article can be found in the category: