Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java 9 REPL (JShell)

Java 9 REPL (JShell)

Java 9 New Features Java 9 New Features

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 the Python interpreter, you can directly enter expressions and see their execution results.

Run JSHELL

$ jshell
|  Welcome to JShell -- Version 9-ea
|  For an introduction type: /help intro
jshell>

View JShell commands

Enter /help to view JShell-related commands:

jshell> /help
|  Type a Java language expression, statement, or declaration.
|  Or type one of the following commands:
|  /list [|-all|-start]
|  list the source you have typed
|  /edit 
|  edit a source entry referenced by name or id
|  /drop 
|  delete a source entry referenced by name or id
|  /save [-all|-history|-start] 
|  Save snippet source to a file.
|  /open 
|  open a file as source input
|  /vars [|-all|-start]
|  list the declared variables and their values
|  /methods [|-all|-start]
|  list the declared methods and their signatures
|  /types [|-all|-start]
|  list the declared types
|  /imports 
|  list the imported items

Execute JShell commands

The /imports 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 performs 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 multiplies the passed integer argument by 2 and returns it:

jshell> int doubled(int i){ return i*2;}
|  created method doubled(int)
jshell> doubled(6)
$3 ==> 12
jshell>

Exit JShell

Enter the /exit command to exit jshell:

jshell> /exit
| Goodbye 

Java 9 New Features Java 9 New Features