Java 9 provides an interactive REPL tool to test code snippets rapidly without a test project or main method. So we can learn or evaluate Java features easily. In this tutorial, we’re gonna look at how to use Java 9 JShell – REPL.
Contents
I. Start JShell
1. Run
We can run JShell by jshell command available at ${JAVA_HOME}\bin directory:
This is how the JShell command line tool looks like:
Now we don’t need to create Java Project or define a public static void main(String[] args)
method for testing code. Just write and run immediately.
2. Some commands
After executing /help
command, we can see other useful commands:
For example, /help /list
shows us some deeper commands:
II. JShell features
1. Default import types
To know set of common imports, just use /import
command:
For example, java.util.stream.*
was imported by default, so the code below runs without error:
If we want to test other classes or interfaces of another package, we have to import it:
import java.nio.CharBuffer
*Note: For simple statements, we don’t need to use “semicolon”.
2. Expressions
A valid java expression will be returned a value and assigned to a variable.
In the example, $1 and $2 are assigned the values.
3. Variables
We can declare and initialize our variables:
4. Method
We can also define methods with JShell:
If rewrite the method with same name, it will be replaced.
5. Tab-Completion
Tab-Completion detection uses javac lexer, custom and table-driven code. So this helps us save time when typing only part of all characters.
For example, just type add
, then press key Tab, JShell will complete the code: addTwoNumber(
.
If we define another method:
Type add
, then press key Tab, JShell shows :
That means we just type some more characters to make it unique, then Jshell will complete it.
6. List
– list variables using /vars
– list methods using /methods
– list all things we type using /list
Using /help
command, we can see more functions.
Last updated on September 11, 2018.