What is a forward reference in JShell in Java 9?


JShell is a command-line tool that allows us to enter Java statements (simple statements, compound statements, or even full methods and classes), evaluates it and prints the result.

Forward references are commands that refer to methods, variables, or classes that don't exist in any code we have typed in JShell. As code entered and evaluated sequentially in JShell, these forward references have temporarily unresolved. JShell supports forward references in method bodies, return types, parameter types, variable types, and within class.

In the below code snippet, created a method forwardReference() in Jshell. This method can't be invoked until the variable is declared. If we are trying to attempt to call this method, it throws a warning message: "attempted to call method forwardReference() which cannot be invoked until variable notYetDeclared is declared"

C:\Users\User>jshell
| Welcome to JShell -- Version 9.0.4
| For an introduction type: /help intro

jshell> void forwardReference() {
...>       System.out.println(notYetDeclared);
...>    }
| created method forwardReference(), however, it cannot be invoked until variable notYetDeclared is declared

jshell> forwardReference()
| attempted to call method forwardReference() which cannot be invoked until variable notYetDeclared is declared


In the below code snippet, we have declared the "notYetDeclared" variable that returns a string. Finally, if we call forwardReference() in JShell, then it prints "variable is declared".

jshell> String notYetDeclared = "variable is declared"
notYetDeclared ==> "variable is declared"

jshell> forwardReference()
variable is declared

Updated on: 05-Mar-2020

219 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements