CIT 590/591: From Python to Java
Fall 2012, David Matuszek

Jump to:

Introduction

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.

Style

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 MyClass.java (note capitalization!)
    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 HashMap<keytype, valuetype> - like Python dictionaries

Example declarations

double distance;
String firstName;
int count = 0;                      // initial value
char[][] letters = new char[5][5];  // declares an array of arrays AND creates it
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).

Operators

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.

Statements

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

Python

Java

a = b + c
a = b + c;
print 'x =', x
System.out.println("x = " + x);
print x,
System.out.print(x);
name = raw_input('Enter your name: ')
Scanner scanner = new Scanner(System.in); // done once
System.out.print("Enter your name: ");
name = scanner.nextLine();
age = input('Enter your age: ')
Scanner scanner = new Scanner(System.in); // 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'
else:
    print 'positive'
if (x < 0) {
    System.out.println("negative");
} else if (x == 0) {
    System.out.println("zero");
} else {
    System.out.println("positive");
}
for i in range(0, len(list)):
    print list[i]
for (int i = 0; i < array.length; i++) {
    System.out.println(array[i]);
}
for value in list:
    print(value)
for (int value : array) {
    System.out.println(value);
}
No equivalent.
do {
    word = scanner.next();
while (! word.equals("end"));    
No equivalent.
switch(answer) {
    case 1:
        System.out.println("yes");
        break;
    case 2:
        System.out.println("no");
        break;
    default:
        System.out.println("unknown");
}
raise ValueError, 'Bad value'
throw new ArithmeticException("Bad value");
try:
    doSomething()
except ValueError, msg:
    print msg
except:
    print 'Something went wrong'
finally:
    alwaysDoThis()
try {
    doSomething();
}
catch (ArithmeticException e) {
    System.out.println(e.getMessage());
}
catch (Exception e) {
    e.printStackTrace();
}
finally {
    alwaysDoThis();
}
assert x > 0
assert x > 0;
break
break;
continue
continue;
pass
{ }
return
return;
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) {
    ...
}

Example:

/**
 * Finds the row in the code block containing the given
 * character.
 * 
 * @param block The array to be searched.
 * @param ch The character to search for.
 * @return The row index of the character (or -1 if not found).
 */
int findRow(char[][] block, char ch) {
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            if (block[i][j] == ch) {
                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);

Scope

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 next 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.

Access

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'))
	   
unittest.main()
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

public class PlayfairCipherTest {
    PlayfairCipher cipher;

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