What are the useful commands in JShell in Java 9?

JavaObject Oriented ProgrammingProgramming

Java 9 has introduced a new interactive tool called JShell. This tool can be used to execute, test user-friendly and easy way of java classes, interfaces, enums, objects, statements and etc. JShell can do the work by evaluating the commands that user types into it. It works on the principle of REPL(Read-Evaluate-Print-Loop).

Below are some of the important commands in JShell

/var − This command can be used to get a list of all variables used. While performing the calculations, JShell creates implicit variables. As soon as we type the /var command, it displays all variables declared so far. For instance $1, $2 and $3 in the below example.

Example

jshell> 2+5
$1 ==> 7

jshell> 8%3
$2 ==> 2

jshell> 9/3
$3 ==> 3

jshell> /var
| int $1 = 7
| int $2 = 2
| int $3 = 3


 /types [option] −This command displays the type of all classes, interfaces, and enums. The [option] can be a specific name or id in which we want to see the type.

Example

jshell> class Test1 {
...>       void testMethod1() {
...>          System.out.println("TutorialsPoint");
...>    }
...> }
| created class Test1

jshell> /types Test1
| class Test1

jshell> /types Test2
| No such snippet: Test2


 /methods − This command provides us all methods declared so far. For instance, we have created a method demo() in the below example.

Example

jshell> String demo(String firstName, String lastName) {
...>       return firstName + lastName;
...>    }
| created method demo(String, String)

jshell> /methods
| String demo(String, String)


 /list − This command is one of the most useful commands in JShell. It provides us all the snippets created so far.

Example

jshell> /list

1 : 2+5
2 : 8%3
3 : 9/3
4 : class Test1 {
       void testMethod1() {
          System.out.println("TutorialsPoint");
       }
    } 
5 : String demo(String firstName, String lastName) {
       return firstName + lastName;
    }
raja
Published on 18-Feb-2020 06:50:19
Advertisements