Sub topic 4
How JShell Reads Input: Snippets and Optional Semicolons
Assume you have a JDK 9 or later, basic Java syntax, and comfort using a terminal. JShell reads Java source a piece at a time. Each piece is called a snippet. JShell compiles and evaluates a complete snippet before showing feedback.
A snippet is one unit of input
A snippet can be an expression, variable declaration, method, class, import, or statement. It does not need to be inside a class or a main method.
2 + 3
int count = 4
System.out.println(count)JShell evaluates each complete line:
$1 ==> 5
count ==> 4
4An expression produces a result. A declaration usually reports the name and value of the new variable. A statement such as System.out.println produces its own output.
JShell remembers successful snippets. Later snippets can use their variables, methods, and types.
Semicolons are often optional
For a single simple snippet, JShell can usually infer where the input ends, so you may omit the semicolon:
int width = 8
int height = 5
width * heightYou can also write the same input with semicolons:
int width = 8;
int height = 5;
width * height;The semicolon still matters when you put multiple statements in one snippet. It separates those statements:
int width = 8; int height = 5; width * heightWithout the separator, JShell cannot parse the input as three statements.
A semicolon is also part of some Java grammar. For example, an empty statement is written as ;, and fields or method declarations inside a class follow normal Java syntax. Use semicolons when they make the structure clearer or when ordinary Java syntax requires them.
JShell waits for complete input
JShell does not evaluate a declaration until it has enough source to parse. Braces, parentheses, and block structure tell JShell that more input may follow.
int cube(int value) {
return value * value * value;
}After the opening brace, JShell continues reading until the method body is closed. The complete method declaration becomes one snippet.
The same applies to a class:
class Temperature {
double celsius;
Temperature(double celsius) {
this.celsius = celsius;
}
}JShell may display a continuation prompt while it waits:
jshell> int cube(int value) {
...> return value * value * value;
...> }
| created method cube(int)Expression, statement, and declaration
These inputs look similar but have different roles:
| Input | Snippet kind | Typical result |
|---|---|---|
| `6 * 7` | Expression | A scratch variable such as `$1` |
| `int total = 42` | Variable declaration | A named variable |
| `System.out.println(total)` | Statement | Printed output |
A slash command such as /vars is not a Java snippet. It is a JShell command and must begin at the start of input.
Exercise
What happens when you enter int a = 2; int b = 3; a + b as one JShell input?
Show answer
The semicolons separate three statements in one complete snippet. JShell declares a and b, then evaluates a + b, producing 5.