CSC300: Extras: Scope [12/12] Previous pageContents

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.

Previous pageContents