Sub topic 9
Forward references and unresolved declarations
This chapter assumes you have finished the earlier chapters on methods and classes in JShell. You should be comfortable declaring a method at the top level, and you should know that redeclaring a snippet with the same signature replaces it.
What a forward reference is
A forward reference is a use of a name before that name is declared. In a compiled Java file, the order of methods inside a class does not matter, because the compiler reads the whole file before it checks any name. A REPL gets input one snippet at a time. If JShell required every name to exist when you typed a snippet, you could not write two methods that call each other.
JShell solves this by accepting some declarations whose dependencies are missing. It keeps them in a pending state and finishes them once the missing piece appears.
A method that calls a method that does not exist yet
jshell> int twice(int x) { return half(x) * 4; }
| created method twice(int), however, it cannot be invoked until method half(int) is declared
jshell> int half(int x) { return x / 2; }
| created method half(int)
jshell> twice(10)
$3 ==> 20The first snippet succeeds, and JShell reports it with a "created" message. The message ends with a condition: twice(int) exists but cannot run. When you declare half(int), twice(int) becomes usable without being retyped. JShell tracks the dependency and re-resolves it for you.
The exact wording of these messages can differ between JDK versions and feedback modes. The structure stays the same: a status ("created" or "modified"), then the unresolved name.
What happens if you call it too early
A pending method is registered, but its body cannot run. If you call it before the missing method exists, JShell refuses the call and does not throw an exception:
jshell> int twice(int x) { return half(x) * 4; }
| created method twice(int), however, it cannot be invoked until method half(int) is declared
jshell> twice(10)
| attempted to call method twice(int) which cannot be invoked until method half(int) is declaredNothing is lost. The session continues, and twice(int) becomes callable as soon as you declare half(int).
The life of an unresolved declaration
A declaration moves between two states, and your later input can move it back and forth.
The path back to Pending is easy to forget. Suppose twice is working and you run /drop half. JShell does not delete twice. It marks twice as unresolved again, and calls to it fail until you declare a suitable half. You can check the current state with /methods, which lists each method along with a note when it is unresolved.
Signatures must match
The dependency is on a specific signature, not just a name. Declaring half(double) does not satisfy a call to half(x) where x is an int, if the pending method was recorded as needing half(int). In practice the compiler is free to pick a widening-compatible overload, so such a call may resolve differently from what you expect. If a snippet stays pending after you declare "the missing method", compare the parameter types in the message with the ones you wrote.
Classes can also be pending
The same mechanism applies to classes, records and interfaces. A class can mention a type that does not exist yet:
jshell> class Report { Formatter f = new Formatter(); String render() { return f.format("ok"); } }
| created class Report, however, it cannot be referenced until class Formatter is declared
jshell> class Formatter { String format(String s) { return "[" + s + "]"; } }
| created class Formatter
| update modified class Report
jshell> new Report().render()
$3 ==> "[ok]"The line update modified class Report shows JShell re-resolving the dependent snippet when Formatter arrived. Formatter here is a name chosen to be unlikely to clash with java.util.Formatter. JShell's default imports include java.util.*, and a class you declare in the session takes precedence over an imported one with the same simple name. Even so, picking a distinct name avoids confusion.
Where forward references do not work
Pending status applies to declarations that define behavior: methods, classes, records and interfaces. It does not apply to everything you can type.
- Variable initializers. A variable's initializer runs immediately, so every name in it must already exist.
int total = missing() + 1;is rejected with a "cannot find symbol" error, and no variable is created. - Expressions and statements. These execute at once, so an unknown name is an error. There is nothing to defer.
- Real mistakes. JShell cannot tell a name you plan to declare later from a typo. A misspelled method name produces a pending snippet, not an error. If a snippet says it is waiting for
halv(int), the typo is yours.
The last point is the main hazard. A pending message looks like success, because it says "created". Read the whole line, not just the first word.
Mutual recursion
Forward references let you write methods that depend on each other. Neither can be complete first, so the first one is always pending until the second arrives:
jshell> boolean isEven(int n) { return n == 0 ? true : isOdd(n - 1); }
| created method isEven(int), however, it cannot be invoked until method isOdd(int) is declared
jshell> boolean isOdd(int n) { return n == 0 ? false : isEven(n - 1); }
| created method isOdd(int)
| update modified method isEven(int)
jshell> isEven(10)
$3 ==> trueThe update line shows that isEven was re-resolved when isOdd arrived.
Inspecting and cleaning up
Three commands help when a session contains pending snippets:
| Command | What it shows |
|---|---|
| `/methods` | Declared methods, with unresolved ones marked |
| `/types` | Declared classes, records and interfaces, with unresolved ones marked |
| `/list -all` | Every snippet entered, including ones that failed or were replaced |
If you want to remove a pending snippet, use /drop with its name or number from /list, as with any other snippet. Dropping a method that others depend on turns those dependents pending, as the diagram shows.
Summary of the rules
- A method, class, record or interface may refer to names that are not declared yet. JShell accepts it and reports it as pending.
- A pending snippet cannot run or be instantiated. Calling it prints a message, and the session continues.
- Declaring the missing name resolves the pending snippet automatically.
- Dropping or breaking a dependency makes its dependents pending again.
- Variable initializers, expressions and statements get no deferral. Unknown names in them are errors.
Exercise
You type int area(int w, int h) { return mul(w, h); } and JShell replies "created method area(int,int), however, it cannot be invoked until method mul(int,int) is declared". You then declare int mul(int a, int b) { return a * b; }, and area(3, 4) returns 12. Next you run /drop mul. What is the state of area(int,int), and what does area(3, 4) do?
Show answer
area(int,int) is still in the session but pending again, because its dependency mul(int,int) is gone. Calling area(3, 4) prints a message that the call cannot be made until mul(int,int) is declared. Declaring mul(int,int) again makes area callable.
Exercise
You type int total = compute() + 1; before declaring compute(). Why does JShell reject this, while an equivalent method body that calls compute() would be accepted as pending?
Show answer
A variable initializer runs immediately when you enter the snippet, so every name in it must already exist, and the unknown compute() is a "cannot find symbol" error. A method body does not run at declaration time, so JShell can store the method and wait for compute() to appear.