CSC300: Python to Java: Scope [34/40] Previous pageContentsNext page

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, replacing them with numbers (offsets in memory). This is one characteristic of static languages.

Python keeps names for variables at runtime. As a result, python uses hash tables to store variable/value pairs. 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 pageContentsNext page