Author avatar

Esteban Herrera

Getting Started with JShell Part 2

Esteban Herrera

  • Dec 14, 2018
  • 9 Min read
  • 11,686 Views
  • Dec 14, 2018
  • 9 Min read
  • 11,686 Views
Java and J2EE
JShell

Preface

In the first guide of this series, you learned what JShell is and how to install it.

In this guide, you'll learn how to start working with Jshell.

Expressions and Variables

So, let's start with a simple expression:

1jshell> "Hello World"
2$1 ==> "Hello World"
java

Notice that the result of the evaluation is shown and it's assigned to the variable named $1. You can check this by entering the name of the variable:

1jshell> $1
2$1 ==> "Hello World"
java

A variable like this will be created implicitly when the result of an expression is not assigned to some variable. If the expression doesn't have a return value (like a print statement), no variable will be created.

You can use this implicit variable like any other:

1jshell> System.out.println($1)
2Hello World
java

You can also change the value it holds:

1jshell> $1 = $1 + " again"
2$1 ==> "Hello World again"
3
4jshell> System.out.println($1)
5Hello World again
java

However, it's probably better to work with some meaningful identifiers:

1jshell> String hello = $1
2hello ==> "Hello World again"
3
4jshell> System.out.println(hello)
5Hello World again
java

As you can see in the previous examples, it's not required to use a semicolon for single statements. Of course, this will not work if you try to execute more than one statement at the same time:

1jshell> int sum = 1 + 2 System.out.println(sum)
2|  Error:
3|  ';' expected
4|  int sum = 1 + 2 System.out.println(sum);
5|                 ^
java

You'll need a semicolon between statements (but not after the last one, if you don't want):

1jshell> int sum = 1 + 2; System.out.println(sum)
2sum ==> 3
33
java

Also, JShell won't execute a statement until it knows the statement is completed. For example, if you only type if(sum > 0), the prompt will change to ...>:

1jshell> if(sum >0)
2   ...> 
java

We'll be prompted to continue entering snippets until a valid statement or block is completed:

1jshell> if(sum > 0)
2   ...> System.out.print(sum)
33
java

Methods

The capability of typing multi-line statements allows us to write complete methods and classes. For example, you can define a method to return the negative value of the argument:

1jshell> int getNegativeValue(int number) {
2   ...> return -number;
3   ...> }
4|  created method getNegativeValue(int)
java

This way, you can call it like this:

1jshell> getNegativeValue(10)
2$5 ==> -10
java

Referencing

Sometimes, a method references variables or other methods that are defined later in a class. These are called forward references. Since in JShell the code is entered and evaluated sequentially, code that uses forward references cannot be invoked until these references are evaluated. Take the following method declaration for example:

1jshell> int addMagicNumber(int number) {
2   ...> return number + MAGIC_NUMBER;
3   ...> }
4|  created method addMagicNumber(int), however, it cannot be invoked until variable MAGIC_NUMBER is declared
java

You won't be able to use it until MAGIC_NUMBER is defined:

1jshell> System.out.println(addMagicNumber(3))
2|  attempted to call method addMagicNumber(int) which cannot be invoked until variable MAGIC_NUMBER is declared
3
4jshell> int MAGIC_NUMBER = 1
5MAGIC_NUMBER ==> 1
6
7jshell> System.out.println(addMagicNumber(3))
84
java

JShell supports forward references in:

  • Methods
  • The type of
    • Return statements
    • Parameters
    • Variables

However, it doesn't support forward references in variable initializers (possibly because they need to be executed at the moment the variable is defined):

1jshell> int MAGIC_NUMBER = getMagicNumber()
2|  Error:
3|  cannot find symbol
4|    symbol:   method getMagicNumber()
5|  int MAGIC_NUMBER = getMagicNumber();
6|                     ^------------^
java

Classes

You can also declare classes, for example:

1jshell> class Book {
2   ...> private String title;
3   ...> public void setTitle(String title) { this.title = title; }
4   ...> public String getTitle() { return title; }
5   ...> }
6|  created class Book
java

