jshell is Java’s built-in interactive programming tool. It allows you to type in Java code, run it immediately, and see what happens. Even though it is simple and easy to use, it is a pretty powerful computer programming tool.
jshell comes built into Java 9 and later versions, so if you have a modern Java installation, you already have it!
To start jshell, open your terminal or command prompt and type:
jshellYou should see something like:
| Welcome to JShell -- Version 17.0.2
| For an introduction type: /help intro
jshell>The jshell> prompt means jshell is ready for you to type Java code.
Let’s try a simple example. At the jshell prompt, type:
jshell> System.out.println("Hello, World!");
Hello, World!Notice how jshell immediately ran your code and showed the output "Hello, World!"
Now try this:
jshell> System.out.println("Hello, YourName!");(Replace "YourName" with your actual name)
What does jshell stand for? The "shell" part means it’s an interactive environment where you can type commands and see results immediately. This is perfect for learning Java because you can experiment right away.
In jshell, you can create variables and use them immediately:
jshell> int age = 25;
age ==> 25
jshell> String name = "Alex";
name ==> "Alex"
jshell> System.out.println("My name is " + name + " and I am " + age + " years old");
My name is Alex and I am 25 years oldNotice how jshell shows you the value that was assigned to each variable with the =⇒ arrow.
Throughout this book, you’ll see full Java programs that look like this:
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}When you see these programs, you can run just the statements inside the main method in jshell:
jshell> System.out.println("Hello, World!");This makes learning much faster because you don’t have to worry about all the extra syntax.
When you’re done with jshell, you can exit by typing:
jshell> /exitOr you can press Ctrl+D (on Mac/Linux) or Ctrl+Z then Enter (on Windows).