Social Media
View From Dalmeny To Crammond Island

JShell in Five Minutes

This post builds on my My Top Java 9 Features post by looking more in depth at these features. Here we show you how you can learn jshell in five minutes, and improve your Java 9 development experience.

Getting Started

Assuming you have downloaded, and installed Java 9 then you can start the shell by typing –

Or if you want verbose –

 

Variables

Simply type the variable, with or without semi-colons –

Unassigned values are automatically assigned to a variable beginning with $

This means we can reuse the value later –

Control Flows

The next step in jshell is to use control flows (for, if, while, …). We can do this by entering our condition, using return for each new line –

A quick tip is to use TAB for code completion

Methods

We can declare a method in a similar way as Flow control, and press for each new line –

Then call it –

We can also change methods in our shell, and have methods calling methods that arent defined yet –

Now we fix the method –

Classes

We can also define classes in jshell –

And assign and access them –

imports

The current classes in the workspace can be seen using the /imports command.

Additional classes can be added through the –class-path, or –module-path –

Or you can use /env within the shell –

Useful Commands

Now we’ve got the basics here are some quick commands –

Tab Code completion
/vars list of variables in the current shell
/methods list of methods in current shell
/list All code snippets in jshell session
/imports Current imports in the shell
/methods list of methods in current shell
/types Current classes defined in the shell, in the case above we would see “class HelloWorld”
/edit Lets you edit your session in an editor(default to JEditPad)
/exit close session

 

Conclusion

The real strength of the JShell REPL editor is you can test out snippets and API’s. This is really useful for saving time, and experimenting when learning Java9. In fact even if you are not moving to Java 9 straight away its worth installing JDK9 to use jshell as a testing ground.

About the Author Martin Farrell

My name is Martin Farrell. I have almost 20 years Java experience. I specialize inthe Spring Framework and JEE. I’ve consulted to a range of businesses, and have provide Java and Spring mentoring and training. You can learn more at About

follow me on:

Leave a Comment:

2 comments
My Top Java 9 Features - javabullets says 09/10/2017

[…] to Spring Data REST How Lambda’s And Anonymous Inner Classes(AIC) Work JShell in Five Minutes My Top Java 9 Features Add EntityManager.refresh to all Spring Data Repositories […]

Reply
Experimenting with Java9 HTTP Client and Process API in JShell - javabullets says 11/10/2017

[…] Work Experimenting with Java9 HTTP Client and Process API in JShell JShell in Five Minutes My Top Java 9 Features Add EntityManager.refresh to all Spring Data Repositories […]

Reply
Add Your Reply