JShell: Java without the ceremony

A line of Java with no class, no main and no compile step — the fastest way to check what something does.

3 min read🔧 Setting Up Java

For most of Java's life, trying one line meant creating a file, declaring a class, writing a main, compiling and running. JShell removed all of that, and it is the fastest way to answer "what does this actually do".

What it looks like

plaintext
$ jshell
jshell> int x = 2 + 3
x ==> 5
 
jshell> x * 10
$2 ==> 50
 
jshell> "hello".toUpperCase()
$3 ==> "HELLO"
 
jshell> /exit

No class. No main. No semicolon required at the end of a line. Each expression is evaluated and its result printed — and given a name ($2, $3) so you can use it in the next line.

That is the whole idea: Java as a conversation, the way the terminal is a conversation with the machine.

What it is for

Checking what a method does. Rather than reading the documentation for String.split and guessing:

plaintext
jshell> "a,b,,,".split(",").length
$1 ==> 2
 
jshell> "a,b,,,".split(",", -1).length
$2 ==> 5

Two lines, and you now know something that catches people out in production.

Trying an API before committing to it. Import and use it; if it is awkward in JShell it will be awkward in your code.

Settling an argument. "Does Integer.valueOf(128) == Integer.valueOf(128) return true?" is a question with an answer, and it takes eight seconds to get.

Teaching and learning. Every example in this course that prints something is a thing you can paste and watch.

The commands worth knowing

Anything starting with / is JShell itself rather than Java:

CommandDoes
/listshow what you have entered so far
/varsthe variables you have defined
/importswhat is imported (a useful set already is)
/editopen a multi-line editor for something you are building up
/save file.jshwrite your session out
/open file.jshread one back in
/helpall of them
/exitleave

/list is the one you will use. A session drifts, and seeing what you actually typed is often the answer.

What it will not do

It is a scratchpad, not a development environment. It has no project, no dependency management (you can add a classpath with --class-path, and it is fiddly), and no persistence beyond /save.

It is also not how you should learn program structure. A language where everything is a top-level expression is not Java, and a beginner who lives in JShell arrives at their first class confused about why anything needs a main. Use it to check a fact, then go and write the file.

Misconceptions

  • "JShell is a different Java." Same language, same library, same JVM. It wraps what you type in the machinery Java needs and hides it.
  • "Semicolons are optional in Java now." In JShell, at the end of an entry. In a file, no.
  • "It is for beginners." It is quickest for people who already know what they are checking. Beginners get the most from it alongside real files, not instead of them.
Progress is saved on this device and to your account when signed in.