Java 9 – The Java Shell (RPEL) Part 3 | Code Factory


Index Page : Link

Donate : Link

Medium Blog : Link

Applications : Link

9. Using classes,interfaces and enum with JShell

In the JShell we can declare classes, interfaces, enums also.

We can use /types command to list out our created types like classes, interfaces and enums.

jshell> class Student{}
|  created class Student

jshell> interface Interf{}
|  created interface Interf

jshell> enum Colors{}
|  created enum Colors

jshell> /tyes
|  Invalid command: /tyes
|  Type /help for help.

jshell> /types
|    class Student
|    interface Interf
|    enum Colors

Recommened to use editor to type lengthy code.

public class Student
{
  private String name;
  private int rollNo;

  Student(String name, int rollNo)
  {
    this.name = name;
    this.rollNo = rollNo;
  }

  public String getName()
  {
    return name;
  }
  public int getRollNo()
  {
    return rollNo;
  }
}
jshell> /edit
|  replaced class Student
|    update overwrote class Student

jshell> /types
|    interface Interf
|    enum Colors
|    class Student

jshell> Student s = new Student("Abc", 12);
s ==> Student@7f560810
|  created variable s : Student

jshell> s.getName();
$6 ==> "Abc"
|  created scratch variable $6 : String

jshell> s.getRollNo();
$7 ==> 12
|  created scratch variable $7 : int

10. Loading and Saving Snippets in JShell

We can load and save snippets from the file.

Assume all our required snippets are available in snippets.jsh. This file can be with any extension like .txt, But recommended to use .jsh.

snippets.jsh

System.out.println("Code Factory");
public void m1()
{
  System.out.println("m1 method");
}
String s = "Code Factory"

We can load all snippets of this file from the JShell with /open command as follows.

Note: Bydefault, all files will be created in current working directory. If we want in some other location then we have to use absolute path (Full Path).

jshell> /list

jshell> /open snippets.jsh
Code Factory

jshell> /list

   1 : System.out.println("Code Factory");
   2 : public void m1()
       {
         System.out.println("m1 method");
       }
   3 : String s = "Code Factory";

Once we loaded snippets,we can use these loaded snippets based on our requirement.

jshell> m1()
m1 method

jshell> s
s ==> "Code Factory"
|  value of s : String

Saving JShell snippets to the file:

We can save JShell snippets to the file with /save command.

jshell> /help save
|
|                                   /save
|                                   =====
|
|  Save the specified snippets and/or commands to the specified file.
|
|  /save <file>
|       Save the source of current active snippets to the file.
|
|  /save -all <file>
|       Save the source of all snippets to the file.
|       Includes source of overwritten, failed, and startup code
|
|  /save -history <file>
|       Save the sequential history of all commands and snippets entered since the
|       jshell tool was launched.
|
|  /save -start <file>
|       Save the current startup definitions to the file
|
|  /save <id> <file>
|       Save the snippet with the specified snippet ID.
|       One or more IDs or ID ranges may used, see '/help id'

Note: If the specified file is not available then this save command itself will create that file.

jshell> /save history.jsh

Check Content of history.jsh

System.out.println("Code Factory");
public void m1()
{
  System.out.println("m1 method");
}
String s = "Code Factory";
m1()
s

How to Reload Previous state (session) of JShell:

We can reload previous session with /reload command so that all snippets of previous session will be available in the current session.

C:\Users\CodeFactory>jshell -v
|  Welcome to JShell -- Version 11.0.10
|  For an introduction type: /help intro

jshell> System.out.println("Code Factory");
Code Factory

jshell> 1+2+3+4
$2 ==> 10
|  created scratch variable $2 : int

jshell> /list

   1 : System.out.println("Code Factory");
   2 : 1+2+3+4

jshell> /exit
|  Goodbye

C:\Users\CodeFactory>jshell -v
|  Welcome to JShell -- Version 11.0.10
|  For an introduction type: /help intro

