概述

  1. JShell 在 JDK 9 中正式发布
  2. JShell API 和工具提供了一种在 JShell 状态交互式评估 Java 编程语言的声明语句表达式的方法
  3. JShell 的状态包括不断发展代码执行状态
  4. 为了快速调查和编码,语句表达式不需要出现在方法中,变量方法也不需要出现在
  5. JShell 在验证简单问题时,比 IDE高效

启动 JShell

1
2
3
4
5
$ jshell
| Welcome to JShell -- Version 17.0.9
| For an introduction type: /help intro

jshell>

详细模式 - 提供更多的反馈结果,观察更多细节

1
2
3
4
5
$ jshell -v
| Welcome to JShell -- Version 17.0.9
| For an introduction type: /help intro

jshell>

退出 JShell

1
2
3
4
5
6
$ jshell -v
| Welcome to JShell -- Version 17.0.9
| For an introduction type: /help intro

jshell> /exit
| Goodbye

JShell 命令

image-20241202184743423

语句

立即执行

1
2
3
4
5
6
7
8
$ jshell -v
| Welcome to JShell -- Version 17.0.9
| For an introduction type: /help intro

jshell> System.out.println("Helllo, World");
Helllo, World

jshell>

声明

可覆盖

  1. JShell 支持变量重复声明
  2. JShell 是一个有状态工具,可以很好地处理多个有关联语句
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$ jshell -v
| Welcome to JShell -- Version 17.0.9
| For an introduction type: /help intro

jshell> String language = "Rust";
language ==> "Rust"
| created variable language : String

jshell> String ok = switch(language) {
...> case "Rust" -> "Yes";
...> default -> "No";
...> };
ok ==> "Yes"
| created variable ok : String

jshell> System.out.println(ok);
Yes

jshell>

jshell> language = "Go"
language ==> "Go"
| assigned to language : String

jshell> ok = switch(language) {
...> case "Rust" -> "Yes";
...> default -> "No";
...> };
ok ==> "No"
| assigned to ok : String

jshell> System.out.println(ok);
No

为了方便评估,可以使用 JShell 运行变量的重复声明类型变更

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$ jshell -v
| Welcome to JShell -- Version 17.0.9
| For an introduction type: /help intro

jshell> String language = "Rust";
language ==> "Rust"
| created variable language : String

jshell> language = "Go";
language ==> "Go"
| assigned to language : String

jshell> int language = 1;
language ==> 1
| replaced variable language : int
| update overwrote variable language : String

jshell> language = 2;
language ==> 2
| assigned to language : int

可编译的代码中,在一个变量作用域内,不允许重复声明,也不允许改变类型

表达式

  1. 在 Java 程序中,语句最小可执行单位,而表达式不能单独存在
  2. JShell 支持表达式的输入
1
2
3
$ jshell> 1+1
$1 ==> 2
| created scratch variable $1 : int

可以直接评估表达式,不再需要依附于一个语句

1
2
3
4
5
6
7
$ jshell> "Hello, world" == "Hello, world"
$2 ==> true
| created scratch variable $2 : boolean

jshell> "Hello, world" == new String("Hello, world")
$3 ==> false
| created scratch variable $3 : boolean