What are the rules we need to follow in JShell in Java 9?


Java 9 introduced an interactive REPL (Read-Evaluate-Print-Loop) tool: JShell, and it allows us to execute code snippets and get an immediate result. A snippet is an instruction that can use standard Java syntax. It represents a single expression, statement, or declaration.

Below are some of the rules we need to follow while using the JShell tool.

Rules for JShell tool:

  • A snippet is like import declarations, class declarations, method declarations, interface declarations, field declarations, statements, and primary expressions.
  • The package declarations are not allowed. JShell code is placed under the transient JShell package.
  • The access modifiers: public, protected, and private, and the modifiers: final and static are not allowed in top-level declarations. If provided they are ignored by a warning.
  • The modifiers: default and synchronized do not allow at all in the top-level declarations. However, it can allow in a nested context.
  • An abstract modifier can be allowed only in classes.
  • When user input is incomplete (for instance, we type only System.out and skip the println part), JShell auto-completion API prompts for a more user input.
  • If the user input is complete, but there is no semicolon, JShell can append it automatically.


In the below sample code snippet, we have created Employee class with necessary getter methods and instantiate it using the new operator.

Snippet

jshell> class Employee {
   ...>    private String firstName;
   ...>    private String lastName;
   ...>    private String designation;
   ...>    public Employee(String firstName, String lastName, String designation) {
   ...>       this.firstName = firstName;
   ...>       this.lastName = lastName;
   ...>       this.designation = designation;
   ...>    }
   ...>    public String getFirstName() {
   ...>       return firstName;
   ...>    }
   ...>    public String getLastName() {
   ...>       return lastName;
   ...>    }
   ...>    public String getDesignation() {
   ...>       return designation;
   ...>    }
   ...>    public String toString() {
   ...>       return "Name = " + firstName + ", " + lastName + " | " +
   ...>              "designation = " + designation;
   ...>    }
   ...> }
| created class Employee

jshell> Employee emp = new Employee("Sai", "Adithya", "Content Developer");
emp ==> Name = Sai, Adithya | designation = Content Developer

Updated on: 27-Apr-2020

115 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements