CIT 591 From Python to Java
Fall 2009, David Matuszek
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.
package statements (which specify the enclosing directory) and import statements go in front of the class declaration. Normally, every class is put on a separate file. But all variable and method declarations must be inside classes.camelCase.CamelCase.final variables) are written in ALL_CAPS_WITH_UNDERSCORES.{, go at the end of a line, not on a line by themselves. This differs from the C/C++ convention.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 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 }
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.
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 |
|---|---|---|
|
|
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 |
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
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:
int[] numbers = {1, 2, 3, 4};new int[] {1, 2, 3, 4}Java has no equivalent to Python's list[i:j] notation.
An ArrayList acts more like a Python list, but uses only object syntax. There are no literals.
ArrayList<String> languages = new ArrayList<String>();languages.add("Python"); // append to listString oldLanguage = languages.get(0);languages.set(0, "Java");Some additional methods: boolean isEmpty(), boolean contains(object), int size(), type remove(index).
A HashSet is like a Python set, but uses only object syntax. There are no literals. Declaration and creation look like:
HashSet<type> variable = 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.
A HashMap is like a Python dictionary, but uses only object syntax. There are no literals. Declaration and creation look like:
HashMap<keyType, valueType> variable = new HashSet<keyType, valueType>();
Some methods: type put(key, value) (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.
| Python | Java |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
No direct equivalent; use above for loop. |
| No equivalent. | |
| No equivalent. | |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 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:
public - Available from anywhere.protected - Available from anywhere within this folder/directory, and to all subclasses.private - Available only within this class. Instance variables should almost always be private.| Python | Java |
|---|---|
|
|