java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 importPackage(java.util).

package com.javacoderanch.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)