jshell> /reload -restore
|  Restarting and restoring from previous state.
-: System.out.println("Code Factory");
Code Factory
-: 1+2+3+4

jshell> /list

   1 : System.out.println("Code Factory");
   2 : 1+2+3+4

How to reset JShell State:

We can reset JShell state by using /reset command.

jshell> /help reset
|
|                                   /reset
|                                   ======
|
|  Reset the jshell tool code and execution state:
|       * All entered code is lost
|       * The execution state is restarted
|       * Startup code is re-executed
|  Save any work before using this command.
|  The /reset command accepts evaluation context options, see:
|
|       /help context

jshell> /list

   1 : System.out.println("Code Factory");
   2 : 1+2+3+4

jshell> /reset
|  Resetting state.

jshell> /list

11. Using Jar Files in the JShell

It is very easy to use external jar files in the jshell. We can add Jar files to the JShell in two ways.

  1. From the Command Prompt
  2. From the JShell Itself

Adding Jar File to the JShell from Command Prompt:

We have to open jshell with –class-path option.

C:\Users\CodeFactory>jshell -v --class-path C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6.jar

Demo Program to get all employees information from oracle database:

snippets.jsh:

import Java.sql.*;

public void getEmpInfo() throws Exception
{
  Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","code","factory");
  Statement st=con.createStatement();
  ResultSet rs=st.executeQuery("select * from employees");
  while(rs.next())
  {
    System.out.println(rs.getInt(1)+".."+rs.getString(2)+".."+rs.getDouble(3)+".."+rs.getString(4));
  }
  con.close();
}

Database info:

create Table employees(eno number,ename varchar2(10),esal number(10,2),eaddr varchar2(10));

insert into employees values(001,'Narendra',1000,'Mumbai');
insert into employees values(002,'Amit',2000,'Hyd');
insert into employees values(003,'Aditya',3000,'Hyd');
C:\Users\CodeFactory>jshell -v --class-path C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6.jar

jshell> /open mysnippets.jsh
jshell> getEmpInfo()
001..Narendra..1000.0..Mumbai
002..Amir..2000.0..Hyd
003..Aditya..3000.0..Hyd

Adding Jar File to the JShell from JShell itself:

We can add External Jars to the jshell from the Jshell itself with /env command.

jshell> /env --class-path C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6.jar
| Setting new options and restoring state.

jshell> /open mysnippets.jsh

jshell> getEmpInfo()
001..Narendra..1000.0..Mumbai
002..Amir..2000.0..Hyd
003..Aditya..3000.0..Hyd

Note: Internally JShell will use environment variable CLASSPATH if we are not setting CLASSPATH
explicitly.

12. How to customize JShell Startup

By default the following snippets will be executed at the time of JShell Startup.

jshell> /list -start

  s1 : import java.io.*;
  s2 : import java.math.*;
  s3 : import java.net.*;
  s4 : import java.nio.file.*;
  s5 : import java.util.*;
  s6 : import java.util.concurrent.*;
  s7 : import java.util.function.*;
  s8 : import java.util.prefs.*;
  s9 : import java.util.regex.*;
 s10 : import java.util.stream.*;

We can customize these start-up snippets based on our requirement.

Assume our required start-up snippets are available in myStartup.jsh.

myStartup.jsh

System.out.println("Code Factory's startup");

To provide these snippets as startup snippets we have to open JShell as follows

C:\Users\Rahul8>jshell -v --startup myStartup.jsh
Code Factory's startup
|  Welcome to JShell -- Version 11.0.10
|  For an introduction type: /help intro

jshell> /list -start

  s1 : System.out.println("Code Factory's startup");

Note: if we want DEFAULT import start-up snippets also then we have to open JShell as follows.

C:\Users\Rahul8>jshell -v --startup DEFAULT myStartup.jsh
Code Factory's startup
|  Welcome to JShell -- Version 11.0.10
|  For an introduction type: /help intro

jshell> /list

   1 : System.out.println("Code Factory's startup");

