CIT 591 From Python to Java
Fall 2009, David Matuszek

Jump to: Introduction, Style, Program structure, Strings and comments, Variable declarations, Operators, Statements, Methods and constructors, Scope, Access, Unit testing.


Python and Java are both object-oriented (O-O) languages, so most of the concepts are very similar. Here are some important differences you must keep in mind.


Program structure

Until you understand all the details, here is a good program structure to start with.

package myPackage;      // optional package declaration

import java.util.*;     // imports go here; util is needed for ArrayList, HashSet, HashMap

public class MyClass {  // must save in a file named
    int myInstanceVar;  // declare instance variables here

    public static void main(String[] args) {
        new MyClass().myStartingMethod();

    void myStartingMethod() {
        // declare local variables here
        // statements go here; can call other methods

    //other methods go here

Strings and comments

Java string literals are enclosed in double quotes ("), never in single quotes. Character literals are enclosed in single quotes ('), never in double quotes. A one-character string is not the same as the single character. Escape sequences (\n, \t, etc.) are single characters. There are no triple-quoted strings or raw strings in Java.

Strings can be concatenated with the + operator. Any object, of any type, may be concatenated to a String; it will be automatically converted to a String (for objects, via their toString() method) before being concatenated.

In Python, # starts a single-line comment; in Java, // starts a single-line comment. Java also has multi-line comments, beginning with /* and ending with */.

In Python a docstring (documentation string) is a string, usually triple-quoted, just after a function or method header. In Java, a Javadoc comment begins with /** and ends with */, and is put just before a method header, class header, or variable declaration.

Variable declarations

You must declare the type of every variable that you use. Each variable must be declared once and only once (but the same variable name may be declared in different scopes.) There are eight primitive types; everything else is an object type (defined by a class).

Important primitive types Other primitive types Important object types

int - for integers

byte - for very small integers

String - for strings
double - for floating point numbers short - for small integers Arrays - have a fixed size
boolean - values are true and false (all lowercase) long - for integers longer than nine digits ArrayList<type> - like Python lists
char - for single characters float - for less accurate floating-point numbers  

Example declarations

double distance;
String firstName;
int count = 0;                      // initial value
char[][] letters = new char[5][5];  // declares an array AND creates one
ArrayList<String> students;         // declares but does NOT create an ArrayList
final int CLASS_LIMIT = 38;         // constant

Python list → Java array

An array is indexed like a Python list, with square brackets: students[0] or letters[i][j].

Declaring an array does not create one. The declaration tells how many dimensions the array has, but never its size: for example, char[][] letters. To create one, use the word new, then its type and size; new char[5][5].

Python has list literals: [1, 2, 3, 4]. Java has two different syntaxes for array literals:

Java has no equivalent to Python's list[i:j] notation.

Python list → Java ArrayList

An ArrayList acts more like a Python list, but uses only object syntax. There are no literals.

Some additional methods: boolean isEmpty(), boolean contains(object), int size(), type remove(index).

Python tuples → No Java equivalent

Python set → Java HashSet

A HashSet is like a Python set, but uses only object syntax. There are no literals. Declaration and creation look like:
      HashSet<typevariable = new HashSet<type>();

Some methods: boolean add(object), boolean remove(object), boolean isEmpty(), boolean contains(object), boolean addAll(collection) (union), boolean retainAll(collection) (intersection), boolean removeAll(collection) (set difference), boolean containsAll(collection) (subset).

A HashSet is one kind of collection. Operations that may change the set return true if the set was changed, false otherwise.

Python dictionary → Java HashMap

A HashMap is like a Python dictionary, but uses only object syntax. There are no literals. Declaration and creation look like:
      HashMap<keyTypevalueTypevariable = new HashSet<keyTypevalueType>();

Some methods: type put(keyvalue) (returns previous value), type get(key), boolean containsKey(key).


The following operators are basically the same in Python and Java:

    .  +  -  *  /  <  <=  ==  !=  >=  >  +=  -=  *=  /=  &  |  ^  ~  <<  >>

When applied to objects, the Java == and != operators act like Python's is and is not operators, which is usually not what is wanted (especially for Strings). Equality testing should be done with the obj1.equals(obj2) method.

The % (mod) operator behaves the same for positive integers, but differently for negative integers.

Python's isinstance(object, Class) function is the equivalent of Java's object instanceof Class operator.

The Java equivalents of Python's and, or, and not are &&, ||, and !, respectively. There are no equivalents for in and not in.

Java has ++, to increment by one, and --, to decrement by one. These can be either prefix or postfix, and should be used only as statements, not as part of an expression. Java also has the expression condition ? valueIfTrue : valueIfFalse to choose between two values.


Rather than trying to give precise syntactical definitions of the various statements, I'll just provide examples.



a = b + c
a = b + c;
print 'x =', x
System.out.println("x = " + x);
print x,
name = raw_input('Enter your name: ')
Scanner scanner = new Scanner(System.input); // done once
System.out.print("Enter your name: ");
name = scanner.nextLine();
age = input('Enter your age: ')
Scanner scanner = new Scanner(System.input); // done once
System.out.print("Enter your age: ");
name = scanner.nextInt();
while x < 1000:
    x = 2 * x
while (x < 1000) {
    x = 2 * x;
if x < 0:
    print 'negative'
elif x == 0:
    print 'zero'
    print 'positive'
if (x < 0) {
} else if (x == 0) {
} else {
for i in range(0, len(list)):
    print list[i]
for (int i = 0; i < array.length; i++) {
for value in list:
    print value
No direct equivalent; use above for loop.
No equivalent.
do {
    word =;
while (! word.equals("end"));    
No equivalent.
switch(answer) {
    case 1:
    case 2:
raise ValueError, 'Bad value'
throw new ArithmeticExpression("Bad value");
except ValueError, msg:
    print msg
    print 'Something went wrong'
try {
catch (ArithmeticException e) {
catch (Exception e) {
finally {
assert x > 0
assert x > 0;
{ }
return a + b
return a + b;     

Methods and constructors

Java has no "functions," only methods. A method may have an optional access modifier, and must have a return type. If the method doesn't return anything, the return type is void. The type of each parameter must be specified. The syntax of a method declaration is:

access returnType methodName(type parameter, ..., type parameter) {


 * Finds the row in the code block containing the given
 * character.
 * @param ch The character to be found.
 * @return The row index of the character (or -1 if not found).
int findRow(char ch) {
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            if (block[i][j] == ch) {   // block is an instance variable
                return i;
    return -1;

Aside from fancy features, the syntax of a method call is the same in Java as it is in Python. As in Python, objects are passed by reference (and so can be altered).

The Java keyword this corresponds to the Python word self; it is used to indicate an instance variable or instance method. Unlike Python, it is only needed when you need to distinguish an instance variable from a local variable (or parameter) with the same name.

In Python, a constructor is a method with the name __init__, and it must have self as a first parameter. In Java, a constructor is like a method, but the returnType and methodName are replaced with the name of the class:

access ClassName(type parameter, ..., type parameter) {

Example constructor (assuming that we are within a Car class):

public Car(String make, int year) {
    this.make = make;
    this.year = year;

A constructor may contain a return; statement, but it may not explicitly return a value; the newly constructed object is alway implicitly returned. Constructors are called with the keyword new:

Car myCar = new Car("Prius", 2005);


Anything declared within a class (but not inside a method) is available everywhere throughout the class. Variables and methods do not have to be in any particular order. Usually, variables are put first, and usually the main method is just after the variables or at the bottom.

Parameters to a method are available throughout the method.

Within a method, local variables are usually declared at the top, making them available throughout the method. However, the rule is: Anything declared within braces, { }, is available from the point of declaration to the matching close brace.

As a special case, a variable may be declared within a for loop (for (int i = 0; ...), and is available throughout the loop.


Variable declarations and method declarations may be preceded by one of the following access modifiers:

Unit testing

Python Java
import playfair
import unittest

class TestPlayfair(unittest.TestCase):

   def setUp(self):
       self.cipher = Playfair("University")
   def testGetRow(self):
       self.assertEqual(0, cipher.getRow('a'))
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

public class PlayfairCipherTest {
    PlayfairCipher cipher;

    public void setUp() {
        cipher = new PlayfairCipher("University");
    public void testGetRow() {
        assertEquals(0, cipher.getRow('a'));