Review - Fordham

Midterm Review
6th week
Spring 2011
1
Primitive Types vs. Reference Types
 Java’s types: primitive types and reference types.
 Primitive types: boolean, byte, char, short, int, long, float and double.
 A primitive-type variable can store exactly one value of its declared
type at a time.
 Reference type variable (sometimes called reference) stores location of
object in memory, i.e., it refer to an object in program.
 E.g., Scanner input = new Scanner (System.in);
 A reference is required to invoke (i.e., call) method defined for the
object
 E.g., number1 = input.nextInt();
2
Primitive Types vs. Reference Types
 Primitive types: boolean, byte, char, short,
int, long, float, double
 A primitive variable => a cup with name,
size (type), and content
 Name: name of variable
 Size is measured in bits
 Content is the value of the variable stored as bits
 Reference type (or, nonprimitive types)
 Size: all reference variable have same size
 Content: bits representing a way to get to (access) a specific object
 Default value of null
 How JVM does it ? Pointers …
3
Primitive Types vs. Reference Types
4
5
Call methods on the Dog object through remote control
(i.e., reference variable): myDog.bark()
Primitive Types vs. Reference Types
 Java variables are either primitive type or reference type.
 A variable’s declared type indicates whether the variable is of a
primitive or a reference type
 If a variable’s type is not one of the eight primitive types, then it is a
reference type.
 E.g., array date type is a reference type
 int [] array = new int[20];
6
Scope Rules
 Scope of a parameter declaration: the body of the method in
which the declaration appears.
 Scope of a local-variable declaration: from the point at which
the declaration appears to the end of that block.
 Scope of a local-variable declared in initialization section of a
for statement’s header: the body of the for statement and the
other expressions in the header.
 A method or field’s scope: the entire body of the class.
7
Scope Rules (cont’d)
 Shadowing: If a local variable or parameter in a method has
the same name as a field of the class, the field is “hidden” until
the block terminates execution
 Avoid shadowing by use different names !
 Declaring a local variable for multiple times leads to
compilation error
8
Methods declaration
public static double maximum(double x, double y, double z)
{
…
}
 Method header
 modifiers: public, private, static
 return type: the data type of the value returned by the method, or
void if the method does not return a value.
 method name: the rules for field names apply to method names as
well, but the convention is a little different.
 parameter list in parenthesis: a comma-delimited list of input parameters,
preceded by their data types
9
Recursion Problem-Solving Concepts
 If method is called with more complex problem, problem divided into
two pieces—a piece the method knows how to do and a piece the
method does not know how to do (called recursive call or recursion
step)
 Base case
 Recursive method capable of solving only simplest case—the base
case
 If method is called with base case, method returns result
 Recursive call/recursion step
 Must resemble original problem but simpler or smaller version
 Method calls fresh copy of itself to work on smaller problem
 Normally includes return statement
10
Example Using Recursion: Factorials
 Factorial of n, or n! is the product
n · (n – 1) · (n – 2) · … · 1
With 1! equal to 1 and 0! Defined to be 1.
 Can be solved recursively or iteratively (nonrecursively)
 Recursive solution uses following relationship:
n! = n · (n – 1)!
11
12
1
2
// Fig. 15.3: FactorialCalculator.java
// Recursive factorial method.
3
4
public class FactorialCalculator
5
{
6
7
8
9
10
// recursive method factorial
public long factorial( long number )
{
if ( number <= 1 ) // test for base case
return 1; // base cases: 0! = 1 and 1! = 1
11
12
13
else // recursion step
return number * factorial( number - 1 );
} // end method factorial
14
15
// output factorials for values 0-10
16
public void displayFactorials()
17
{
18
// calculate the factorials of 0 through 10
19
for ( int counter = 0; counter <= 10; counter++ )
20
System.out.printf( "%d! = %d\n", counter, factorial( counter ) );
21
} // end method displayFactorials
22 } // end class FactorialCalculator
13
Common Programming Error
 Either omitting the base case or writing the recursion step
incorrectly so that it does not converge on the base case can
cause a logic error known as infinite recursion, where
recursive calls are continuously made until memory has been
exhausted. This error is analogous to the problem of an
infinite loop in an iterative (nonrecursive) solution.
14
Recursion and Method Call Stack
 Method call stack used to store method activation records
 Last-In-First-Out, or First-In-Last-Out
 Upon method call: a new method activation record is created
