Visit Java's Relatives: Jython and Groovy
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:
- Open a command window and move to the directory containing this file.
- Type java jython-21 and press Enter to begin installation.
- 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.
- 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.
- Click Next to continue.
Figure 1 Verify the Jython version and determine how much of the Jython distribution gets installed.
- 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.
- The dialog box next presents a license agreement. Read this agreement and click the Accept button.
- The dialog box next asks you to choose the location in which to install Jython. For my Windows XP platform, I chose c:\jython.
- After choosing Jython’s home directory, click the Next button.
- The dialog box tells you that it is ready to copy files. Press the green Go! button and the file-copying begins.
- 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.