Review To Compile or Interpret q A language














































![Arrays (5( q What is the value of dates[1] after this statement? Date [] Arrays (5( q What is the value of dates[1] after this statement? Date []](https://slidetodoc.com/presentation_image_h/2da5ac5123927fed0cc6bf03deb34ff5/image-47.jpg)















- Slides: 62

Review

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

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

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

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

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

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

Java Trivia q What is the command to compile a Java source file named "Hello. java" ? ubuntu> q What is the command to execute a Java class file named "Hello. class" ? C: DOSneverdies>

Import q What does "import java. util. Scanner" do? 1. include the Scanner class in compiled program. 2. include Scanner source code in this class 3. add java. util. Scanner to CLASSPATH 4. add java. util. Scanner to current name space

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

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

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

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

Ordering In a Java file, which of these should come first? second? third? fourth? 1. 2. 3. 4. 5. 6. 7. ____ public class My. Class {. . . } ____ packagename; ____ /** * javadoc comment for this class * @author me */ ____ import stuff;

Ordering of Contents In a Java class named Person, which of these should come first? second? third? fourth? 1. ____ public Person(String first, String last) {. . } 2. ____ public String get. First. Name() { return first. Name; } 3. ____ /** return the person's first name */ 4. ____ private String first. Name; 5. ____ private static final char SEPERATOR = ', '; }

More import q 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

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

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

No import (answer( q 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. for. Name( "java. util. Date" ); // load the class Date now = (Date) cl. new. Instance( ); // new object

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

Demo

What is "import static? " q 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. PI Math. pow

import static JOption. Pane import static javax. swing. JOption. Pane. *; public class Wake. Up {. . . int choice; choice = show. Confirm. Dialog( null, "Are you awake? ", "This is a Confirm Dialog", YES_NO_CANCEL_OPTION ); if ( choice == NO_OPTION ) show. Message. Dialog( null, "Liar!!");

Static block q 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"); }

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

Constructors? q What is the purpose of a constructor? q Can you write a class with no constructors? q Can a class have more than one constructor? How? q Can one constructor call another constructor? n q 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"); q If not, then how do you call a constructor?

Constructors, again Can a constructor call super and 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, "" ); }

Constructors (2( q The Fraction class has multiple constructors: Fraction half = new Fraction(1, 2); // = 1/2 Fraction ten = new Fraction( 10 ); // = 10/1 q 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, 1 L ); // call other constr. }

Constructors (3( q 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. is. Na. N(x) ) this( 0 L, 0 L ); else if ( Double. is. Infinite(x) ) this( 1 L, 0 L ); else. . . }

Constructor (4( q 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);

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 );

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

Fraction class (1( The fraction class should store fractions as a numerator and denominator. q Each fraction should have a unique representation. The constructor is important for this. q 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. }

Fraction class (2( To design methods, do the calculation as you would on paper. q Example: q q 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 ); }

Fraction class (3( q Check that extended numbers are handled correctly: this = Na. N (0/0), f = Na. N (0/0) this. divide(f) ==> should be Na. N 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 ]

Fraction class (4( this = Infinity (1/0), f = 0 (0/1) this. divide(f) ==> should be Na. N check: Fraction(1*1, 0*0) [ not OK ] q this case doesn't give the correct result, so you need to handle it in the divide method. public Fraction divide(Fraction f) { if ( is. Infinite( ) && 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

Fraction class (5( q 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 Na. N. * @param f is the fraction to divide by * @return quotient of this divided by f. */ public Fraction divide(Fraction f) { if ( is. Infinite( ) && f. equals(ZERO) ) return NAN; return new Fraction( numerator*f. denominator, f. numerator*denominator ); }

Fraction class (6( q q 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 = Na. N this means you have to handle this case separately.

More Review Questions

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

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 public interface 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.

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

Arrays (1( q q 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; q What is the index of the last element of x? 99 q q Does the statement "y[1] = 10" change x[1]? yes. y refers to the same array as x

Arrays (2( q q q 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

Arrays (3( q How would create a new array z and copy x to z? double [] z = new double[x. length]; // arraycopy( src, src_start, dest_start, count) System. arraycopy(x, 0, z, 0, x. length); q How would you copy x to z using a loop? for(int k=0; k<x. length; k++) z[k] = x[k]; q 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! q What is the meaning of this statement? String [] fruit = { "Apple", "Orange", "Grape" };

Arrays (4( q 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+");
![Arrays 5 q What is the value of dates1 after this statement Date Arrays (5( q What is the value of dates[1] after this statement? Date []](https://slidetodoc.com/presentation_image_h/2da5ac5123927fed0cc6bf03deb34ff5/image-47.jpg)
Arrays (5( q 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. q q How do you create Date objects for 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.

Arrays (6( q 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 array while( input. has. Next. Double() && k < score. length ) score[k++] = input. next. Double(); if ( input. has. Next. Double() ) { // oops! we need a bigger array score = new double[20]; // (1) } // now read more data. . . while(. . . ) score[k++] = input. next. Double(); You can't change the size of an array. Statement (1) discards the old array!

Arrays (7( q How can you read data and save in an array if you don't know how much data there will be? Use an Array. List After reading the data, convert it to an array of exactly the size of the actual data. (CJ, page 180). import java. util. Array. List; . . . Array. List<double> arr = new Array. List<double>( ); // read scores into an array while( input. has. Next. Double() ) { double ascore = input. next. Double(); arr. add ( ascore ); } // now convert to an array double [] score = new double[ arr. size() ]; score = arr. to. Array( score );

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. q What about String s = "hello"; s = s + " world"; Doesn't that change the String s? No. "+" creates a new string. q Can you change the value of a Double, Integer, etc. ? No. These objects are also immutable. q immutable: cannot be changed.

Fractions class (again( q are Fraction object mutable or immutable? Immutable: all the methods in the Fraction class return a new Fraction. None of the methods modify an existing Fraction. This is useful: it means that if the Fraction constructor creates a fraction in standard form (least common denominator, no negative in denominator) then you don't have to check these conditions again.

String Processing (1( Why is this loop inefficient? String text; // text read from the input Scanner input = new Scanner(System. in); while ( input. has. Next( ) ) { String word = input. next( ); text = text + " " + word; // (1) } Each time (1) appends a word, it must copy the entire String (text) to a new string! The old String is discarded. q How could you make this more efficient? q

String Processing (2( q How could you make this more efficient? Use a String. Buffer or String. Builder object. You can append strings to a String. Builder (faster) or String. Buffer (thread-safe). When you are finished, convert the object to a String! String. Builder buf = new String. Builder(); Scanner input = new Scanner(System. in); while ( input. has. Next( ) ) { String word = input. next( ); buf. append(' '); append is polymorphic buf. append(word); } String text = buf. to. String( );

String Processing (3( q Is it worth the effort to use write extra code to use String. Builder? See my example program: Test. String. Builder. java It reads a file word-by-word and appends each word to a String or String. Builder, as in the previous slides. For a 40 KB file from the Java tutorial, I recorded these times: read and append to a String: 6. 60 seconds read and append to String. Builder: 0. 03 seconds read and append to String. Buffer: 0. 03 seconds For String. Buffer and String. Builder, these times include converting the result into a String object!

Immutable Objects q What does it mean for an object to be immutable? q Does this class define immutable objects? public class Appointment { No mutator methods! private Date date; private String description; public Appointment( Date when, String what ) { date = when; description = what; } public Date get. Date( ) { return date; } public String get. Description { return description; } }

Immutable Objects (2( It is mutable because Date is mutable. (See Horstmann for example. ) q To fix it, always copy the mutable Date object: q public class Appointment { private Date date; private String description; public Appointment( Date when, String what ) { date = (Date) when. clone(); description = what; } public Date get. Date( ) { return (Date)date. clone(); } public String get. Description { return description; } }

A Mutable Object q A Date object is mutable. The Date class provides methods such as set. Year(int), set. Month(int), and set. Date(int) to change the year, month, or day. Date millenia = new Date( 101, // = year - 1900 Calendar. JANUARY, // = month 1 ); // = day System. out. println(millenia); // prints "January 1, 2001" millenia. set. Year(99); // change year to 1999 millenia. set. Month(Calendar. MARCH); millenia. set. Date(15); System. out. println(millenia); // prints "March 15, 1999"

Encapsulation q q How can a class enforce encapsulation of attributes and still give the other classes ability to read an attribute's value? Make the attributes private and provide an accessor method Give an example. class Person { private String name; private Date birthday; public Person(String name, Date birthday) { /* set the attributes */ } // accessor method for name public String get. Name() { return name; }

Encapsulation and Mutability A Date object is mutable. The Date class has methods such as set. Year(int), set. Month(int), and set. Date(int). q Does this get. Birthday() method break encapsulation of the birthday object? q class Person { private String name; private Date birthday; public Person(String name, Date birthday) { /* set the attributes */ } // accessor method for birthday public Date get. Birthday() { return birthday; }

Encapsulation and Mutability (2( q Why? Give an example. Person you = new Person("a name", new Date(. . ) ); Date bd = you. get. Birthday( ); bd. set. Year( 99 ); // change the year to 1900 + 99 q How would you fix this problem? For mutable objects, return a copy of the object. class Person {. . . // accessor method for birthday public Date get. Birthday() { return new Date( birthday ); } q For more info, see Core Java chapter 4.

Encapsulation and Mutability (3( q Does this get. Name() method break encapsulation of the name object? class Person { private String name; private Date birthday; public Person(String name, Date birthday) { /* set the attributes */ } // accessor method for name public String get. Name() { return name; } q No. String objects are immutable, so the caller cannot use the return value to change the name attribute.

Encapsulation and Accessor Methods q For primitive data types and immutable objects, it is safe for an accessor method to return the value: class Bank. Account { private long balance; // account balance /** return the account balance */ public long get. Balance() { return balance; // this is safe } q For mutable objects, an accessor should return a copy: class Person { /** return the person's birthday */ public Date get. Birthday() { return new Date( birthday ); }