Python and Java comparison

Construct

Python

Java

Primitive
Types

boolean, int, double
long (unlimited), complex

boolean, int, double
short, long, float
byte, char

Reference
Types

str
lists, dictionaries, tuples
everything

String
List, Map
any non-primitives

Variables

a = 3
b = 3.5
flag = True
c = 'hello'
c = 4

int a = 3;
double b = 3.5;
boolean flag = true;
String c = “hello”;
illegal

Arithmetic
expressions

a = 3 + 4 * 5
b = 2 ** 8
*, /, %, +, -
+=, -=

a = 3 + 4 * 5;
b = Math.pow(2, 8);
*, /, %, +, -
+=, -=
++, --

Binary
expressions

(a or b) and not c
<, >, <=, >=, ==, !=
<>

(a || b) && !c
<, >, <=, >=, ==, !=

String
expressions

c = “hello” + ' there'
hihi = 2 * 'hi'

String c = “hello” + “ there”;

Blocks

indentation

{
}

Conditional
statements

if a < b:
    block1
elif b < c:
    block2
else:
    block3

if (a < b) {
    block1;
}
else if (b < c) {
    block2;
}
else {
    block3;
}





Construct

Python

Java

For loops

for i in range(0, 4):
    print “iteration”, I

for word in ['these', 'are', 'words']:
    print “Word: “, word, len(word)

for (int i = 0; i < 5; i++) {
    System.out.println(“iteration “ + i);
}

int[] nums = {0, 1, 2, 3, 4};
for (int i : nums) {
    System.out.println(“iteration “ + i);
}

While loops

a = 0
while a < 5:
    print “iteration”, a
    a += 1

int a = 0;
while (a < 5) {
    System.out.println(“iteration “ + a);
    a++;
}

Arrays

a = [1, 1, 2, 3, 5, 8]
a[0] = 12
food = “spam”
c = food[1]
spa = food[0:3]

int[] a = {1, 1, 2, 3, 5, 8};
a[0] = 12;
String food = “spam”;
char c = food.charAt(1);
String spa = food.substring(0, 3);

Method
calls

obj.method()
chars = len(“aString”)

obj.method();
int chars = “aString”.length();

Comments

# single line comment
“”” Multiple line comment
for more information “””

// single line comment
/* Multiple line comment
for more information */