Home > Articles > Programming > Java

Visit Java's Relatives: Jython and Groovy

Out of the many JRE-hosted languages in existence, this article focuses on the popular Jython and Groovy languages. Jython is a Java version of the Python language, whereas Groovy is based on Java. In addition to introducing Jython and Groovy, programmer Jeff Friesen shows you how to download and install necessary software, and takes you on a brief tour of each language.
Like this article? We recommend

The Java Runtime Environment (JRE) can host languages other than Java. This flexibility is perfect for non-Java developers who want to work within the contexts of their own languages, while reaping JRE benefits (such as a cross-platform virtual machine with security features). And this flexibility is perfect for Java developers who want to explore the potential of other languages, while staying with the familiar JRE. To illustrate the JRE's language flexibility, this article introduces the Jython and Groovy JRE languages.

Jython

Jython is a Java implementation of the Python language. Written entirely in Java, Jython is available to all Java platforms. This interpreted, interactive, and object-oriented language combines Java’s robustness with Python’s flexibility and ease of use, which encourages productivity and makes this language perfect for rapid application development.

Download and Install Jython

Before we tour Jython, let’s download and install the current production release: Jython 2.1. This version was released on December 31, 2001, and corresponds to Python 2.1. Begin by pointing your Web browser to the official Jython site and select the Download link on the main page. On the resulting Downloads page, select the jython-2.1 link to start the download.

After downloading the 2.65MB jython-21.class installer file, follow these steps:

  1. Open a command window and move to the directory containing this file.
  2. Type java jython-21 and press Enter to begin installation.
  3. If you are running Windows XP, you will probably notice an error message and a dialog box. Respond by selecting the Windows list item and clicking the OK button.
  4. The installer now presents an Install dialog box—see Figure 1—where you can select an installation language (English or German), an installation type (All: everything, Standard: everything but sources, and Minimum: only the core files), and individual checkboxes for choosing a combination of core files, library modules, demos and examples, and sources.
  5. Click Next to continue.
    Figure 1

    Figure 1 Verify the Jython version and determine how much of the Jython distribution gets installed.

  6. The dialog box now identifies the operating system and Java version. It also presents a checkbox that lets you decide whether to launch Jython with a console window (unchecked, the default—for Windows XP, java.exe is used to launch Jython) or without a console window (checked—for Windows XP, javaw.exe is used to launch Jython). Leave the checkbox unchecked and click the Next button.
  7. The dialog box next presents a license agreement. Read this agreement and click the Accept button.
  8. The dialog box next asks you to choose the location in which to install Jython. For my Windows XP platform, I chose c:\jython.
  9. After choosing Jython’s home directory, click the Next button.
  10. The dialog box tells you that it is ready to copy files. Press the green Go! button and the file-copying begins.
  11. After the files have been copied, a readme file is presented, which identifies some important changes in the 2.1 version. Once you finish reading this file, click the Exit button to close the installer.

Because I installed Jython on a Windows platform, my Jython home directory contains jython.bat. This batch file launches the Jython interpreter via a java command (or javaw command, if you chose to launch Jython without a console window). Before you can invoke this batch file (or UNIX equivalent) from any directory, add your Jython home directory to your path environment variable.

A Brief Jython Tour

The simplest way to launch the interpreter is to type jython by itself on the command line. This command launches Jython in interactive mode, with the following standard greeting message:

Jython 2.1 on java1.5.0 (JIT: null)
Type "copyright", "credits" or "license" for more information.
>>>

Jython supports the basic integer, floating-point, and string data types. Expressions can be built from these basic types and evaluated in a simple manner:

>>> 4*3*2*1 # Calculate 4 factorial.
24
>>> 3.14159*45/180 # Convert 45 degrees to radians equivalent.
0.7853975
>>> "Hello, "+"World" # Concatenate to strings.
’Hello, World’

Except for #, which introduces a comment (ignored by the interpreter), this Jython expression code looks much the same as Java expression code. Here are some differences:

>>> pi=3.14159 # Variable types are inferred from expressions.
>>> pi
3.14159
>>> i=j=k=1 # Multiple variables can be assigned the same value.
>>> i
1
>>> j
1
>>> k
1
>>> cn1=30+2j # Jython supports complex numbers.
>>> cn1.real # You can access the real part...
30.0
>>> cn1.imag # ...and the imaginary part.
2.0
>>> cn2=15-6j
>>> cn1+cn2 # You can also perform standard complex arithmetic.
(45-4j)
>>> str1="String 1" # Strings can be enclosed in double quotes...
>>> str1
’String 1’
>>> str2=’String 2’ # ...or in single quotes.
>>> str2
’String 2’
>>> str1[0] # Single characters can be extracted using an index.
’S’
>>> str1[0:2] # A substring can be returned via two indexes separated by a colon.
’St’
>>> str2[2:] # With no second index, substring continues to end of string.
’ring 2’
>>> str2[:3] # With no first index, substring begins at start of string.
’Str’