jshell> /list -start

  s1 : import java.io.*;
  s2 : import java.math.*;
  s3 : import java.net.*;
  s4 : import java.nio.file.*;
  s5 : import java.util.*;
  s6 : import java.util.concurrent.*;
  s7 : import java.util.function.*;
  s8 : import java.util.prefs.*;
  s9 : import java.util.regex.*;
 s10 : import java.util.stream.*;

Note: To import all JAVASE packages (almost around 173 packages) at the time of startup we have
to open JShell as follows.

C:\Users\Rahul8>jshell -v --startup JAVASE
|  Welcome to JShell -- Version 11.0.10
|  For an introduction type: /help intro

jshell> /list

jshell> /list -start

  s1 : import java.applet.*;
  s2 : import java.awt.*;
  s3 : import java.awt.color.*;
  s4 : import java.awt.datatransfer.*;
  s5 : import java.awt.desktop.*;
...
...
s171 : import org.w3c.dom.views.*;
s172 : import org.xml.sax.*;
s173 : import org.xml.sax.ext.*;
s174 : import org.xml.sax.helpers.*;

Note: In addition to JAVASE, to provide our own snippets we have to open JShell as follows

C:\Users\Rahul8>jshell -v --startup JAVASE myStartup.jsh
Code Factory's startup
|  Welcome to JShell -- Version 11.0.10
|  For an introduction type: /help intro

jshell> /list

   1 : System.out.println("Code Factory's startup");

jshell> /list -start

  s1 : import java.applet.*;
  s2 : import java.awt.*;
  s3 : import java.awt.color.*;
  s4 : import java.awt.datatransfer.*;
  s5 : import java.awt.desktop.*;
...
...
s171 : import org.w3c.dom.views.*;
s172 : import org.xml.sax.*;
s173 : import org.xml.sax.ext.*;
s174 : import org.xml.sax.helpers.*;

Need of PRINTING Option at the startup:

Usually we can use System.out.print() or System.out.println() methods to print some statements to the console. If we use PRINTING Option then several overloaded print() and println() methods will be provided at the time of startup and these internally call System.out.print() and System.out.println() methods methods.

Hence to print statements to the console just we can use print() or println() methods directly instead of using System.out.print() or System.out.println() methods.

C:\Users\Rahul8>jshell -v --startup PRINTING
|  Welcome to JShell -- Version 11.0.10
|  For an introduction type: /help intro

jshell> /list

jshell> /list -start

  s1 : void print(boolean b) { System.out.print(b); }
  s2 : void print(char c) { System.out.print(c); }
  s3 : void print(int i) { System.out.print(i); }
  s4 : void print(long l) { System.out.print(l); }
  s5 : void print(float f) { System.out.print(f); }
  s6 : void print(double d) { System.out.print(d); }
  s7 : void print(char s[]) { System.out.print(s); }
  s8 : void print(String s) { System.out.print(s); }
  s9 : void print(Object obj) { System.out.print(obj); }
 s10 : void println() { System.out.println(); }
 s11 : void println(boolean b) { System.out.println(b); }
 s12 : void println(char c) { System.out.println(c); }
 s13 : void println(int i) { System.out.println(i); }
 s14 : void println(long l) { System.out.println(l); }
 s15 : void println(float f) { System.out.println(f); }
 s16 : void println(double d) { System.out.println(d); }
 s17 : void println(char s[]) { System.out.println(s); }
 s18 : void println(String s) { System.out.println(s); }
 s19 : void println(Object obj) { System.out.println(obj); }
 s20 : void printf(java.util.Locale l, String format, Object... args) { System.out.printf(l, format, args); }
 s21 : void printf(String format, Object... args) { System.out.printf(format, args); }

Now onwards,to print some statements to the console directly we can use print() and println()
methodds.

jshell> print("Code Factory")
Code Factory
jshell> println("Hello " + 34)
Hello 34

jshell>

Note:

  1. Total 21 overloaded print(),println() and printf() methods provided because of PRINTING shortcut.
  2. Whenever we are using PRINTING shortcut,then DEFAULT imports won’t come. Hence,to get DEFAULT imports and PRINTING shortcut simultaneously,we have to open JShell as follows.
    jshell -v --startup DEFAULT PRINTING

