This is an archived version of the course. Please see the latest version of the course.

Variables - Java vs. Python

In Java, a variable is some space reserved in memory, and has a type, a name, and a value assigned to it.

A Java variable

This is NOT how you should think of variables in Python. Variables in Python are more like Java variables that point to object references. More specifically, they point to some object in the heap (dynamic memory allocation).

Recall that, except for Java primitive types, you would usually initialise a new variable in Java with the new keyword, e.g. String text = new String("hey"). In this case, a variable stores as its value the address of the object it is pointing to in the memory heap. A variable is also statically bound to be of a certain type at compile time.

A Java variable pointing to a reference

In Python, a variable is simply a label (or a nickname) that always points to an object in the memory heap (remember, everything is an object in Python, including basic data types and None). That’s it.

Unlike in Java, a variable does not even have a type. It simply points to an object (which has a type!)

A Python variable

Like Java, Python also runs automatic garbage collection, so there is no need to worry about deallocating memory.