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.

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));
  }
}

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