Java REPL - JShell
Java added a new feature JShell in its Java 9 version. It is a command-line interactive REPL (Read-Evaluate-Print-Loop) console that allows executing Java code.
It can execute any expression, statement, or code instantly without saving code to any file or project. It reduces our effort of separately compiling and running the code.
In this tutorial, we will learn to use JShell by executing some code examples. We are using Windows cmd (Command Prompt) to start with JShell. If you are working on another platform like Linux or Mac then you can open a terminal to start the JShell.
How to Start JShell?
To start the JShell, you can simply type jshell
command to the cmd or terminal and press enter. It will start the JShell in the same terminal and then you can start writing and executing your code.
Example:
In this example, we are starting JShell and creating a variable that holds an integer value 10, and we are getting print of this value by using the print statement.
>jshell
| Welcome to JShell -- Version 9-ea
| For an introduction type: /help intro
jshell> int a = 10
a ==> 10
jshell> System.out.println("a value = " + a )
a value = 10
Examples: Creating Methods
We can create methods by adding complete definition. Here, we are creating a method sum(int, int) that takes two integer values and returns an integer.
jshell> int sum (int a, int b) {
...> return a+b;
...> }
| created method sum(int,int)
Example: Calling Method
After creating a method, now we need to use that method, so we can call it by simply its name. Notice, we did not create any object to call this method. JShell uses a simple approach for execution. If we don't provide any variable to hold the return value of the method then Java provides a default variable ($2) to hold it. See the example below.
jshell> int sum(int a, int b){
...> return a+b;
...> }
| created method sum(int,int)
jshell> sum(10,20);
$2 ==> 30 // result
Example: Storing Result Into A Variable
If we want to store the result into a variable then you can simply create a variable and store the result. See the example below.
jshell> int sum(int a, int b){
...> return a+b;
...> }
| created method sum(int,int)
jshell> sum(10,20);
$2 ==> 30
jshell> int result = sum(10,20); // Storing result into a variable
result ==> 30
Example: Find Methods - List
If we want to know about the number of methods we created. So, we can use /list command that shows the complete method.
jshell> /list sum
1 : int sum (int a, int b) {
return a+b;
}
Example: Conditional Statements (IF-ELSE)
Like variables, methods, etc. We can execute conditional statements also. Here, we are using IF-ELSE statements to check the result and print the message to the console.
jshell> int result = sum(20,50); // calling method
result ==> 70
jshell> if(result>100){
...> System.out.print("Sum is greater than 100");
...> }else{
...> System.out.println("Sum is less than 100");
...> }
Sum is less than 100 // result