Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีกำหนด Expressions, Variables และ Methods ใน JShell ของ Java 9

JShell: REPL สำหรับ Java

JShell ประเมิน declarations, statements, expressions ทันทีที่พิมพ์ แสดงผลลัพธ์ทันที รันจาก command prompt

1. Expression (นิพจน์)

พิมพ์นิพจน์ Java ใดๆ ได้: arithmetic, string manipulation, method call ผลลัพธ์จะถูก assign ให้ scratch variable ($1, $2, ...) อัตโนมัติ

jshell> 10 * 5
$1 ==> 50
jshell> 77 % 3
$2 ==> 2
jshell> $1 + $2
$3 ==> 52
jshell>

2. Variable (ตัวแปร)

ประกาศตัวแปรเหมือน Java ปกติ มี scope อยู่ใน session

jshell> String str = "Tutorialspoint"
str ==> "Tutorialspoint"
jshell> str
str ==> "Tutorialspoint"
jshell>

3. Method (เมธอด)

กำหนดเมธอดได้เหมือนใน class ใช้งานได้ตลอด session จนกว่าจะออกจาก JShell

jshell> int sum(int x, int y) {
...>     return x + y;
...> }
| created method sum(int,int)
jshell> sum(10,20)
$2 ==> 30
jshell>

สรุป

  • Expression -> ผลลัพธ์เก็บใน scratch variables ($n)
  • Variable -> ประกาศแบบปกติ มีชื่อ ชนิดข้อมูล
  • Method -> กำหนดได้แบบ multi-line ใช้ prompt ...>
  • ทุกอย่างคงอยู่ใน session จนกว่าจะ /exit