Sub topic 16
Differences from compiled Java and when to use JShell
This chapter assumes you have used JShell for expressions, variables, methods, classes, and slash commands, and that you know ordinary compiled Java. Here you will see where JShell's behavior departs from a .java file, what causes the differences, and how to decide between JShell and a compiled program.
How JShell executes your input
JShell is not a different language. It accepts Java and wraps each snippet in a synthetic class behind the scenes. A variable becomes a static field, a method becomes a static method, and an expression becomes a field initializer or a method body. The wrapper is compiled with the normal Java compiler and loaded into a separate JVM that JShell controls.
Most differences follow from this design. Because each snippet is compiled and loaded on its own, JShell can replace one declaration without restarting the session. Because the wrapper exists, JShell can drop requirements that apply to a full source file.
Rules JShell relaxes
| Area | Compiled Java | JShell |
|---|---|---|
| Entry point | Needs a class and usually `main` | Not needed. Statements, methods and variables stand alone |
| Semicolons | Required | Optional at the end of a single statement or expression |
| Redeclaring a variable | Compile error in the same scope | Allowed, even with a different type |
| Redeclaring a method | Compile error for the same signature | Replaces the earlier method |
| Checked exceptions | Must be caught or declared | Allowed uncaught at top level |
| Method order | Methods can be in any order inside a class | Forward references are accepted, but the method cannot be called until the missing method exists |
| `package` declaration | Allowed | Not allowed |
Redefinition
Redefinition is the main reason to use JShell for experiments. Typing int greeting = 5 after String greeting = "Hello" replaces the variable. Methods work the same way: declare square(int) again and JShell reports modified method square(int).
Redefinition has side effects that file-based Java never shows:
- If you redefine a class, JShell recompiles snippets that use it. Variables whose type is that class are reset to
null, because the old objects belong to the old class. - If you redefine a variable or method so that a dependent snippet no longer compiles, that dependent snippet becomes unresolved. JShell prints a message and you cannot call it until you fix it.
Checked exceptions
A statement at the top level does not need a try block or a throws clause. This line works as typed:
jshell> Thread.sleep(10)
jshell> Files.readString(Path.of("missing.txt"))
| Exception java.nio.file.NoSuchFileException: missing.txt
| (stack trace lines follow)Thread.sleep(10) is a void call, so JShell prints nothing. In a compiled program the same call needs a declaration:
public class Nap {
public static void main(String[] args) throws InterruptedException {
Thread.sleep(10);
System.out.println("done");
}
}The relaxed rule applies only to the statements you type directly. A method you declare in JShell still follows the usual compiler rules for its own body. If void pause() { Thread.sleep(10); } does not catch or declare InterruptedException, the declaration is rejected.
Modifiers on top-level declarations
Top-level declarations do not have an enclosing class that you wrote, so access and static modifiers have no meaning there. JShell ignores them and prints a warning.
jshell> static int count = 3
| Warning:
| Modifier 'static' not permitted in top-level declarations, ignored
count ==> 3The same applies to public, private and protected. Everything you declare is visible to the rest of the session. The exact warning text varies with the JDK version, and final is also treated as a modifier that JShell relaxes so that redefinition keeps working. Do not rely on final to protect a top-level variable.
Gotchas that come from session state
A compiled program starts from a known state every run. A JShell session accumulates state, and the result of a snippet depends on everything entered before it.
- Order matters. Two snippets that work in sequence may fail if you run them in the opposite order, or after a
/drop. - Hidden state. An old variable you forgot about can make a new expression give the wrong answer. Use
/vars,/methodsand/listto look at what is defined. - Not reproducible by memory. A result you got in a session is hard to repeat later. Save the working snippets with
/saveand replay them withjshell file.jsh. - Timing is misleading. Each snippet is compiled on first use, and the JVM has not warmed up. Do not use JShell to benchmark code.
- A separate JVM. The code runs in a remote JVM. If your code calls
System.exit, that remote process ends and JShell restarts it with a reset state. Check/varsafterwards.
Where JShell does not fit
JShell has no build, no packages, and no way to organize more than a few classes. The following tasks belong in compiled projects:
- Code that will ship, or code that other people must build.
- Unit tests. A test runner needs reproducible source files, not session history.
- Programs with several classes, packages, or a dependency manager such as Maven or Gradle.
- Performance measurements.
- Any program where the start-up order of initialization is important.
A middle option is source-file mode, available since Java 11. java Hello.java compiles and runs a single file in memory. It keeps the full rules of compiled Java, including main, but skips the manual compile step.
When JShell is the right tool
JShell is best when the question is small and you want the answer immediately:
- Checking what an API method returns for edge-case input, such as
"".split(",")orInteger.parseInt("+5"). - Learning a new library by loading its jar with
--class-pathand trying calls. - Testing a regular expression, date format, or stream pipeline before copying it into code.
- Teaching, where each line of output shows the effect of the line before it.
- Prototyping a small algorithm before you write a class for it.
Moving from JShell to real code
When an experiment works, convert it deliberately:
- Run
/listand keep the snippets that matter. Discard failed attempts. - Put variables in fields or locals, and put methods inside a class.
- Add
importstatements for anything that depended on JShell's default imports, such asjava.util.*. - Add
throwsclauses ortryblocks where top-level statements relied on the relaxed exception rule. - Compile it fresh and run it. This confirms the code does not depend on hidden session state.
Exercise
In a JShell session you run int total = 5, declare int doubled() { return total * 2; }, and then enter String total = "five". What happens to doubled(), and what should you check before trusting later results?
Show answer
Redeclaring total as a String replaces the variable. The method doubled() depends on the old int variable and no longer compiles ("five" * 2 is invalid), so JShell reports it as unresolved and you cannot call it until you redefine it. Check /vars and /methods to see the current state. If you are unsure, run /reset and replay your saved script. This shows that redefinition is allowed but changes dependent snippets.
Exercise
Why does Thread.sleep(10) work at the JShell prompt, but fail to compile inside a method of a .java file unless you add something? What do you add?
Show answer
JShell relaxes the checked-exception rule for statements typed at the top level. A compiled method must handle InterruptedException, either with a try/catch block or by adding throws InterruptedException to the method signature.