and pushed onto stack, it stores:
 Parameters: all parameters are pass-by-value
 Return address: where to return afterwards?
 Local variables
 Upon (recursive) method return, its activation record are
popped off the stack
 Resume execution based on return address
 For recursive call, it’s the previous recursive call
15
Method call stacks during factorial (3)
16
Recursion vs. Iteration
 Any problem that can be solved recursively can be solved
iteratively
 Both iteration and recursion use a control statement
 Iteration uses a repetition statement
 Recursion uses a selection statement
 Iteration and recursion both involve a termination test
 Iteration terminates when the loop-continuation condition fails
 Recursion terminates when a base case is reached
 Recursion can be expensive in terms of processor time and
memory space, but usually provides a more intuitive
solution
17
1
2
// Fig. 15.13: PermutationTest.java
// Testing the recursive method to permute strings.
3
4
import java.util.Scanner;
5
6
public class PermutationTest
{
7
8
9
10
Outline
public static void main( String args[] )
{
Scanner scanner = new Scanner( System.in );
Initial
Permutation permutationObject = new Permutation();
11
12
13
System.out.print( "Enter a string:
String input = scanner.nextLine();
14
15
// permute String
16
17
permutationObject.permuteString( "", input );
} // end main
18 } // end class PermutationTest
18
call to recursive method;
There are no removed
" );
characters yet, so first argument
// retrieve String to permute
is “”
Merge Sort
MergeSort algorithm is one which is defined recursively
Suppose we:
 divide an unsorted list into two sub-lists,
 sort each sub list
How quickly can we recombine the two sub-lists into a single
sorted list?
19
Example
Consider the two sorted arrays and an empty array
Define three indices at the start of each array
20
Example
 We compare 2 and 3: 2 < 3
 Copy 2 down
 Increment the corresponding indices
21
Example
 We compare 3 and 7
 Copy 3 down
 Increment the corresponding indices
22
Example
 We compare 5 and 7
 Copy 5 down
 Increment the appropriate indices
23
Example
 We compare 18 and 7
 Copy 7 down
 Increment...
24
Example
 We compare 18 and 12
 Copy 12 down
 Increment...
25
Example
 We compare 18 and 16
 Copy 16 down
 Increment...
26
Example
 We compare 18 and 33
 Copy 18 down
 Increment...
27
Example
 We compare 21 and 33
 Copy 21 down
 Increment...
28
Example
 We compare 24 and 33
 Copy 24 down
 Increment...
29
Example
We would continue until we have passed beyond the limit of
one of the two arrays
After this, we simply copy over
all remaining entries in the nonempty array
30
Merging Two Lists
Programming a merge is straight-forward:
 the sorted arrays, array1 and array2, are of size n1 and
n2, respectively, and
 we have an empty array, arrayout, of size n1 + n2
Define three variables
int in1 = 0, in2 = 0, out = 0;
which index into these three arrays
31
Merging Two Lists
We can then run the following loop:
#include <cassert>
//...
int in1 = 0, in2 = 0, out = 0;
while ( in1 < n1 && in2 < n2 ) {
if ( array1[in1] < array2[in2] ) {
arrayout[out] = array1[in1];
++in1;
} else {
assert( array1[in1] >= array2[in2] );
arrayout[out] = array2[in2];
++in2;
}
++out;
}
32
Merging Two Lists
We’re not finished yet, we have to empty out the remaining
array
for ( /* empty */ ; in1 < n1; ++in1, ++out ) {
arrayout[out] = array1[in1];
}
for ( /* empty */ ; in2 < n2; ++in2, ++out ) {
arrayout[out] = array2[in2];
}
33
MergeSort Algorithm
Question:
 we split the list into two sub-lists and sorted them
 how should we sort those lists?
Answer (theoretical):
 if the size of these sub-lists is > 1, use merge sort again
 if the sub-lists are of length 1, do nothing: a list of length one is
sorted
34
The Algorithm
However, just because an algorithm has excellent asymptotic
properties, this does not mean that it is practical at all levels
Answer (practical):
 If the sub-lists are less than some threshold length, use an
algorithm like insertion sort to sort the lists
 Otherwise, use merge sort, again
35
The Algorithm
Thus, a graphical interpretation of merge sort would be
36
The Algorithm
Some details:
 if the list size is odd, just split the array into two almost equally
sized list – one even, one odd
 each merging requires an additional array
 we can minimize the amount of memory required by using two arrays,
splitting and sorting in one, then merging the results between the two
arrays
37
The Algorithm
Merge sort using two arrays
38
Example
Applying the merge sort algorithm:
39
Run-time Analysis of Merge Sort
Thus, the time required to sort an array of size n > 1 is:
 the time required to sort the first half,
 the time required to sort the second half, and
 the time required to merge the two lists
That is:
Θ(1)
n 1

T( n)  
n

