CSC300: Python to Java

Contents [0/12]

Video [1/12]
Main [2/12]
Import [3/12]
Fully qualified class names [4/12]
Variable declarations [5/12]
Types [6/12]
Syntax [7/12]
Function declarations [8/12]
Lists/Arrays [9/12]
More about Arrays [10/12]
Formatting Output [11/12]
Extras: Scope [12/12]

(Click here for one slide per page)


Video [1/12]

Open Playlist

Main [2/12]

PythonJava
01
02
03
04
05
def main():
    print("Hello")

if __name__ == "__main__":
    main()
01
02
03
04
05
06
package algs11;
public class Hello {
  public static void main (String[] args) {
    System.out.println ("Hello");
  }
}

Every java program requires a main function. It must be declared exactly as on the third line above.

Every java function resides in a class, in this case Hello.

Every java class resides in a package, in this case algs11.

Java includes visibility annotations, such as public and private. In python, everything is public.

Java functions are written using the keyword static. (More later.)

Java functions must include types for arguments and results, in this case String[] and void.

Both java and python code is compiled before it is run.

Import [3/12]

PythonJava
01
02
03
04
05
def main():
    print("Hello")

if __name__ == "__main__":
    main()
01
02
03
04
05
06
07
package algs11;
import stdlib.*;
public class Hello {
  public static void main (String[] args) {
    StdOut.println ("Hello");
  }
}

System.out and System.in refer to objects.

I don't want to talk about objects yet, so we will use the version about, which replaces System.out with StdOut.

StdOut is a class in the stdlib package.

System is a class in the java.lang package.

All of the classes in java.lang are imported implicitly into every java program. All other classes must be imported explicitly.

The statement import stdlib.* makes the classes declared in stdlib visible in our program.

Instead of importing every class from a package, you can also import a single class.

Unnecessary imports will generate a warning.

If your code has a compiler error, it will not run.

If your code has a warning, you can run it. But you should fix the warning.

Fully qualified class names [4/12]

PythonJava
01
02
03
04
05
def main():
    print("Hello")

if __name__ == "__main__":
    main()
01
02
03
04
05
06
package algs11;
public class Hello {
  public static void main (java.lang.String[] args) {
    stdlib.StdOut.println ("Hello");
  }
}

As an alternative to using import, you can also use a class's fully qualified name, which includes the package explicitly.

Fully qualified names make code rather verbose, so usually people prefer to use import.

Variable declarations [5/12]

PythonJava
01
02
03
04
05
06
def main():
    name = "Bob"
    print("Hello " + name)

if __name__ == "__main__":
    main()
01
02
03
04
05
06
07
08
09
package algs11;
import stdlib.*;
public class Hello {
  public static void main (String[] args) {
    String name;
    name = "Bob";
    StdOut.println ("Hello " + name);
  }
}

In python, values are typed, but variables are not.

In java, both values and variables are typed. Variable types must be explicitly declared.

The declaration and initialization can be combined into a single statement.

01
02
    String name = "Bob";
    StdOut.println ("Hello " + name);

In both languages, + is used to represent string concatenation.

Here's another version which does not use concatenation.

PythonJava
01
02
03
04
05
06
07
def main():
    name = "Bob"
    print("Hello ", end="")
    print(name)

if __name__ == "__main__":
    main()
01
02
03
04
05
06
07
08
09
package algs11;
import stdlib.*;
public class Hello {
  public static void main (String[] args) {
    String name = "Bob";
    StdOut.print ("Hello ");
    StdOut.println (name);
  }
}

Types [6/12]

PythonJava
01
02
03
04
05
06
07
08
def main():
    x = "Bob"
    print("Hello " + x)
    x = 42
    print(x - 1)

if __name__ == "__main__":
    main()
01
02
03
04
05
06
07
08
09
10
11
package algs11;
import stdlib.*;
public class Hello {
  public static void main (String[] args) {
    String x;
    x = "Bob";
    StdOut.println ("Hello " + x);
    x = 42; // Compiler error
    StdOut.println (x - 1); // Compiler error
  }
}

Python allows a single variable to be used at multiple types.

By typing variables, java catches more errors before runtime.

PythonJava
01
02
03
04
05
06
def main():
    x = "Bob"
    print(x - 1)

if __name__ == "__main__":
    main()
01
02
03
04
05
06
07
08
09
package algs11;
import stdlib.*;
public class Hello {
  public static void main (String[] args) {
    String x;
    x = "Bob";
    StdOut.println (x - 1);
  }
}

Java does more implicit conversions than python.

PythonJava
01
02
03
04
05
06
def main():
    x = "Bob"
    print(x + 1)

if __name__ == "__main__":
    main()
01
02
03
04
05
06
07
08
09
package algs11;
import stdlib.*;
public class Hello {
  public static void main (String[] args) {
    String x;
    x = "Bob";
    StdOut.println (x + 1);
  }
}

You can safely ignore the rest of this slide, which uses some more advanced java features that you don't need just yet.

