Home  >  Article  >  Java  >  What rules do we need to follow in JShell in Java 9?

What rules do we need to follow in JShell in Java 9?

WBOY
WBOYforward
2023-09-08 19:09:02458browse

在Java 9的JShell中,我们需要遵循哪些规则呢?

Java 9 introduces an interactive REPL (Read-Evaluate-Print-Loop) tool: JShell , which allows us to execute code snippets and get results immediately. A snippet is a directive that can use standard Java syntax. It represents a single expression, statement or statement.

When using the JShell tool, we need to follow some of the following rules.

Rules for JShell tools:

  • Code snippets can be import declarations, class declarations, method declarations, interface declarations, field declarations, statements and main expressions.
  • PackageStatement not allowed. The JShell code is placed under the JShell package of transient. The
  • public, protected, and private access modifiers, as well as final and static These modifiers are not allowed in top-level declarations. If these modifiers are provided, they are ignored and a warning is given.
  • default and synchronized These modifiers are not allowed at all in top-level declarations. However, it is allowed in nested contexts.
  • abstractModifiers are only allowed within classes.
  • When the user input is incomplete (for example, we only entered System.out and skipped the println part), the JShell autocomplete API will prompt the user Continue typing.
  • If the user input is complete but there is no semicolon, JShell will automatically append it.

In the following sample code snippet, we have created an Employee class with necessary getter methods and Instantiate using the new operator.

Code snippet

<strong>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</strong>

The above is the detailed content of What rules do we need to follow in JShell in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete