1 / 62

Interpreted vs. Compiled: Programming Language Implementation Choices

This review explores the differences between interpreted and compiled programming languages, including examples and their pros and cons.

bessien
Download Presentation

Interpreted vs. Compiled: Programming Language Implementation Choices

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Review

  2. To Compile or Interpret? • A language design and implementation choice • What is a COMPILER ? Give an example. • What is an INTERPRETER? Give an example.

  3. Interpreted Languages • Interpreted: BASIC, Perl, SQL, Matlab, JavaScript • The interpreterreads the source program and executes each command as it is read. The interpreter “knows” how to perform each instruction in the language. Source Program Interpreter Execution

  4. Language processing: Compiled • Compiled: C/C++, C#, Fortran • The compiler converts source code into machine language to create an object code file. • A linker combines object code files and pre-compiled libraries to produce an executable program (machine language).

  5. Compiling a Program Source Code file.obj .sym printf FE048C7138 029845AAAF ... Object Code Compiler file.c main() { printf("hello"); exit(0); } Executable Program Linker printf.obj <obj. code for printf function> Libraries (of object codes) file.exe <hardware instructions>

  6. Interpreted More flexible More interactive Rapid development Can write & run program immediately Can run on any machine that has the interpreter Compiled More efficient Extensive data checking More structured Usually more scalable (can develop large applications) Must re-compile program after each change Must re-compile for each hardware/OS Interpreted versus Compiled

  7. Hello.java Java: A Hybrid Strategy • Java Compiler: compiles program to create a machine independent byte code. • Java Virtual Machine (interpreter): executes the byte code. Libraries Hello, World! javac Hello.class java Java source program Javacompiler byte code Java VM: - byte checker - class loader - interpreter - security mgr Program execution Java Runtime Environment (JRE) Machine independent byte code can run almost anywhere

  8. Java Trivia • What is the command to compile a Java source file named "Hello.java" ? ubuntu> • What is the command to execute a Java class file named "Hello.class" ? C:\DOS\never\dies>

  9. Import • What does "import java.util.Scanner" do? • include the Scanner class in compiled program. • include Scanner source code in this class • add java.util.Scanner to CLASSPATH • add java.util.Scanner to current name space

  10. Import • The "import" command is processed by (choose one): • Java compiler • Java interpreter (Java VM) • Java program editor • "import X.Y" is like what statement in C# ? • using X.Y; • namespace X.Y • include "X.Y"

  11. Identify Me String java.lang.String "hello class" "hello class".length( ) java.lang java.lang.System java.lang.management System.out System.out.println("hello") Math.sqrt( ) Math.PI java.lang.Comparable Object java.util.Arrays.sort(array) org.greenfoot long Identify as one of: • package • class • object • primitive type • attribute of object • instance method • static method • class constant • interface

  12. Locations • What is "java.lang" ? • Name some classes in "java.lang" • (True/False) You should always "import java.lang.*" so your program can use the classes in java.lang.

  13. More import (True/False) The command "import java.util.*" does... • includes the code for all classes in java.util into your program • adds all classes in java.util to the name space • makes the compiled program larger

  14. Ordering In a Java file, which of these should come first? second? third? fourth? ____ public class MyClass { ... } ____ package packagename; ____ /** * javadoc comment for this class * @author me */ ____ import stuff;

  15. Ordering of Contents In a Java class named Person, which of these should come first? second? third? fourth? ____ public Person(String first, String last) {..} ____ public String getFirstName() { return firstName; } ____ /** return the person's first name */ ____ private String firstName; ____ private static final char SEPERATOR = ',';}

  16. More import • Java has 2 Date classes: java.util.Date & java.sql.Date. Which Date class will be used here? import java.util.*; import java.sql.*; public class Test { Date today = new Date( ); ...etc... } Answers: 1. java.util.Date because java.util is imported first. 2. java.sql.Date because java.sql was imported last. 3. implementation dependent (can be either one). 4. neither - compiler will raise an error

  17. No Ambiguity Allowed • If there are 2 or more classes with the same name in the list of imports, the compiler issues an error. • No error if you exactly specify the class name on the import command. import java.util.*; import java.sql.*; import java.util.Date; // specify the Date class public class Test { Date today = new Date( ); ...etc... } ambiguous (not clear)

  18. No import • How can you use Date without an "import" ? public class Test { Date today = new Date( ); // ??? how ??? ...etc... }

  19. No import (answer) • Write the complete path. public class Test { java.util.Date today = new java.util.Date( ); ...etc... } This is necessary when loading classes at runtime. For example: Class cl = Class.forName( "java.util.Date" ); // load the class Date now = (Date) cl.newInstance( );// new object

  20. No Import - Why? Database Connector: • we want to let the user choose his database (MySQL, Postresql, Oracle, ...) • each database requires its own connector Solution: • read name of database connector from a file • load the class at runtime

  21. Demo

  22. What is "import static" ? • What does "import static ... " mean? import static java.lang.Math.*; public class Circle { double radius; // radius of circle /** get area of circle */ public double area() { return PI * pow(radius,2); } Math.pow Math.PI

  23. import static JOptionPane import static javax.swing.JOptionPane.*; public class WakeUp { ... intchoice; choice = showConfirmDialog( null, "Are you awake?","This is a Confirm Dialog", YES_NO_CANCEL_OPTION ); if ( choice == NO_OPTION ) showMessageDialog( null, "Liar!!");

  24. Static block • What does static { ... } mean? public class Point { double x; double y; public static final Point INFINITY; public static final Point ORIGIN; static { double zero = 0.0; INFINITY = new Point(1.0/zero, 1.0/zero); ORIGIN = new Point(zero, zero); System.out.println("Point class is loaded"); }

  25. The "." • What does "." mean? ...as in: System.out.println( ); Math.PI; java.util.Scanner; obj.toString( ); Answer: "." is the scope resolution operator. "obj.toString()" means "the toString() object belonging to obj". • What symbol does C++ use for Java's "." ? Answer: C++ uses :: e.g., as obj::toString();

  26. Constructors? • What is the purpose of a constructor? • Can you write a class with no constructors? • Can a class have more than one constructor? How? • Can one constructor call another constructor? • If so, how? • Can you use an object to call its class constructor? For example: String am = new String("good morning"); String pm = am.String("good afternoon"); • If not, then how do you call a constructor?

  27. Constructors, again Can a constructor call superand call another constructor? // calling superclass constructor public Student( String name, String id, String phone ) { super( name, phone ); this.id = id; } can we do this statement first? // calling our other constructor public Student( String name, String id ) { this( name, id, "" ); } // can we do both? public Student( String name, String id ) { super( name, id ); this( name, id, "" ); }

  28. Constructors (2) • The Fraction class has multiple constructors: Fraction half = new Fraction(1, 2); // = 1/2 Fraction ten = new Fraction( 10 ); // = 10/1 • If both constructors perform similar actions, eliminate duplicate code: let one constructor invoke the other. public class Fraction { /** construct a new Fraction = num/denom */ public Fraction( long num, long denom ) { /* do the real work here */ } /** constructor makes fraction from an int. */ public Fraction( long num ) { this( numerator, 1L ); // call other constr. }

  29. Constructors (3) • What is wrong here? public class Fraction { /** construct a new Fraction object */ public Fraction( long num, long denom ) { /* do the real work here */ ... } /** constructor makes fraction from a double */ public Fraction(double x) { if ( Double.isNaN(x) ) this( 0L, 0L ); else if ( Double.isInfinite(x) ) this( 1L, 0L ); else ... }

  30. Constructor (4) • If a class has a constructor and an initialization block, which one is used when you use "new Fraction(...)" ? public class Fraction { /** initialization block */ { System.out.println("Run init block."); } /** construct a new Fraction object */ public static Fraction( long num, long denom ) { System.out.println("Run constructor..."); /* do the real work here */ } public static void main(String[] args) { Fraction half = new Fraction(1,2);

  31. What will be printed? (1) public class Point { double x, y; public static final Point ORIGIN; static { // static initialization block System.out.println("Static init block..."); ORIGIN = new Point(0.0, 0.0); } { // dynamic initialization block System.out.println("Init block..."); } public Point(double x, double y) { System.out.printf("Construct (%f,%f)\n",x,y); this.x = x; this.y = y; } ... Point p = new Point( 0.5, 2.0 );

  32. What will be printed? (2) public class TestPoint { public static void main(String [] args){ System.out.println("Test: make a point"); Point e1 = new Point(1, 2); System.out.println("Test: another point"); Point e2 = new Point(3, 4); } }

  33. Fraction class (1) • The fraction class should store fractions as a numerator and denominator. • Each fraction should have a unique representation. The constructor is important for this. public Fraction (long num, long denom) { // (1) eliminate any common factors long gcd = gcd( num, denom); // always > 0 num = num/gcd; denom = denom/gcd; // (2) make sure denominator is >= 0 write the code yourself. // (3) now assign the attributes write the code yourself. }

  34. Fraction class (2) • To design methods, do the calculation as you would on paper. • Example: • So, division should "intuitively" return a new Fraction that is (a*d) / (b*c): public Fraction divide(Fraction f) { return new Fraction( numerator*f.denominator, f.numerator*denominator ); }

  35. Fraction class (3) • Check that extended numbers are handled correctly: this = NaN (0/0), f = NaN (0/0) this.divide(f) ==> should be NaN check: Fraction(0*0 , 0*0) [ OK ] this = Infinity (1/0), f = finite number, not zero this.divide(f) ==> should be Infinity check: Fraction( 1*f.denom, 0*f.numer) [OK] this = 1 (1/1), f = Infinity (1/0) this.divide(f) ==> should be 0 check: Fraction(1*0, 1*1) [ OK ]

  36. Fraction class (4) this = Infinity (1/0), f = 0 (0/1) this.divide(f) ==> should be NaN check: Fraction(1*1, 0*0) [ not OK ] • this case doesn't give the correct result, so you need to handle it in the divide method. public Fraction divide(Fraction f) { if ( isInfinite( ) && f.equals(ZERO) ) return NAN; return new Fraction( numerator*f.denominator, f.numerator*denominator ); } this code supposes you had predefined static constants ZERO and NAN

  37. Fraction class (5) • you must also include Javadoc comments for the class, public constants, and all methods! /** return a new fraction equal to the quotient of * this fraction and f. May be Infinity or NaN. * @param f is the fraction to divide by * @return quotient of this divided by f. */ public Fraction divide(Fraction f) { if ( isInfinite( ) && f.equals(ZERO) ) return NAN; return new Fraction( numerator*f.denominator, f.numerator*denominator ); }

  38. Fraction class (6) • Example: • Special cases: What if (a/b) is Infinity (1/0) and (c/d) is Infinity (1/0). The result should be Infinity. Is it? (1/0) + (1/0) = (1*0 + 0*1)/(0*0) = 0/0 = NaN this means you have to handle this case separately.

  39. More Review Questions

  40. Fraction class (again) • when I run the Fraction Calc or Fraction Console, it prints: "fraction@53ba30". Why? Inheritance: Fraction is a subclass of Number; Number is a subclass of Object. If Fraction doesn't have a toString() method, then it will inherit the toString from the Object class.

  41. The Three Noble Truths Encapsulation: an object contains both data and the methods that operate on the data. It may expose some of these to the outside and hide others.This design separates the publicinterface from the implementation, and enforces data integrity. Inheritance: one class can inherit attributes and methods from another class. Polymorphism: the operation performed by a named method can depend on context. In particular, it can depend on the type of object it is applied to.

  42. Example: The Three Noble Truths • Give an example of polymorphism. Number x; // x is a reference to a Number object x = new BigDecimal( Math.PI ); // BigDecimal is a subclass of Number, so // this is OK. System.out.println("x = "+ x.toString ); // calls the toString() method of BigDecimal x = new Fraction( 2, 33 ); // Fraction is also a subclass of Number System.out.println("x = "+ x.toString ); // calls the toString() method of Fraction

  43. Arrays (1) • How do you declare x to reference an array of double? double [ ] x; • How do you create an array of 100 double and assign x to reference it? x = new double[100]; • How do you define an array reference y and set y to reference the same array as x? double [ ] y = x; • What is the index of the last element of x? 99 • Does the statement "y[1] = 10" change x[1]? yes. y refers to the same array as x

  44. Arrays (2) • What attribute or method returns the size of an array? length as in x.length • Is "length" an attribute or a method? attribute. In contrast, for a String s, s.length() is a method. • Using length, set "last" equal to the last element of x. double last = x[x.length - 1]; • Is x an object or primitive data type? What about x[1]? x is an object, x[1] is a double • From the questions above, what fact tells you that x must be an object, not a primitive? primitive data types don't have attributes

  45. Arrays (3) • How would create a new array z and copy x to z? double [] z = new double[x.length]; // arraycopy( src, src_start, dest, dest_start, count) System.arraycopy(x, 0, z, 0, x.length); • How would you copy x to z using a loop? for(int k=0; k<x.length; k++) z[k] = x[k]; • What does the statement "z = x" do? make z to refer to the same array as x. The old storage allocated to z is lost! • What is the meaning of this statement?String [] fruit = { "Apple", "Orange", "Grape" }; create a new array of length 3 and assign values to the array elements

  46. Arrays (4) • What is wrong with these statements?String s = "Arrays are very useful";String [] words = new String [4];words = s.split("\\s+"); //split at whitespace The "words = new String[4]" is useless! The third line will set words to a new array (returned by split), so the old array is discarded. A better way to write this is: String s = "Arrays are very useful";String [] words = s.split("\\s+");

  47. Arrays (5) • What is the value of dates[1] after this statement?Date [] dates = new Date[10]; null. This line only creates an array of Date references. It doesn't create any Date objects. • How do you create Date objectsfor this array? for(int k=0; k < dates.length; k++) dates[k] = new Date( ); • What is the value of score[1] after this statement?int [] score = new int[10]; 0"int" is a primitive data type, so the array elements contain the data values.

  48. Arrays (6) • Can you change the size of an array after you create it? For example: double [] score = new double[10];int k = 0;// read scores into an arraywhile( input.hasNextDouble() && k < score.length ) score[k++] = input.nextDouble();if ( input.hasNextDouble() ) {// oops! we need a bigger array score = new double[20]; // (1) }// now read more data... while( ... ) score[k++] = input.nextDouble(); You can't change the size of an array.Statement (1) discards the old array!

  49. Arrays (7) • How can you read data and save in an array if you don't know how much data there will be? Use an ArrayList After reading the data, convert it to an array of exactly the size of the actual data. (CJ, page 180). import java.util.ArrayList; ... ArrayList<double> arr = new ArrayList<double>( );// read scores into an arraywhile( input.hasNextDouble() ) { double ascore = input.nextDouble(); arr.add ( ascore ); }// now convert to an arraydouble [] score = new double[ arr.size() ]; score = arr.toArray( score );

  50. String, Double, Integer, ... • After creating a String object, can you change the String object? No. Strings are immutable.The String class doesn't contain any "set", "append", "insert", "clear", "delete" or other methods to modify a string object. • What about String s = "hello"; s = s + " world"; Doesn't that change the String s? No. "+" creates a new string. • Can you change the value of a Double, Integer, etc.? No. These objects are also immutable. immutable: cannot be changed.

More Related