The special class java.lang.Integer is used to create objects holding a single integer (more later).

All java objects can be referenced at type Object.

Using these properties it is possible to mimic the original python code above, but java requires explicit casts in order to apply the concatenation and subtraction operators.

PythonJava
01
02
03
04
05
06
07
08
def main():
    x = "Bob"
    print("Hello " + x)
    x = 42
    print(x - 1)

if __name__ == "__main__":
    main()
01
02
03
04
05
06
07
08
09
10
11
package algs11;
import stdlib.*;
public class Hello {
  public static void main (String[] args) {
    Object x;
    x = "Bob";
    StdOut.println ("Hello " + ((String) x));
    x = 42;
    StdOut.println (((Integer) x) - 1);
  }
}

Java will do implicit conversions in some places.

The difference between the two casts occurs because every java object can be converted to a String, using java.util.Objects.toString. In some contexts, this will be done implicitly.

Syntax [7/12]

PythonJava
01
02
03
04
05
06
07
def main():
    name = "Bob"
    print("Hello ", end="")
    print(name)

if __name__ == "__main__":
    main()
01
02
03
04
05
06
07
08
09
package algs11;
import stdlib.*;
public class Hello {
  public static void main (String[] args) {
    String name = "Bob";
    StdOut.print ("Hello ");
    StdOut.println (name);
  }
}

Java uses semicolons and curly-braces, where python uses newlines, colons and indentation.

When formatting java, the conventions for indentation and newlines mimic those of python. But in java, these are just conventions, not requirements.

If statements (aka conditionals)

PythonJava
01
02
03
04
05
06
07
08
def main():
    i = int(input('Enter a number: '))
    if i < 5:
        n = 2 ** i
        print (n)

if __name__ == "__main__":
    main()
01
02
03
04
05
06
07
08
09
10
11
12
package algs11;
import stdlib.*;
public class Hello {
  public static void main (String[] args) {
    StdOut.print ("Enter a number: ");
    int i = StdIn.readInt ();
    if (i < 5) {
      int n = (int) Math.pow (2, i);
      StdOut.println (n);
    }
  }
}

Comment: Python's ** operator returns an int when both arguments are ints. (If either argument is a float, it returns a float.)

Java's Math.pow, instead, always returns a double. So, to recover an int, the Java code requires a cast.

While statements (aka loops)

PythonJava
01
02
03
04
05
06
07
08
def main():
    i = int(input('Enter a number: '))
    while i < 5:
        print (i)
        i = i + 1

if __name__ == "__main__":
    main()
01
02
03
04
05
06
07
08
09
10
11
12
package algs11;
import stdlib.*;
public class Hello {
  public static void main (String[] args) {
    StdOut.print ("Enter a number: ");
    int i = StdIn.readInt ();
    while (i < 5) {
      StdOut.println (i);
      i = i + 1;
    }
  }
}

For loops

PythonJava
01
02
03
04
05
06
07
def main():
    for i in range(int(input('Enter a number: ')), 5, -3):
        n = 2 ** i
        print (n)

if __name__ == "__main__":
    main()
01
02
03
04
05
06
07
08
09
10
11
package algs11;
import stdlib.*;
public class Hello {
  public static void main (String[] args) {
    StdOut.print ("Enter a number: ");    
    for (int i = StdIn.readInt (); i > 5; i = i - 3) {
      int n = (int) Math.pow (2, i);
      StdOut.println (n);
    }
  }
}

Function declarations [8/12]

PythonJava
01
02
03
04
05
06
07
08
09
def addHello(x):
    return "Hello " + x

def main():
    print(addHello("Bob"))
    print(addHello("Alice"))

if __name__ == "__main__":
    main()
01
02
03
04
05
06
07
08
09
10
11
package algs11;
import stdlib.*;
public class Hello {
  public static String addHello (String x) {
    return "Hello " + x;
  }
  public static void main (String[] args) {
    StdOut.println (addHello ("Bob"));
    StdOut.println (addHello ("Alice"));
  }
}

Java requires declaration of return type and parameter types.

Because of types, java compiler can catch more errors, as below. What's wrong?

PythonJava
01
02
03
04
05
06
07
08
09
def addHello(x):
    "Hello " + x

def main():
    print(addHello("Bob"))
    print(addHello("Alice"))

if __name__ == "__main__":
    main()
01
02
03
04
05
06
07
08
09
10
11
package algs11;
import stdlib.*;
public class Hello {
  public static String addHello (String x) {
    "Hello " + x;
  }
  public static void main (String[] args) {
    StdOut.println (addHello ("Bob"));
    StdOut.println (addHello ("Alice"));
  }
}

Lists/Arrays [9/12]

PythonJava
01
02
03
04
05
06
07
08
09
10
def myprint(a):
    for x in a:
        print(x)

def main():
    lst = [11,21,31]
    myprint(lst)

if __name__ == "__main__":
    main()
