JShell (REPL Java 9) cho phép thực thi code Java và nhận kết quả ngay. Có thể đánh giá biểu thức, thuật toán đơn giản mà không cần tạo project, compile, build. Hỗ trợ biểu thức, import, định nghĩa class, method, variable.
Khởi động JShell
Gõ jshell tại command-prompt. Các lệnh hữu ích: /exit (thoát), /reset (reset), /reload (chạy lại), /import (xem import).
Ví dụ: In tam giác sao với vòng lặp for
C:\Users\User> jshell
| Welcome to JShell -- Version 9.0.4
jshell> for(int i=0; i<10; i++) {
...> for(int j=0; j<=i; j++)
...> System.out.print("*");
...> System.out.println("");
...> }
*
**
***
****
*****
******
*******
********
*********
**********
Các biến thể khác
Tam giác vuông ngược
jshell> for(int i=10; i>0; i--) {
...> for(int j=0; j<i; j++)
...> System.out.print("*");
...> System.out.println();
...> }
Kim tự tháp (pyramid)
jshell> int n = 5;
jshell> for(int i=1; i<=n; i++) {
...> for(int j=1; j<=n-i; j++) System.out.print(" ");
...> for(int k=1; k<=2*i-1; k++) System.out.print("*");
...> System.out.println();
...> }
Sử dụng IntStream (Java 9+)
jshell> IntStream.rangeClosed(1, 5).forEach(i -> {
...> String spaces = " ".repeat(5-i);
...> String stars = "*".repeat(2*i-1);
...> System.out.println(spaces + stars);
...> })
JShell biến việc học thuật toán, vòng lặp, in pattern thành trải nghiệm tương tác, thấy kết quả ngay từng dòng code.