Java 9 REPL (JShell)
REPL (Read Eval Print Loop) means an interactive programming environment.
JShell is an interactive programming environment tool newly added in Java 9. It allows you to execute Java statements without wrapping them in classes or methods. Similar to Python's interpreter, you can directly input expressions and view the execution results.
Execute JShell
$ jshell | Welcome to JShell -- Version 9-ea | For an introduction type: /help intro jshell>
View JShell commands
Enter/helpYou can view JShell-related commands:
jshell> /help | Type a Java language expression, statement, or declaration. | Or type one of the following commands: | /list [<name or id>|-all|-start] | list the source you have typed | /edit <name or id> | edit a source entry referenced by name or id | /drop <name or id> | delete a source entry referenced by name or id | /save [-all|-history|-start] <file> | Save snippet source to a file. | /open <file> | open a file as source input | /vars [<name or id>|-all|-start] | list the declared variables and their values | /methods [<name or id>|-all|-start] | list the declared methods and their signatures | /types [<name or id>|-all|-start] | list the declared types | /imports | list the imported items
Execute JShell commands
/importsThe command is used to view imported packages:
jshell> /imports | import java.io.* | import java.math.* | import java.net.* | import java.nio.file.* | import java.util.* | import java.util.concurrent.* | import java.util.function.* | import java.util.prefs.* | import java.util.regex.* | import java.util.stream.* jshell>
JShell Performing Calculations
The following example performs simple calculations in JShell:
jshell> 3+1 $1 ==> 4 jshell> 13%7 $2 ==> 6 jshell> $2 $2 ==> 6 jshell>
JShell Creating and Using Functions
Create a function doubled() that takes an integer parameter, multiplies it by 2, and returns it:
jshell> int doubled(int i){ return i*2;}
| created method doubled(int)
jshell> doubled(6)
$3 ==> 12
jshell>
Exiting JShell
Enter the /exit command to exit jshell:
jshell> /exit | GoodbyeOther Extensions
Java 9 New Features