Jython’s equivalent to Java arrays is its flexible list type. A list is expressed as a comma-delimited sequence of values placed between square brackets:

>>> languages=[’Jython’,"JRuby",’Groovy’] # Create a list.
>>> languages
[’Jython’, ’JRuby’, ’Groovy’]
>>> languages[0]="Java" # Replace the first list item.
>>> languages
[’Java’, ’JRuby’, "Groovy’]
>>> languages=languages+[’Jython’] # Append a list item.
>>> languages
[’Java’, ’JRuby’, ’Groovy’, ’Jython’]
>>> languages[0:1]=[] # Remove a list item.
>>> languages
[’JRuby’, ’Groovy’, ’Jython’]
>>> len(languages) # The len() function returns a list’s length.
3
>>> languages[1]=[1,"Groovy",3] # Lists can contain different-typed values.
>>> languages # Furthermore, lists can contain lists.
[’JRuby’, [1, ’Groovy’, 3], ’Jython’]

Jython supports a variety of statements, including the while and for loop statements, the break and continue loop-control statements, and the if decision statement:

>>> fact=n=1
>>> while n < 11:
...   print n, fact
...   n=n+1
...   fact=fact*n
...
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880
10 3628800
>>> for age in [50,57,68]:
...   if age < 55:
...       print "Not eligible for early retirement"
...   elif age < 65:
...       print "Not eligible for traditional retirement"
...   else:
...       print "Retired"
...
Not eligible for early retirement
Not eligible for traditional retirement
Retired
>>> for i in range(0,10):
...   print "i =", i
...
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9

You’ll notice many similarities between these Jython statements and their Java counterparts. You’ll also notice many differences. These differences include:

  • Compound statements are not delimited with brace characters. Colon characters and indentation (spaces and tabs) delimit Jython’s compound statements.
  • When running the interpreter in interactive mode (which we are doing), you must leave one blank line after the final part of a compound statement to signify (to the interpreter) the end of this statement.
  • Jython does not have a Boolean type. As with C, Jython recognizes any nonzero integer as true and zero as false. For example, a while loop keeps iterating as long as its expression evaluates to a nonzero value.
  • The print statement outputs the values of expressions. Strings are output without surrounding quotes, and a space is placed between successive values for nicely formatted output.

The for statement is similar to Java 5.0’s enhanced for statement. Each iteration retrieves the next list item (the range() function returns a list of integers) and assigns it to the loop variable.

In addition to using Jython’s built-in functions (such as len() and range()), you can define (via Jython’s def keyword) and use your own functions:

>>> def fact(n):
...   i=factorial=1
...   while i <= n:
...       factorial=factorial*i
...       i=i+1
...   return factorial
...
>>> for i in range(0,11):
...   print "i =", i, ": fact =", fact(i)
...
i = 0 : fact = 1
i = 1 : fact = 1
i = 2 : fact = 2
i = 3 : fact = 6
i = 4 : fact = 24
i = 5 : fact = 120
i = 6 : fact = 720
i = 7 : fact = 5040
i = 8 : fact = 40320
i = 9 : fact = 362880
i = 10 : fact = 3628800

Functions can be defined inside classes. Functions defined with keyword self (Jython’s equivalent of Java’s this keyword) as the initial parameter are equivalent to Java’s instance methods:

>>> class Employee:
...   name=""
...   __age=0
...   def __init__(self,name,age):
...       self.name=name
...       self.__age=age
...   def getAge(self):
...       return self.__age
...
>>> john=Employee("John Doe",37) # Construct Employee object.
>>> john.name
’John Doe’
>>> john.__age
Traceback (innermost last):
 File "<console>", line 1, in ?
AttributeError: instance of ’Employee’ has no attribute ’age’
>>> john.getAge()
37

The Employee class defines two variables (name and __age) and two method functions (__init__ and getAge()). These definitions illustrate two points:

  • A class’s variables and method functions are known as attributes. Unless prefixed by at least two underscore characters, an attribute has public visibility.
  • The __init()__ method function serves as the class’s constructor. This method function is called when you construct an object—note the absence of a new keyword.

To close this tour, let’s look at importing Java classes into Jython. This task is accomplished with the from package import class directive:

>>> from java.util import StringTokenizer
>>> s = StringTokenizer("Jython can easily access Java classes")
>>> s.nextToken()
’Jython’
>>> s.nextToken()
’can’
>>> s.nextToken()
’easily’
>>> s.nextToken()
’access’
>>> s.nextToken()
’Java’
>>> s.nextToken()
’classes’
>>> s.nextToken() # Guess what happens?

I excerpted the earlier Jython code fragments from a jython.py script (part of this article’s code)—.py is the standard Jython file extension. You can run this script by passing it as an argument to jython.bat (or the UNIX equivalent). Example: jython jython.py.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020