And use them like this:

1jshell> Book book = new Book()
2book ==> Book@3dd4520b
3
4jshell> book.setTitle("Java 9");
5
6jshell> System.out.println(book.getTitle())
7Java 9
java

Modifiers of methods and fields defined inside a class are applied just like in Java:

1jshell> book.title
2|  Error:
3|  title has private access in Book
4|  book.title
5|  ^--------^
java

External Declarations

Declarations outside a class or interface (and declarations of classes and interfaces by themselves) are created under the following rules:

  1. Access modifiers (public, protected, and private) are ignored. All declaration snippets are accessible to all other snippets:

    1jshell> private int x = 1;
    2x ==> 1
    3
    4jshell> System.out.print(x) // private ignored
    51
    java
  2. The modifier final is ignored. Changes and inheritance are allowed:
    1jshell> final class A {void m() {} }
    2|  Warning:
    3|  Modifier 'final'  not permitted in top-level declarations, ignored
    4|  final class A { void m() {} }
    5|  ^---^
    6|  created class A
    java
  3. The modifier static is ignored because there isn't a container class (at least none you can use):
    1jshell> static char letter = 'A'
    2|  Warning:
    3|  Modifier 'static'  not permitted in top-level declarations, ignored
    4|  static char letter = 'A';
    5|  ^----^
    6letter ==> 'A'
    java
  4. The modifiers default and synchronized are not allowed:
    1jshell> synchronized void method() {}
    2|  Error:
    3|  Modifier 'synchronized'  not permitted in top-level declarations
    4|  synchronized void method() {}
    5|  ^----------^
    java
  5. The modifier abstract is allowed only on classes:
    1jshell> abstract void method();
    2|  Error:
    3|  Modifier 'abstract'  not permitted in top-level declarations
    4|  abstract void method();
    5|  ^------^
    java

Exceptions

JShell automatically catches exceptions, display information about them, and allows you to continue the session as if nothing has happened. This works for unchecked exceptions:

1jshell> 1/0
2|  java.lang.ArithmeticException thrown: / by zero
3|        at (#24:1)
4
5jshell>
java

And checked exceptions, without wrapping them in a try/catch statement:

1jshell> FileInputStream fis = new FileInputStream("nonexistentfile.txt")
2|  java.io.FileNotFoundException thrown: nonexistentfile.txt (The system cannot find the file specified)
3|        at FileInputStream.open0 (Native Method)
4|        at FileInputStream.open (FileInputStream.java:196)
5|        at FileInputStream.<init> (FileInputStream.java:139)
6|        at FileInputStream.<init> (FileInputStream.java:94)
7|        at (#25:1)
java

Finally, to end a session just type /exit:

1jshell> /exit
2|  Goodbye
3
4$
java

Saving Files

One problem we have is that all these statements are lost when we exit JShell. Luckily, there's a /save command that can save all commands and snippets to a file. It has the following options:

  • /save <file>: Save the commands and snippets currently active to the provided file path.
  • /save -all <file>: Save all commands and snippets, including overwritten, start-up, and failed commands and snippets to the provided file path.
  • /save -history <file>: Save all commands and snippets run to the provided file.
  • /save -start <file>: Save all commands and snippets that initialized the JShell session to the provided path.

This way, if we execute:

1/save my-session.txt
java

A text file named my-session.txt will be saved in the current directory with the statements you issued in the last session. For example:

1"Hello World"
2System.out.println($1)
3"Hello World modified";
4class Book {
5private String title = "<NO TITLE>";
6public void setTitle(String title) { this.title = title; }
7public String getTitle() { return title; }
8public String toString() { return "Book: " + title; }
9}
java

This way, if we open a new JShell session and execute the command:

1/open my-session.txt
java

All the statements defined in the text file will be executed:

1jshell> /open my-session.txt
2Hello World
java

By the way, /open also works with existing Java source files, for example:

1jshell> /open Book.java
java

Next Steps

In the next guide in this series, you'll learn how to manage code snippets and use JShell to explore libraries.