Note:

Various allowed options with –startup are :

  1. DEFAULT
  2. JAVASE
  3. PRINTING

13. Shortcuts and Auto-Completion of Commands

Shortcut for Creating Variables:

Just type the value on the JShell and then “Shift+Tab followed by v” then complete variable declaration code will be generated we have to provide only name of the variable.

jshell> "Code Factory" // press "Shift+Tab followed by v"

jshell> String str = "Code Factory" // just need to provide variable name str
str ==> "Code Factory"
|  created variable str : String

jshell> 34

jshell> int i = 34 // just need to provide variable name i
i ==> 34
|  created variable i : int

Shortcut for auto-import:

just type class or interface name on the JShell and press “Shift+Tab followed by i”.

Then we will get options for import.

jshell> Connection
0: Do nothing
1: import: com.sun.jdi.connect.spi.Connection
2: import: java.sql.Connection
Choice: // press 2
Imported: java.sql.Connection

jshell> /imports
|    import java.sql.Connection

Auto Completion commands :

1. To get all static members of the class:

jshell>classsname.<Tab> 

jshell> Integer.
BYTES                    MAX_VALUE                MIN_VALUE                SIZE                     TYPE                     bitCount(
class                    compare(                 compareUnsigned(         decode(                  divideUnsigned(          getInteger(
hashCode(                highestOneBit(           lowestOneBit(            max(                     min(                     numberOfLeadingZeros(
numberOfTrailingZeros(   parseInt(                parseUnsignedInt(        remainderUnsigned(       reverse(                 reverseBytes(
rotateLeft(              rotateRight(             signum(                  sum(                     toBinaryString(          toHexString(
toOctalString(           toString(                toUnsignedLong(          toUnsignedString(        valueOf(

jshell> Integer.M
MAX_VALUE   MIN_VALUE

jshell> Integer.M

2. To get all instance members of class:

jshell>objectreference.<Tab>

jshell> String str = "Hello"
str ==> "Hello"
|  modified variable str : String
|    update overwrote variable str : String

jshell> str.
charAt(                chars()                codePointAt(           codePointBefore(       codePointCount(        codePoints()           compareTo(
compareToIgnoreCase(   concat(                contains(              contentEquals(         endsWith(              equals(                equalsIgnoreCase(
getBytes(              getChars(              getClass()             hashCode()             indexOf(               intern()               isBlank()
isEmpty()              lastIndexOf(           length()               lines()                matches(               notify()               notifyAll()
offsetByCodePoints(    regionMatches(         repeat(                replace(               replaceAll(            replaceFirst(          split(
startsWith(            strip()                stripLeading()         stripTrailing()        subSequence(           substring(             toCharArray()
toLowerCase(           toString()             toUpperCase(           trim()                 wait(

3. To get signature and documentation of a method:

jshell> classname.methodname(<Tab>
jshell> objectreference.methodname(<Tab>

jshell> str.ch
charAt(   chars()

jshell> str.substring(
i

Signatures:
String String.substring(int beginIndex)
String String.substring(int beginIndex, int endIndex)

<press tab again to see documentation>
jshell> str.substring(
String String.substring(int beginIndex)
Returns a string that is a substring of this string.The substring begins with the character at
the specified index and extends to the end of this string.
Examples:
     "unhappy".substring(2) returns "happy"
     "Harbison".substring(3) returns "bison"
     "emptiness".substring(9) returns "" (an empty string)


Parameters:
beginIndex - the beginning index, inclusive.

Returns:
the specified substring.

Note: Even this short cut applicable for our own classes and methods also.

jshell> void m1(){}
|  created method m1()

jshell> void m1(int i){}
|  created method m1(int)


jshell> m1(
i

Signatures:
void m1()
void m1(int i)

<press tab again to see documentation>
jshell> m1(
void m1()
<no documentation found>

Leave a comment