Download R0-Review-Basics

Document related concepts
no text concepts found
Transcript
Review
To Compile or Interpret?

A language design and implementation choice

What is a COMPILER ? Give an example.

What is an INTERPRETER? Give an example.
Interpreted Languages
Interpreted: BASIC, Perl, SQL, Matlab, JavaScript
 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.

Source
Program
Interpreter
Execution
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).

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
FE048C7138
029845AAAF
...
Executable
Program
file.exe
<hardware
instructions>
Interpreted versus Compiled
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
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.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

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>
Import

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

The "import" command is processed by (choose one):
1. Java compiler
2. Java interpreter (Java VM)
3. Java program editor

"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:
 package
 class
 object
 primitive type
 attribute of
object
 instance method
 static method
 class constant
 interface
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
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.
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
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;
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 = ',';}
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
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.*;
ambiguous (not clear)
import java.sql.*;
import java.util.Date; // specify the Date class
public class Test {
Date today = new Date( );
...etc...
}
No import

How can you use Date without an "import" ?
public class Test {
Date today = new Date( );
...etc...
}
// ??? how ???
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
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
Demo
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.PI
Math.pow
import static JOptionPane
import static javax.swing.JOptionPane.*;
public class WakeUp {
...
int choice;
choice = showConfirmDialog( null,
"Are you awake?","This is a Confirm Dialog",
YES_NO_CANCEL_OPTION );
if ( choice == NO_OPTION )
showMessageDialog( null, "Liar!!");
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");
}
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();
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?
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)

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.
}
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 ...
}
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);
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 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);
}
}
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.
}
Fraction class (2)
To design methods, do the calculation as you would on
paper.
a b ad
 Example:

c d bc


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)

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 ]
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
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 );
}
Fraction class (6)
a c ad  bc
 
b d
bd

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.
More Review Questions
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.
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

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
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
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
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
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+");
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 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)

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.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!
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 array
while( input.hasNextDouble() ) {
double ascore = input.nextDouble();
arr.add ( ascore );
}
// now convert to an array
double [] score = new double[ arr.size() ];
score = arr.toArray( 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.
 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.
Fractions class (again)

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.hasNext( ) ) {
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.
 How could you make this more efficient?

String Processing (2)

How could you make this more efficient?
Use a StringBuffer or StringBuilder object.
You can append strings to a StringBuilder (faster) or
StringBuffer (thread-safe). When you are finished,
convert the object to a String!
StringBuilder buf = new StringBuilder();
Scanner input = new Scanner(System.in);
while ( input.hasNext( ) ) {
String word = input.next( );
buf.append(' ');
append is polymorphic
buf.append(word);
}
String text = buf.toString( );
String Processing (3)

Is it worth the effort to use write extra code to use
StringBuilder?
See my example program: TestStringBuilder.java
It reads a file word-by-word and appends each word to
a String or StringBuilder, as in the previous slides.
For a 40KB file from the Java tutorial, I recorded these
times:
read and append to a String:
6.60 seconds
read and append to StringBuilder:
0.03 seconds
read and append to StringBuffer:
0.03 seconds
For StringBuffer and StringBuilder, these times include
converting the result into a String object!
Immutable Objects

What does it mean for an object to be immutable?

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 getDate( ) { return date; }
public String getDescription { return description; }
}
Immutable Objects (2)
It is mutable because Date is mutable. (See Horstmann
for example.)
 To fix it, always copy the mutable Date object:

public class Appointment {
private Date date;
private String description;
public Appointment( Date when, String what ) {
date = (Date) when.clone();
description = what;
}
public Date getDate( ) { return (Date)date.clone(); }
public String getDescription { return description; }
}
A Mutable Object

A Date object is mutable. The Date class provides
methods such as setYear(int), setMonth(int), and
setDate(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.setYear(99); // change year to 1999
millenia.setMonth(Calendar.MARCH);
millenia.setDate(15);
System.out.println(millenia);
// prints "March 15, 1999"
Encapsulation

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 getName() {
return name;
}
Encapsulation and Mutability
A Date object is mutable. The Date class has methods
such as setYear(int), setMonth(int), and setDate(int).
 Does this getBirthday() method break encapsulation of
the birthday object?

class Person {
private String name;
private Date birthday;
public Person(String name, Date birthday)
{
/* set the attributes */ }
// accessor method for birthday
public Date getBirthday() {
return birthday;
}
Encapsulation and Mutability (2)

Why? Give an example.
Person you = new Person("a name", new Date(..) );
Date bd = you.getBirthday( );
bd.setYear( 99 ); // change the year to 1900 + 99

How would you fix this problem?
For mutable objects, return a copy of the object.
class Person {
...
// accessor method for birthday
public Date getBirthday() {
return new Date( birthday );
}

For more info, see Core Java chapter 4.
Encapsulation and Mutability (3)

Does this getName() 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 getName() {
return name;
}

No. String objects are immutable, so the caller cannot
use the return value to change the name attribute.
Encapsulation and Accessor Methods

For primitive data types and immutable objects, it is
safe for an accessor method to return the value:
class BankAccount {
private long balance; // account balance
/** return the account balance */
public long getBalance() {
return balance;
// this is safe
}

For mutable objects, an accessor should return a copy:
class Person {
/** return the person's birthday */
public Date getBirthday() {
return new Date( birthday );
}