Sub topic 9
Forward references and unresolved declarations
Assume you already know basic Java methods and can start a JDK 9 or later JShell session. In a normal Java source file, a method can call another method that appears later in the class. The compiler checks the complete class before running it.
JShell checks each submitted snippet separately. It still allows some declarations that refer to code you have not entered yet. JShell marks those declarations as unresolved until their dependencies exist.
Declaring a method before its dependency
In this example, twice calls half, but half has not been declared:
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 input creates the twice method, but JShell reports that it cannot run yet. The method body is syntactically valid, and its return expression has the right type if half(int) eventually exists.
After the second declaration supplies half(int), JShell resolves the dependency. The earlier method becomes callable without being re-entered.
This behavior is useful when exploring a design from the outside in. You can write a public operation first, then add the smaller helper methods it needs.
What keeps a declaration unresolved?
A method stays unresolved when JShell cannot find a compatible declaration. The name, parameter types, and visible scope must match.
jshell> int tripleViaHelper(int x) { return helper(x) * 3; }
| created method tripleViaHelper(int), however, it cannot be invoked until method helper(int) is declared
jshell> String helper(String text) { return text.trim(); }
| created method helper(java.lang.String)
jshell> tripleViaHelper(4)
| Error:
| cannot find symbol
| symbol: method helper(int)helper(String) does not satisfy a call to helper(int). Java does not select a method only because its name matches. Its parameter types must also be compatible.
The unresolved method itself remains in the session. You can add the correct declaration and try again:
jshell> int helper(int value) { return value + 1; }
| created method helper(int)
jshell> tripleViaHelper(4)
$5 ==> 15If the dependency contains a typo, correct it by redefining the dependency or the method that uses it. Use /methods to inspect declared methods and /list to review the snippets that created them.
How resolution works
Forward references are convenient for short experiments, but they can hide mistakes in a long session. If a method remains unresolved, inspect its exact parameter types and spelling before adding more code.
Exercise
In JShell, declare int area(int side) { return square(side); }, then make it callable by declaring the required helper. What helper declaration should you enter?
Show answer
Enter int square(int value) { return value * value; }. Then area(5) returns 25.