Many programming languages like Python. Scala provide an interactive command line tool where you can type a statement and immediately see the result. In Java such a tool was missing till Java 8. Finally in Java 9, the Java Shell Tool or JShell in short is added which is an interactive tool for learning the Java programming language, prototyping Java code, testing the parts of the code.
JShell is a Read-Evaluate-Print Loop (REPL) which-
- Reads the entered statements, declarations and expressions.
- Evaluates them
- Immediately show the result (Print them)
- Goes back to command line (Loop)
How JShell is useful
Since Java is object oriented programming language so it requires the complete setup of declaring a class and having at least main method for even a simple program like printing “Hello World”.
Another scenario is trying to test a part of the code before integrating it with the application.
Without JShell these scenarios would involve-
- Write a complete program in IDE.
- Compile the program
- Fix compile time errors, if any.
- Run the program.
- Figure out logical errors or runtime errors
- Fix those errors
- Repeat the process.
JShell helps you try out code and easily explore options as you develop your program. Rather than going through the whole process as mentioned above you can test individual statements or small portions, try out different variations of a method and experiment with unfamiliar APIs within the JShell session.
For example suppose you have just upgraded to Java 12 from Java 8 and want to try out new String methods like repeat() or isBlank() added in Java 11. Rather than directly using in your code you can start a JShell session and practice there to get used with these methods and then use it properly in your application.
jshell> String str = "test"; str ==> "test" | created variable str : String jshell> str.repeat(5); $2 ==> "testtesttesttesttest" | created scratch variable $2 : String jshell> System.out.println(str.is) isBlank() isEmpty() jshell> System.out.println(str.isBlank()); false
Note that JShell provides code completion using Tab key.
How to start and stop JShell
Prerequisite for using JShell is that you have JDK 9 or above installed. Also set the Path to Java installation directory so that you are not restricted to start JShell only from the Java installation directory.
To start JShell, enter the jshell command on the command line.
F:\NETJS>jshell | Welcome to JShell -- Version 12.0.1
To start JShell in verbose mode use the -v option
F:\NETJS>jshell -v | Welcome to JShell -- Version 12.0.1 | For an introduction type: /help intro
To exit JShell, enter /exit.
jshell> /exit | Goodbye
Print Hello World in JShell
In the section “How JShell is useful” I mentioned how you have to go through the process of creating a class and have a main method even for printing a statement, not anymore with JShell!
jshell> System.out.println("Hello World") Hello World
Note that statement is not terminated with a semicolon. JShell automatically adds terminating semicolons to the end of a complete snippet if not entered.
Declaring variables in JShell
JShell accepts variable declarations, method and class definitions, imports and expressions. Let's start with variable declaration using JShell.
Declaring a string-
jshell> String s = "JShell"; s ==> "JShell" | created variable s : String
Declaring a double variable-
jshell> double d = 1.45 d ==> 1.45 | created variable d : double
A variable once declared is retained thought out the lifetime of the JShell session. After declaring String variable we declared another variable but String s is retained, if I print s I still get the value.
jshell> System.out.println(s) JShell
Changing type of variable
You can change the type of a variable in JShell even in incompatible ways. For example with in the same session of JShell type of s can be changed from String to int.
jshell> int s = 7 s ==> 7 | replaced variable s : int | update overwrote variable s : String jshell> System.out.println(s) 7
Scratch variables in JShell
When an expression is entered that is not assigned to a named variable, a scratch variable is created so that the value can be referenced later. Scratch variable name start with a '$' sign.
jshell> 1 + 3 $3 ==> 4 | created scratch variable $3 : int jshell> System.out.println($3); 4
Creating methods in JShell
You can create a method in JShell and invoke it from JShell too.
Creating method-
jshell> double multiply(int a, int b){ ...> return a * b; ...> } | created method multiply(int,int)
Invoking method-
jshell> System.out.println(multiply(91, 23)); 2093.0
Creating Classes in JShell
You can also create a class in JShell.
jshell> class HelloWorld{ ...> void display(){ ...> System.out.println("Hello World"); ...> } ...> } | created class HelloWorld
From the JShell itself you can create instance of the class and execute its methods.
jshell> new HelloWorld().display(); Hello World
Forward References in JShell
JShell accepts method definitions that reference methods, variables, or classes that aren’t yet defined. Note that you won't be able to execute a method until all the forward references are defined. For example you have defined a method to calculate area of the circle which refernces yet to be defined variable and method.
jshell> double area(double radius){ ...> return PI * square(radius); ...> } | created method area(double), however, it cannot be invoked until variable PI, and method square(double) are declared
As you can see JShell warns you that the method has forward references that need to be defined. If you try to execute area() method without doing that you will get an error.
jshell> System.out.print(area(5)); | attempted to call method area(double) which cannot be invoked until variable PI, and method square(double) are declared.
Defining all the required elements and then executing method.
jshell> double PI = 3.1415926535 PI ==> 3.1415926535 | created variable PI : double jshell> double square(double d){ ...> return d * d; ...> } | created method square(double) | update modified method area(double) jshell> System.out.print(area(5)); 78.5398163375
Exception handling in JShell
JShell also has full exception handling support and prints the stack trace in case of exception.
jshell> int divide(int x, int y) { ...> return x/y; ...> } | created method divide(int,int) jshell> divide(5, 0) | Exception java.lang.ArithmeticException: / by zero | at divide (#18:2) | at (#19:1)
JShell Commands
JShell has a set of commands to control the environment and display information within a session. Any JShell command starts with a leading forward slash (/) which distinguishes it from snippets. Here is a list of some of the JShell commands and how to use them.
/vars command
List the declared variables and their values.
jshell> /vars | String $2 = "testtesttesttesttest" | String str = "test" | double d = 1.45 | int s = 7 | double PI = 3.1415926535 | int $19 = 0
/methods Command
List the declared methods and their signatures.
jshell> /methods | double multiply(int,int) | double area(double) | double square(double) | int divide(int,int)
/list Command
List the source code you have typed.
jshell> /list 2 : str.repeat(5); 3 : System.out.println(str.isBlank()); 4 : System.out.println("Hello World") 5 : String str = "test"; 7 : double d = 1.45; 8 : System.out.println(s) 9 : int s = 7; 10 : System.out.println(s) 11 : double multiply(int a, int b){ return a * b; } 12 : System.out.println(multiply(91, 23)); 13 : double area(double radius){ return PI * square(radius); } 14 : System.out.print(area(5)); 15 : double PI = 3.1415926535; 16 : double square(double d){ return d * d; } 17 : System.out.print(area(5)); 18 : int divide(int x, int y) { return x/y; } 19 : divide(5, 0)
Getting list of available commands
You can get the list of available JShell commands by typing forward slash (/) accompanied by tab.
jshell> / /! /? /drop /edit /env /exit /help /history /imports /list /methods /open /reload /reset /save /set /types /vars <press tab again to see synopsis>
/help Commamd
Gives information about JShell commands and how to use JShell tool.
For example getting help about /imports command.
jshell> /help /imports | | /imports | ======== | | List the current active imports. This will include imports from | startup snippets.
/imports Command
List the imported items. JShell imports few packages by default so you will get some values when using this command even if you don’t import any package yourself.
jshell> /import | 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.*
That's all for this topic JShell in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Basics Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment