Saturday

How to improve your Java programming skill with JShell


Introduction

If you are a javascript developer, I believe you will use the developer tool of the browser to interact with the page that you're inspecting or test a piece of code. This console is a REPL (Read-eval-print-loop) or language Shell. A REPL is a simple, interactive programming environment that takes user input (Read), executes the user command (Evaluate), returns the result to the user (Print), and waits for the next user input (Loop).

From java 9, we also have a REPL tool for java which called Java Shell Tool or in short JShell.

Open Jshell:

quoc ~  $ jshell
|  Welcome to JShell -- Version 15.0.2
|  For an introduction type: /help intro

jshell>


Code with JShell

Hello world

jshell> System.out.print("Hello world!")
Hello world!
jshell> var greeting = "Hello world";
greeting ==> "Hello world"

jshell> System.out.print(greeting)
Hello world
jshell>

The semicolon is optional in JShell

Default imports

As the previous example we define a string which part of java.lang. By default JShell imports the most used packages, we can list all the imported packaget by using /imports command:

jshell> /imports
|    import java.io.*
|    import java.math.*
|    import java.net.*
|    import java.nio.file.*
|    import java.util.*
|    import java.util.concurrent.*
|    import java.util.function.*
|    import java.util.prefs.*
|    import java.util.regex.*
|    import java.util.stream.*

So with these packages we can define some common types in Collection like List, Map,...

jshell> List list = List.of("Alex","Bob","Carol")
list ==> [Alex, Bob, Carol]

Code suggestion with Tab

JShell provides excellent support for code suggestion with the TAB key.

jshell> var greeting = "Hello " + //type <tab> in the keyboard
<press tab again to see all possible completions; total possible completions: 545>
jshell> var greeting = "Hello " + n //type <tab> 
name        netscape.
jshell> var greeting = "Hello " + netscape.
   ...>
   ...> :
|  Error:
|  <identifier> expected
|  var greeting = "Hello " + netscape.
|                                     ^

jshell> var greeting = "Hello " + n //type <tab> 
name        netscape.
jshell> var greeting = "Hello " + name
greeting ==> "Hello Alex"

Another example

jshell> name.to //type <tab>
toCharArray()   toLowerCase(    toString()      toUpperCase(
jshell> name.toLowerCase()
$9 ==> "alex"

Scratch Variables

The above example, you can see the result of name.toLowerCase() is assigned to a number $9, JShel create this variable and stores it automatically. This variable is called Scratch variable.

jshell> name.toLowerCase()
$9 ==> "alex"

jshell> System.out.print($8)
alex

Error Handling

If the user-provided command has some error, JShell detects the error and return a nicely formatted error message to the user.

jshell> name.substring(0,10)
|  Exception java.lang.StringIndexOutOfBoundsException: begin 0, end 10, length 4
|        at String.checkBoundsBeginEnd (String.java:3734)
|        at String.substring (String.java:1903)
|        at (#11:1)

Javadoc

JShell not only let us assist with code completion and possible method options, it allows the user to read the documentation of the language construct as well. Pressing the Tab key three times present the Javadoc of the method as shown below:

jshell> name.toUpperCase( //type <tab> 3 times to see java doc
String String.toUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the
given Locale .Case mapping is based on the Unicode Standard version specified by the
Character class. Since case mappings are not always 1:1 char mappings, the resulting
String may be a different length than the original String .
Examples of locale-sensitive and 1:M case mappings are in the following table.
-------------------------------------------------------------------------------------

Examples of
locale-sensitive
and 1:M case
mappings. Shows
Language code of
locale, lower
case, upper case,
and description.
| Language Code of   | Lower Case         | Upper Case         | Description        |
| Locale             |                    |                    |                    |
-------------------------------------------------------------------------------------
| tr (Turkish)       | \u0069             | \u0130             | small letter i     |
|                    |                    |                    | ->capital letter I |
|                    |                    |                    | with dot above     |
-------------------------------------------------------------------------------------
| tr (Turkish)       | \u0131             | \u0049             | small letter       |
|                    |                    |                    | dotless i          |
|                    |                    |                    | ->capital letter I |
-------------------------------------------------------------------------------------
| (all)              | \u00df             | \u0053\u0053       | small letter sharp |
|                    |                    |                    | s ->two letters:   |
|                    |                    |                    | SS                 |
-------------------------------------------------------------------------------------
| (all)              | Fahrvergnügen      | FAHRVERGNÜGEN      |                    |

<press tab again to see next page>

Declaring class and methods

In the previous example, we have mostly seen the single-line commands. However, JShell provides us with the ability to define methods and classes.

jshell> String hello(String name){
   ...>     return "Hello " + name;
   ...> }
|  created method hello(String)

jshell> hello("Alex")
$13 ==> "Hello Alex"
jshell> public class User{
   ...>    private String firstName;
   ...>    public User(String firstName){
   ...>      this.firstName = firstName;
   ...>    }
   ...>    public String getFirstName(){
   ...>      return firstName;
   ...>    }
   ...>    }
|  created class User

jshell> var alex = new User("Alex");
alex ==> User@5e91993f

jshell> alex.getFirstName()
$16 ==> "Alex"

Command in JShell

JShell commands control the environment and display information within a session. You can see the following example of how to execute the command in JShell. For more information you can read here https://docs.oracle.com/javase/10/jshell/commands.htm

Help

The most important command is /help. This provides the list of JShell commands with the purpose of the commands.

jshell> /help
|  Type a Java language expression, statement, or declaration.
|  Or type one of the following commands:
|  /list [<name or id>|-all|-start]
|  	list the source you have typed
|  /edit <name or id>
|  	edit a source entry
|  /drop <name or id>
|  	delete a source entry
|  /save [-all|-history|-start] <file>
|  	Save snippet source to a file
........

List

The /list command displays all the previously typed commands along with a sequence number. The list command also takes an argument named all to provide a detailed output of the commands.

jshell> /list

   1 : System.out.print("Hello world!")
   3 : System.out.print(greeting)
   4 : List list = List.of("Alex","Bob","Carol");
   6 : var greeting = "Hello " + name;
   7 : var name = "Alex";
   8 : name.toLowerCase()
   9 : name.toLowerCase()
  10 : System.out.print($8)
  11 : name.substring(0,10)
  12 : String hello(String name){
           return "Hello " + name;
       }
  13 : hello("Alex")
  14 : public class User{
          private String firstName;
          public User(String firstName){
            this.firstName = firstName;
          }
          public String getFirstName(){
            return firstName;
          }
          }
  15 : var alex = new User("Alex");
  16 : alex.getFirstName()

0 comments:

Post a Comment