In this tutorial, we will learn how to work with import statements using JShell. We will also see how to import third-party library imports using JShell.
The Java Shell tool (JShell) is an interactive tool for learning the Java programming language and prototyping Java code. JShell is a Read-Evaluate-Print Loop (REPL), which evaluates declarations, statements, and expressions as they are entered and immediately shows the results.
Complete the Java JShell tutorial at https://www.javaguides.net/2022/06/java-shell-jshell-tutorial.html
Using Java Default Imports
By default, jshell imports some common packages on startup. You can type /imports command to see all the available imports: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.*
For example, we can use java.lang.String class methods using JShell:
jshell> "java" + "guides"
$13 ==> "javaguides"
jshell> "java".equals("java")
$14 ==> true
jshell> "java guides".substring(0, 4)
$15 ==> "java"
Java Import Different Package
In addition to the Java API packages, you can import other packages to use their types in JShell.jshell> import java.time.*
jshell> System.out.println(LocalDate.now())
2022-06-08
Use again /imports commands to see all the imports:
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.*
| import java.time.*
Import Third-Party Packages
In order to import the third-party packages, you need first to use JShell’s /env-class-path command to add the packages to JShell’s CLASSPATH, which specifies where the additional packages are located. You can then use import declarations to experiment with the package contents in JShell.Let’s add the Person class to JShell’s CLASSPATH. Also, I have downloaded a Gson library JAR file to add to CLASSPATH too so you can use the Gson class to generate a JSON-formatted text from the person class instance.
public class Person {
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
}
Use the following command to add packages and libraries to the current JShell session’s CLASSPATH:jshell> /env -class-path ./lib/gson-2.8.5.ja
| Setting new options and restoring state.
Comments
Post a Comment
Leave Comment