Java Shell Tool (JShell)It is an interactive Java Shell tool, it allows us to execute Java code from the shell and shows output immediately. JShell is a REPL (Read Evaluate Print Loop) tool and run from the command line. Advantages of JShellJshell has reduced all the efforts that are required to run a Java program and test a business logic. If we don't use Jshell, creating of Java program involves the following steps.
Jshell does not require above steps. We can evaluate statements, methods and classes, even can write hello program without creating class. How to Start JShellTo start Jshell, first we must have installed Java 9 then open terminal in Linux or command prompt in windows and type jshell ?v. It will start jshell session and displays a welcome message to the console. Hello Java MessageTo display a simple "Hello Java" message, write print command without creating class and hit enter. VariablesWe can declare variables and use anywhere throughout Jshell session. Let's create an integer variable. Semicolon (;) is optional, we can leave it and it works fine. See, variable b is created without using semicolon. Scratch VariablesIf we don't provide variable name, Java create implicit variable to store the value. These variables start with $ sign. We can use these variable by specifying implicit variable, as we did in the in the following screen-shot. ExpressionsWe can test any valid Java expression to get instant output. See, the following example. Adding two integers Compound expression MethodsTo test method business logic, create an method and get result immediately. See, the following example. Calling method To create class, write source code for the class and call its method by creating object immediately. See the following example. ClassPackage ImportsBy default, 10 packages are imported and can also be imported any package by using import statement. To see, default import packages, we can use following command. Importing java.sql package. Listing import packages and it will show available accessible packages. Now number of packages are 11 including new one java.sql.*. Jshell CommandsJshell provides various useful commands that we can use to modify environment, manage code and to get code related information. Following are the useful information. Package Imports Command /vars to show variables. To get all written source code, use /list Next TopicModule System |