JShell is an interactive tool that allows you to experiment with Java code in real time, without the need to write full classes or main methods. It was introduced in Java 9 and provides a quick, easy way to test small code snippets.
Prerequisites
JShell is available in Java 9 and later. To check which version of Java you have installed, open a terminal (Command Prompt on Windows) and run:
java -version
If you have Java 9 or later, JShell is automatically installed.
Starting JShell
To launch JShell, simply open your terminal or command prompt and type:
jshell
This starts the JShell interactive environment where you can enter Java expressions and see the results immediately.
Useful JShell Commands
JShell has a few commands that make it easier to interact with the environment:
| Command | Description |
|---|---|
/help | Displays the help menu. |
/exit | Exits the JShell session. |
/list | Lists the code snippets you’ve entered. |
/save | Saves the code to a file. |
/reload | Reloads the saved code from a file. |
For more detailed command options, you can type /help in the JShell terminal.
Basic Operations in JShell
JShell is great for quickly testing simple expressions or exploring Java classes. Here’s a quick rundown of things you can do in JShell:
1. Simple Math
You can perform basic arithmetic directly in JShell:
3 + 2 // returns 5
You can also try more complex expressions:
5 * (3 + 2) // returns 25
2. Working with Java Methods
You can test built-in Java methods directly. For example, let’s test the String.length() method:
"Hello".length() // returns 5
JShell will immediately output the result of the expression.
3. Creating Variables
You can declare and use variables just like in a regular Java programme:
int x = 10;
int y = 20;
x + y // returns 30
4. Using Java Classes
You can import and use Java classes, such as the Scanner class for input:
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name:");
String name = scanner.nextLine();
System.out.println("Hello, " + name);
Note: To use the Scanner class, you need to import it explicitly like shown above. JShell allows you to test even the most commonly used classes without the need to set up a full Java program.
Exiting JShell
To exit the JShell session, simply type:
/exit
This will close JShell and return you to your regular terminal.
Summary
- JShell is an interactive tool to experiment with Java code, available from Java 9 onwards.
- Launch JShell by typing
jshellin the terminal. - Useful commands:
/help(help),/exit(exit),/save(save code). - You can perform basic operations: simple math, test methods (e.g.,
String.length()), and use Java classes (e.g.,Scanner).
Further Resources
If you want to dive deeper into JShell, here are some helpful resources:
Leave a Reply