JShell – Java 9 tool to run Java code snippets

JShell is a very useful tool for prototyping and testing Java code snippets. Even though it is not yet officially released I highly recommend checking it out.

This tool comes bundled with JDK 9. You can download JDK 9 at https://jdk9.java.net/Once downloaded, you can run jshell command by going to the bin directory of JDK. Let’s go through various commands and code snippets we can run using JShell

Default imports

By default, you get a set of common imports

 

 

 

 

 

 

 

 

Expressions

You can execute any expression and that will get assigned to randomly generated variable. In this case, it has been assigned to variable $15. These variables get generated in a sequence, hence next variable name would be $16

 

Methods

You can define methods and also invoke them

List

‘/list’ command will return all code snippets executed till now

History

‘/history’ command will return all code snippets as well as commands written till now

Variables

‘/vars‘ will return you all the variables defined till now. Similarly, we run ‘/methods’ command to see the list of methods declared so far

Edit

Edit command will open JShell edit pad. You can modify all the code snippets and save it

 

Help

‘\help’ command will list down all supported commands

Save

‘\save’ command will save all the code snippets written so far to a file

Exit

‘\exit’ command will exit JShell console

 

There are many more things you can do with JShell. This tool is perhaps not meant for experts but surely a helpful tool for newbies and those who want to try out simple code snippets without taking pain of using any IDE, writing full pledged programs and compiling/running the code

 

For example, I was confused about splitting a string like “uday$$$ogra”. If I use string.split(“$$$”), it does not split. After trying few combinations using JShell I found exact code should be string.split(“\\$\\$\\$”)

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *