Sub topic 7
Declaring and redefining methods
This chapter assumes you can already declare variables in JShell and read its feedback lines, such as created and modified. It covers how to declare methods without a class, how JShell identifies a method, and how redefinition affects other code in the session.
Methods without a class
In compiled Java, every method lives inside a class. In JShell you can declare a method at the top level. JShell wraps it in a synthetic class for you, so you never see the wrapper.
jshell> int square(int x) { return x * x; }
| created method square(int)
jshell> square(12)
$2 ==> 144The feedback line names the method by its name and parameter types, not by its parameter names. That is how JShell identifies it.
Calling a void method prints nothing, because there is no value to show. The same happens for any expression that produces no value.
jshell> void hello(String who) { System.out.println("Hello, " + who); }
| created method hello(String)
jshell> hello("Ada")
Hello, AdaTop-level methods behave as if they were static. You can write modifiers such as public or static, but JShell ignores them and prints a warning. You do not need to type them.
What identifies a method
A method's identity is its name plus its parameter types. The return type and the parameter names are not part of it. This gives three cases.
| You enter | Same name and parameter types as an existing method? | Result |
|---|---|---|
| A new name | No | `created method` |
| Same name, different parameter types | No | A second method (an overload) is created |
| Same name and parameter types, new body or return type | Yes | `modified method`, which replaces the old one |
Overloads work as they do in compiled Java, and the compiler picks the best match at each call.
jshell> int add(int a, int b) { return a + b; }
| created method add(int,int)
jshell> double add(double a, double b) { return a + b; }
| created method add(double,double)
jshell> add(2, 3)
$3 ==> 5
jshell> add(2.5, 3)
$4 ==> 5.5Because the return type is not part of the identity, changing it replaces the method rather than creating an overload. In compiled Java, two methods that differ only in return type are a compile error.
jshell> long add(int a, int b) { return (long) a + b; }
| modified method add(int,int)Redefinition updates the methods that use it
When you redefine a method, other methods that call it pick up the new version. You do not need to re-enter them.
jshell> int square(int x) { return x * x; }
| created method square(int)
jshell> int sumOfSquares(int a, int b) { return square(a) + square(b); }
| created method sumOfSquares(int,int)
jshell> sumOfSquares(3, 4)
$3 ==> 25
jshell> int square(int x) { return x * x * x; }
| modified method square(int)
jshell> sumOfSquares(3, 4)
$5 ==> 91The second call now returns 27 + 64 = 91. JShell tracks which snippets depend on which, and it recompiles the dependents when a definition changes. The same applies when a method uses a session variable and you redeclare that variable.
Method lifecycle
A method is always in one of a few states. A method that refers to something that does not exist yet is accepted, but you cannot call it.
Forward references
You can declare a method before the methods it calls. JShell tells you what is missing.
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 ==> 20This lets you write a high-level method first and fill in the helpers afterward. If you call twice while half is missing, JShell reports that the method cannot be invoked and names the missing one. The session continues.
This differs from a compile error. A forward reference to a method that is not yet declared is allowed. A reference to something that is wrong, such as a type mismatch, is rejected.
jshell> int broken(int x) { return "a"; }
| Error:
| incompatible types: java.lang.String cannot be converted to int
| int broken(int x) { return "a"; }
| ^-^No method is created in that case. The exact error text depends on the JDK version.
Inspecting and removing methods
/methods lists the methods currently defined. /list shows all snippets with their numbers. /drop removes a method by name or snippet number.
jshell> /methods
| int square(int)
| int sumOfSquares(int,int)
jshell> /drop square
| dropped method square(int)
| update modified method sumOfSquares(int,int) which cannot be invoked until method square(int) is declaredDropping a method that others depend on does not delete the dependents. They move back to the unresolved state. Declare square again and sumOfSquares works again. When two overloads share a name, /drop with the bare name is ambiguous, so use the snippet number from /list.
Recursion and generics
A method can call itself, and JShell compiles generic methods like any others.
jshell> long factorial(int n) { return n <= 1 ? 1 : n * factorial(n - 1); }
| created method factorial(int)
jshell> factorial(10)
$2 ==> 3628800
jshell> <T> T firstOr(List<T> items, T fallback) { return items.isEmpty() ? fallback : items.get(0); }
| created method firstOr(List<T>,T)
jshell> firstOr(List.of(), "none")
$4 ==> "none"List works without an import because java.util.* is imported by default.
Exceptions inside methods
If a method throws, the session survives. The stack trace refers to snippets by number instead of by file and line.
jshell> int divide(int a, int b) { return a / b; }
| created method divide(int,int)
jshell> divide(1, 0)
| Exception java.lang.ArithmeticException: / by zero
| at divide (#1:1)
| at (#2:1)#1:1 means line 1 of snippet 1. Use /list to match a number to its source.
Common mistakes
- Expecting an overload when only the return type changed. JShell replaces the method.
- Expecting state to live in a method. Methods do not keep values between calls. Store state in session variables.
- Retyping parameter names to "fix" a method. Parameter names are not part of the identity, so the entry replaces the method with the same behavior.
- Typing
staticorpublicout of habit. They are ignored and produce a warning. - Misreading
created ... cannot be invoked. This is not a failure. It means a helper is still missing.
Exercise
In a fresh session you enter int f(int x) { return x + 1; }, then int g(int x) { return f(x) * 2; }, then g(3). You then enter int f(int x) { return x + 10; } and call g(3) again. What do the two calls to g(3) return, and what does JShell print for the redefinition of f?
Show answer
The first call returns 8, because (3 + 1) 2 = 8. The redefinition prints modified method f(int), since the name and parameter types match the existing method. The second call to g(3) returns 26, because g uses the new f: (3 + 10) 2 = 26.
Exercise
You enter int a(int x) { return b(x) + 1; } before declaring b. What does JShell report, and what must you do before a(1) can run?
Show answer
JShell creates a but reports that it cannot be invoked until method b(int) is declared. You must declare int b(int x) { ... }. After that, a(1) can be called. No restart is needed.
Exercise
You have String label(int n) and enter String label(long n) { return "L" + n; }. Does this replace the first method? What does /methods list afterward?
Show answer
No. int and long are different parameter types, so JShell creates an overload. /methods lists both String label(int) and String label(long).