  Θ(n) n  1
2
T
2

Closed-form solution:
T( n)  Θ(n ln( n))
40
Merge Sort
 The (likely) first implementation of merge sort was on the
ENIAC in 1945 by John von Neumann
 The creator of the von Neumann
architecture used by all modern
computers:
http://en.wikipedia.org/wiki/Von_Neumann
41
Object-Oriented Programming
42
Class declaration
 We have designed several classes for our CashierRegister
project
 For each class, we defined data and method members
 Syntax of class declaration
 Use access modifier to control access to members
 Static vs non-static fields
 Static vs non-static methods
43
Software engineering observations
 A class is a user defined type
 A class’s public interface
 public methods: a view of the services the class provides to
the class’s clients
 A class’s implementation details
 private variables and private methods are not
accessible to the class’s clients
44
non-static method & this Reference
 Any non-static method must be called upon with an object
Time1.toString(); ## leads to compilation error !
Time1 t = new Time1; ## create Time1 object and use t to reference it
t.toString(); ## call toString() method upon a Time1 object referenced by t
 Non-static method can access this reference, a reference
to the object on which it is called upon
 implicitly use this when referring to the object’s instance
variables and other methods
 can be explicitly used to access instance variables when they are
shadowed by local variables or method parameters
45
Constructors
 Constructors: special method to initialize an object of a class
 Called when an object is the class is created
new Dog ( );
new Scanner (System.in);
 Java requires a constructor for every class
 Java will provide a default no-argument constructor if none is
provided
 The default constructor initialize instance variables with default value
 Default values are zero for primitive numeric types, false for
boolean values and null for references
 Unless default value for instance variables is acceptable, provide a
constructor
46
Overloaded Constructors
 Overloaded constructors
 Provide multiple constructor definitions with different
signatures
 No-argument constructor: the constructor invoked without
arguments
 this reference can be used to invoke another constructor
 Allowed only as the first statement in a constructor’s body
 A constructor can call methods of the class.
 However: instance variables might not yet be in a consistent state, because
constructor is in process of initializing object.
 Using instance variables before they have been initialized properly is a
logic error.
47
1
2
// Fig. 8.5: Time2.java
// Time2 class declaration with overloaded constructors.
3
4
5
6
7
8
private int hour;
// 0 - 23
private int minute; // 0 - 59
private int second; // 0 - 59
9
10
11
12
13
// Time2 no-argument constructor: initializes each instance variable
// to zero; ensures that Time2 objects start in a consistent state
public Time2()
{
14
15
16
17
18
19
20
21
48
public class Time2
{
this( 0, 0, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 no-argument constructor
// Time2 constructor: hour supplied, minute and second defaulted to 0
public Time2( int h )
{
this( h, 0, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 one-argument constructor
22
23
// Time2 constructor: hour and minute supplied, second defaulted to 0
24
public Time2( int h, int m )
25
26
27
28
{
this( h, m, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 two-argument constructor
29
// Time2 constructor: hour, minute and second supplied
30
public Time2( int h, int m, int s )
31
{
setTime( h, m, s ); // invoke setTime to validate time
32
33
} // end Time2 three-argument constructor
34
35
// Time2 constructor: another Time2 object supplied
36
public Time2( Time2 time )
37
{
38
// invoke Time2 three-argument constructor
39
this( time.getHour(), time.getMinute(), time.getSecond() );
40
} // end Time2 constructor with a Time2 object argument
41
42
// Set Methods
43
// set a new time value using universal time; ensure that
44
// the data remains consistent by setting invalid values to zero
45
public void setTime( int h, int m, int s )
46
{
47
setHour( h );
48
setMinute( m ); // set the minute
49
setSecond( s ); // set the second
50
51
49
// set the hour
} // end method setTime
52
// validate and set hour
53
public void setHour( int h )
54
{
hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
55
56
} // end method setHour
57
58
// validate and set minute
59
public void setMinute( int m )
60
{
minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
61
62
} // end method setMinute
63
64
// validate and set second
65
public void setSecond( int s )
66
{
second = ( ( s >= 0 && s < 60 ) ? s : 0 );
67
68
} // end method setSecond
69
70
// Get Methods
71
// get hour value
72
public int getHour()
73
{
74
75
76
50
return hour;
} // end method getHour
77
// get minute value
78
public int getMinute()
79
80
{
81
82
83
} // end method getMinute
84
public int getSecond()
85
86
{
87
} // end method getSecond
88
89
90
91
92
// convert to String in universal-time format (HH:MM:SS)
public String toUniversalString()
{
return String.format(
93
94
"%02d:%02d:%02d", getHour(), getMinute(), getSecond() );
} // end method toUniversalString
return minute;
// get second value
return second;
95
96
97
98
99
100
101
// convert to String in standard-time format (H:MM:SS AM or PM)
public String toString()
{
return String.format( "%d:%02d:%02d %s",
( (getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12 ),
getMinute(), getSecond(), ( getHour() < 12 ? "AM" : "PM" ) );
102
} // end method toString
103 } // end class Time2
51
1
// Fig. 8.6: Time2Test.java
2
// Overloaded constructors used to initialize Time2 objects.
Call overloaded
constructors
Outline
3
4
public class Time2Test
5
{
6
public static void main( String args[] )
7
{
8
Time2 t1 = new Time2();
// 00:00:00
9
Time2 t2 = new Time2( 2 );
// 02:00:00
10
Time2 t3 = new Time2( 21, 34 );
// 21:34:00
11
Time2 t4 = new Time2( 12, 25, 42 ); // 12:25:42
12
Time2 t5 = new Time2( 27, 74, 99 ); // 00:00:00
13
Time2 t6 = new Time2( t4 );
// 12:25:42
14
15
System.out.println( "Constructed with:" );
16
System.out.println( "t1: all arguments defaulted" );
17
System.out.printf( "
%s\n", t1.toUniversalString() );
18
System.out.printf( "
%s\n", t1.toString() );
19
52
20
21
22
23
System.out.println(
Outline
"t2: hour specified; minute and second defaulted" );
System.out.printf( "
%s\n", t2.toUniversalString() );
System.out.printf( "
%s\n", t2.toString() );
24
25
26
System.out.println(
"t3: hour and minute specified; second defaulted" );
27
System.out.printf( "
%s\n", t3.toUniversalString() );
28
System.out.printf( "
%s\n", t3.toString() );
29
30
System.out.println( "t4: hour, minute and second specified" );
31
System.out.printf( "
%s\n", t4.toUniversalString() );
32
System.out.printf( "
%s\n", t4.toString() );
33
34
System.out.println( "t5: all invalid values specified" );
35
System.out.printf( "
%s\n", t5.toUniversalString() );
36
System.out.printf( "
%s\n", t5.toString() );
37
53
38
39
40
41
System.out.println( "t6: Time2 object t4 specified" );
Outline
System.out.printf( "
%s\n", t6.toUniversalString() );
System.out.printf( "
%s\n", t6.toString() );
} // end main
42 } // end class Time2Test
t1: all arguments defaulted
00:00:00
12:00:00 AM
t2: hour specified; minute and second defaulted
02:00:00
2:00:00 AM
t3: hour and minute specified; second defaulted
21:34:00
9:34:00 PM
t4: hour, minute and second specified
12:25:42
12:25:42 PM
t5: all invalid values specified
00:00:00
12:00:00 AM
t6: Time2 object t4 specified
12:25:42
12:25:42 PM
54
Something new …
55
Using Command-Line Arguments
 It’s possible to pass arguments from the command line (these are
known as command-line arguments) to an application by
including a parameter of type String[] in the parameter list of
main.
 By convention, this parameter is named args.
 When an application is executed using java command,
 i.e., java Cashier weekend
 Java passes command-line arguments that appear after class name
(i.e., weekend) to the application’s main method as Strings in the
array args.
56
57
58
59
Enhanced for Statement
 Iterates through elements of an array without using a counter
 Avoiding possibility of “stepping outside” the array.
 Syntax:
 for ( parameter : arrayName )
statement
 where parameter has a type and an identifier, and arrayName is the array
through which to iterate.
 Parameter type must be consistent with the type of the elements in
the array.
 Can be used only to obtain array elements — it cannot be
used to modify elements.
 Can be used in place of the counter-controlled for statement
whenever code looping through an array
60
Acknowledgement
 Slides on Merge Sort is adapted from slides by Douglas
Wilhelm Harder, Mmath
([email protected])
 This presentation uses materials from
 Head First Java
 Java How to Program, slides set
61