How do I import Java package in script?

Here you can see how to import a Java class so that you can use the class, creates an instance of
it in the scripting environment. We want to print out the current date on the console. For this we
need to import the Date class that’s packaged under the java.util package.

In the script we can import the java.util package using the following script

package org.kodejava.example.script;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class ImportPackageExample {
    public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByExtension("js");

        try {
        } catch (ScriptException e) {

    private static String getScript() {
        StringBuilder sb = new StringBuilder();
        sb.append("var today = new Date();");
        sb.append("println('Today is ' + today);");
        return sb.toString();

This program prints the following line:

Today is Fri Sep 11 2009 17:03:02 GMT+0800 (CST)

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🙂.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.