In the previous tutorial we learned how to work with variables in JShell. In this guide, we will learn how to create methods in JShell, how to use them and how to modify the definition of already defined method.
JShell – Methods
Lets see how to define a method in JShell. In the following example, we have defined a method add()
and later called this method with arguments to get the sum of two integer numbers.
jshell> int add(int a, int b) { ...> return a+b; ...> } | created method add(int,int) jshell> add(10, 20) $2 ==> 30
JShell – how to change the definition of already defined method
We can also change the definition of an already defined method. In the following example, we are modifying the definition of method add()
jshell> int add(int a, int b) { ...> return a+b; ...> } | created method add(int,int) jshell> add(10, 20) $2 ==> 30 jshell> int add(int a, int b) { ...> return a+b+100; ...> } | modified method add(int,int) jshell> add(10, 20) $4 ==> 130
Note: Since we are changing the definition of method add(), JShell feedback shows it as modified method add(int, int) instead of created method add(int,int).
Leave a Reply