Home  >  Article  >  Java  >  How to define expressions, variables and methods in JShell in Java 9?

How to define expressions, variables and methods in JShell in Java 9?

WBOY
WBOYforward
2023-09-13 14:05:08729browse

在Java 9中如何在JShell中定义表达式、变量和方法?

JShell 是一个读取-评估-打印循环(REPL),它会在我们输入的声明语句表达式上立即进行评估并显示结果。该工具从命令提示符中运行。

在下面的示例中,我们可以在JShell中定义表达式、变量和方法。

表达式

我们可以在JShell中输入任何有效的Java表达式。该表达式可以是算术运算字符串操作方法调用,并立即进行评估。所有的结果都会自动分配给JShell创建的变量。这些变量的前缀是 $符号。

示例

<strong>jshell> 10 * 5
$1 ==> 50

jshell> 77 % 3
$2 ==> 2

jshell> $1 + $2
$3 ==> 52

jshell></strong>

变量

JShell中定义的变量与Java程序中定义的变量相同。一旦定义了变量,它就存在于作用域中。

示例

<strong>jshell> String str = "Tutorialspoint"
str ==> "Tutorialspoint"

jshell> str
str ==> "Tutorialspoint"

jshell></strong>

方法

我们可以在JShell中定义方法,就像在Java类中定义方法一样。一旦在JShell会话中创建了一个方法,我们可以随时调用它,直到退出该会话。

示例

<strong>jshell> int sum(int x, int y) {
   ...> return x + y;
   ...> }
| created method sum(int,int)

jshell> sum(10,20)
$2 ==> 30

jshell></strong>

The above is the detailed content of How to define expressions, variables and methods 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