How to use JShell in Java 9 for interactive programming
Since the introduction of JShell in Java 9, developers can perform interactive Java programming through JShell. JShell is a REPL (Read-Eval-Print Loop) tool for interactive code execution. It allows developers to enter and execute Java code directly on the command line without writing a complete Java class file. This article will introduce how to use JShell for interactive programming and provide some code examples.
java -version
on the command line to confirm that the Java version is 9 or higher. Next, run the jshell
command on the command line to start JShell. 1 1
as an example, press Enter, JShell will immediately calculate and output the result 2
. This method can be used to check some simple Java code, such as calculating expressions, verifying output, etc. var
keyword to declare a variable, for example: var x = 10;
. You can then use this variable directly, for example: x 5
will return 15
. Variables declared in JShell do not need to specify a type. JShell will automatically infer the type of the variable based on the context. /method
command to define a method. For example: /method int add(int a, int b) { return a b; }
defines a method add
, which accepts two parameters of type int
, and return their sum. You can call this method, for example: add(3, 5)
will return 8
. java.util.List
as an example, use the /import
command to import this class, and then use it directly to create List
objects and call methods. For example: List<String> list = new ArrayList<>();
and list.add("Hello");
. /
, then enter a new line of code again. JShell will recognize these multiple lines of code and execute them. This is useful for writing complex logic or how to define a class. The following is an example of using JShell for interactive programming:
// 打印Hello World! System.out.println("Hello World!"); // 定义一个名为Person的类 class Person { private String name; Person(String name) { this.name = name; } public String getName() { return name; } } // 创建一个Person对象并输出其名称 Person p = new Person("John"); System.out.println(p.getName());
This is only an example of some of the functions of JShell. It also has more powerful functions, such as: auto-completion , history records, exception handling, etc. By using JShell, you can quickly verify the correctness of code snippets without having to write complete Java class files. It is a useful tool for learning Java and debugging code.
Summary
This article introduces how to use JShell in Java 9 for interactive programming. We learned about the basic usage of JShell, such as executing expressions, declaring variables, defining methods, etc., and provided corresponding code examples. I hope this article can help you use JShell for interactive programming more efficiently.
The above is the detailed content of How to use JShell in Java 9 for interactive programming. For more information, please follow other related articles on the PHP Chinese website!