01
02
03
04
05
06
07
08
09
10
11
12
13
package algs11;
import stdlib.*;
public class Hello {
  public static void myPrint (double[] a) {
    for (double x : a) {
       StdOut.println(x);
    }
  }
  public static void main (String[] args) {
    double[] lst = { 11, 21, 31 };
    myPrint (lst);
  }
}
PythonJava
01
02
03
04
05
06
07
08
09
10
def myprint(a):
    for i in range(len(a)):
        print(i, a[i])

def main():
    lst = [11,21,31]
    myprint(lst)

if __name__ == "__main__":
    main()
01
02
03
04
05
06
07
08
09
10
11
12
13
package algs11;
import stdlib.*;
public class Hello {
  public static void myPrint (double[] a) {
    for (int i=0; i<a.length; i++) {
       StdOut.println(i + " " + a[i]);
    }
  }
  public static void main (String[] args) {
    double[] lst = { 11, 21, 31 };
    myPrint (lst);
  }
}
PythonJava
01
02
03
04
05
06
07
08
09
10
def myprint(a):
    for i,x in enumerate(a):
        print(i, x)

def main():
    lst = [11,21,31]
    myprint(lst)

if __name__ == "__main__":
    main()
01
02
03
04
05
06
07
08
09
10
11
12
13
14
package algs11;
import stdlib.*;
public class Hello {
  public static void myPrint (double[] a) {
    for (int i=0; i<a.length; i++) {
       double x = a[i];
       StdOut.println(i + " " + x);
    }
  }
  public static void main (String[] args) {
    double[] lst = { 11, 21, 31 };
    myPrint (lst);
  }
}

More about Arrays [10/12]

java.util.Arrays includes a useful function for printing arrays:

01
02
03
04
05
06
07
08
09
10
package algs11;
import stdlib.*;
import java.util.Arrays;
public class Hello {
  public static void main (String[] args) {
    double[] lst = { 11, 21, 31 };
    StdOut.println (lst);
    StdOut.println (Arrays.toString(lst));
  }
}

The size of a Java array is fixed when it is created.

PythonJava
01
02
03
04
05
06
07
08
09
10
11
12
13
def createList(size):
    lst = []
    for i in range(size):
        lst.append(0)
    return lst

def main():
    lst = createList(3)
    lst[1] = 21
    print (lst)

 if __name__ == "__main__":
    main()
01
02
03
04
05
06
07
08
09
10
11
12
13
package algs11;
import stdlib.*;
import java.util.Arrays;
public class Hello {
  public static double[] createList (int size) {
    return new double[size];
  }
  public static void main (String[] args) {
    double[] lst = createList(3);
    lst[1] = 21;
    StdOut.println(Arrays.toString(lst));
  }
}

Java arrays are similar to numpy arrays, in that their length is fixed when they are created.

import numpy as np    
a1 = np.array([11, 21, 31]) # fixed length
a2 = np.resize(a1, 4)       # returns a new array of the specified size, with copies of old elements
a2[3] = 41
print (a2)                  # [11, 21, 31, 41]

In addition to numpy arrays, python has another type of arrays, which have variable length like python lists. These are only available for base types, like int and double.

import array as arr    
a3 = arr.array('i', [11, 21, 31]) # variable length array of ints
a3.append (41)
print (a3)                        # array('i', [11, 21, 31, 41])

a4 = arr.array('d', [11, 21, 31]) # variable length array of doubles
a4.append (41)
print (a4)                        # array('d', [11.0, 21.0, 31.0, 41.0])

Formatting Output [11/12]

java.util.Formatter describes formatting conventions.

It's not necessary to use the Formatter class directly.

The Formatter.format() method is used by StdOut.format(), String.format(), and similar methods.

01
02
03
04
05
06
07
08
09
10
11
package algs11;
import stdlib.*;
import java.util.Arrays;
public class Hello {
  public static void main (String[] args) {
    double d = Math.PI;
    int i = Integer.MAX_VALUE;
    double[] lst = { 11, 21, 31 };
    StdOut.format ("d=%f, i=%d\nlst=%s%n", d, i, Arrays.toString(lst));
  }
}

StdOut.format takes a variable number of arguments.

Extras: Scope [12/12]

PythonJava
01
02
03
04
05
06
07
08
09
10
def declareX():
    global x
    x = 0

def useX():
    x 

useX() # runtime error
declareX()
useX() # no problems  
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
package algs11;
import stdlib.*;
public class Hello {
  public static void declareX () {
    int x;
  }
  public static void useX () {
    x;  // compiler error
  }    
  public static void main (String[] args) {
    useX ();
    declareX ();
    useX ();
  }
}

Java compiler removes names for variables. Only the values are stored at runtime. The variable names are replaced with numbers (offsets in memory). This is one characteristic of static languages.

Python keeps names for variables at runtime. It stores a map (aka, a dictionary) from variable names to values. This is characteristic of dynamic languages.

Java's approach is more efficient. Python's is more flexible.

Scripting languages, such as perl and javascript, use the python approach. Most other languages, including C, C++, C#, objective-C, swift and FORTRAN, use the java approach.


Revised: 2008/03/17 13:01