Upload
arleen-obrien
View
217
Download
2
Embed Size (px)
Citation preview
Chapter 1
Introduction to Java
Chapter 1
2
History of Java
• Java– Originally for _______________ consumer-
electronic devices
– Then used for creating Web pages with _______________
– Now also used to:• Develop large-scale enterprise applications
• Enhance WWW ___________ functionality
• Provide applications for consumer devices (cell phones, etc.)
3
Java Class Libraries
• Classes– Include methods that ________________
• Return information after task completion
– Used to build Java programs
• Java provides class ________________– Known as Java APIs
(A_______________ P________________ I ________________
4
FORTRAN, COBOL, Pascal and Ada
• ___________________– FORmula TRANslator
• COBOL– COmmon ______________ Oriented Language
• Pascal– ______________ programming
• Ada– Multitasking
5
BASIC, Visual Basic, Visual C++, C# and .NET
• BASIC– Beginner’s All-Purpose ___________ ________ Code
• .NET– .NET platform
• Visual Basic .NET– Based on BASIC
• _______________ C++– Based on C++
• C#– Based on C++ and ___________________
6
Typical Java Development Environment
• Java programs normally undergo five phases– Edit
• Programmer __________ program (and stores program on disk)
– Compile• Compiler creates bytecodes from program
– __________________• Class loader stores bytecodes in memory
– Verify• _______________ Verifier confirms bytecodes do not violate
security restrictions
– Execute• JVM translates bytecodes into machine language
7
Fig. 1.1 Typical Java development environment.
8
Creating a Program with JCreator
• Click on the JCreator ____________
• IDE windowappears
9
Creating a Program with JCreator
• Click on File, New, then P______________
• Project Wizard appears– Choose Java ________________ template
10
Creating a Program with JCreator
• Give the project a _________________
• Then click Next
11
Creating a Program with JCreator
• You will want the JDK version 1.5
At this point you can click on FinishAt this point you can click on Finish
12
Creating a Program with JCreator
• Now we create our class (the program) with File, New, and Class
13
Creating a Program with JCreator
• The wizard creates a __________________.
• Now complete the program with the required commands.
14
Creating a Program with JCreator
• Run the compiler with Build, and CompileFile
___________________ shows in bottom pane. This is where compiler error messages will be displayed.
15
Creating a Program with JCreator
• To run the compiled program click on Build, and _________________
• Program runs in separate window
16
Chapter 2
Introductionto Java Applications
17
2.1 Introduction
• Java application programming– Display ___________________________
– Obtain information from the user
– ____________________ calculations
– Decision-making fundamentals
18
2.2 First Program in Java: Printing a Line of Text
• Application– Executes when you use the java command to
launch the J_______V_______ M________Sample program
– Displays a line of text
– Illustrates several important Java language features
19
2.2 First Program in Java: Printing a Line of Text (Cont.)
– Comments start with: ____________• Comments ignored during program execution• Document and describe code• Provides code readability
– Traditional comments: ________________/* This is a traditional comment. It can be split over many lines */
– Another line of comments– Note: line numbers not part of program, added for
reference
1 // Fig. 2.1: Welcome1.java
2 // Text-printing program.
20
2.2 First Program in Java: Printing a Line of Text (Cont.)
– Blank line• Makes program more __________________• Blank lines, spaces, and tabs are white-space characters
– _______________________ by compiler
– Begins class declaration for class Welcome1• Every Java program has at least one ________________• Keyword: words reserved for use by Java
– class keyword followed by class name• Naming classes: ______________________________
– SampleClassName
3
4 public class Welcome1
21
2.2 First Program in Java: Printing a Line of Text (Cont.)
– Java identifier• Series of characters consisting of letters, digits,
underscores ( _ ) and dollar signs ( $ )• Does not begin with a ____________, has no _______• Examples: Welcome1, $value, _value, button7
– 7button is invalid• Java is case sensitive (capitalization matters)
– a1 and A1 are different
– In chapters 2 to 7, use public class• Certain details not important now • Mimic certain features, discussions later
4 public class Welcome1
22
2.2 First Program in Java: Printing a Line of Text (Cont.)
– Saving files• File name must be class name with ._______ extension
• Welcome1.java
– Left brace {• Begins _________________ of every class
• Right brace ends declarations (line 13)
4 public class Welcome1
5 {
23
2.2 First Program in Java: Printing a Line of Text (Cont.)
– Part of every Java application• Applications begin executing at main
– Parentheses indicate main is a ______________ (Ch. 3 and 6)– Java applications contain one or more methods
• Exactly one method must be called _________________
– Methods can perform tasks and return information• ______________ means main returns no information• For now, mimic main's first line
– Left brace begins body of method declaration• Ended by right brace } (line 11)
7 public static void main( String args[] )
8 {
24
2.2 First Program in Java: Printing a Line of Text (Cont.)
– Instructs computer to perform an action• Prints string of characters
– String - series characters inside ___________ quotes• White-spaces __________ are not ignored by compiler
– System.out• Standard output object• Print to command window (i.e., MS-DOS prompt)
– Method System.out.println • Displays line of text
– This line known as a statement• Statements must end with __________________
9 System.out.println( "Welcome to Java Programming!" );
25
2.2 First Program in Java: Printing a Line of Text (Cont.)
– Ends method declaration
– Ends class declaration
– Can add __________________ to keep track of ending braces
11 } // end method main
13 } // end class Welcome1
26
2.3 Modifying Our First Java Program
• Modifying programs– Welcome2.java (Fig. 2.3) produces same output as Welcome1.java (Fig. 2.1)
– Using different code
– Line 9 displays “Welcome to ” with cursor remaining on printed line
– Line 10 displays “Java Programming! ” _____________ with cursor on next line
9 System.out.print( "Welcome to " ); 10 System.out.println( "Java Programming!" );
27
2.3 Modifying Our First Java Program (Cont.)
• Escape characters– Backslash ( \ )
– Indicates _____________________ be output
• ____________________ characters (\n)– Interpreted as “special characters” by methods System.out.print and System.out.println
– Indicates cursor should be at the beginning of the next line
– Welcome3.java (Fig. 2.4)
– Line breaks at \n9 System.out.println( "Welcome\nto\nJava\nProgramming!" );
28
Fig. 2.5 | Some common escape sequences.
29
2.4 Displaying Text with printf
•System.out.printf– New feature of J2SE 5.0
– Displays _________________ data
– Format string• Fixed text
• Format ____________ – placeholder for a value
– Format specifier %s – placeholder for a _______
– Other format specifiers
9 System.out.printf( "%s\n%s\n", 10 "Welcome to", "Java Programming!" );
30
Formatting Output with printf
•printf– Precise output formatting
• Conversion specifications: flags, field widths, precisions, etc.
– Can perform • _________________________• aligning columns• right/left _______________________• inserting literal characters• exponential format• octal and hexadecimal format• fixed width and ____________________• date and time format
31
Formatting Output with printf (Cont.)
• Format String– Describe the output format
– Consist of fixed text and format specifier
• Format specifier– Placeholder for a value
– Specify the ________________ of data to output
– Begins with a ________________ and is followed by a conversion character
• E.g., %s, %d
– Optional formatting information• Argument index, flags, field width, precision
• Specified between % and conversion character
32
Printing Integers
• Integer– Whole number (no decimal point): 25, 0, -9– Positive, negative, or zero– Only __________________ prints by default (later we shall
change this)
• Format– printf( format-string, argument-list );– format-string
• Describe the output format
– argument-list• Contain the ____________ corresponding to each format
specifier
33
Integer conversion characters.
• View demonstration program Fig. 28.3– Note output of positive, negative numbers
– Note octal (base 8) and hexadecimal (base 16) options
34
Printing Floating-Point Numbers
• Floating Point Numbers– Have a ______________ point (33.5)
– Computerized scientific notation (exponential notation)• 150.4582 is 1.504582 x 10² in scientific
• 150.4582 is 1.504582e+02 in exponential (e stands for exponent)
• use e or E
– f – print _________________ with at least one digit to left of decimal
– g (or G) - prints in f or e (E) • Use exponential if the magnitude is less than 10-3, or
greater than or equal to 107
35
Floating-point conversion characters.
• View program using printf for floating point numbers, Figure 28.4
Conversion character Description
e or E Display a floating-point value in exponential notation. When conversion character E is used, the output is displayed in uppercase letters.
F Display a floating-point value in decimal format.
g or G Display a floating-point value in either the floating-point format f or the exponential format e based on the magnitude of the value. If the magnitude is less than 10–3, or greater than or equal to 107, the floating-point value is printed with e (or E). Otherwise, the value is printed in format f. When conversion character G is used, the output is displayed in uppercase letters.
a or A Display a floating-point number in hexadecimal format. When conversion character A is used, the output is displayed in uppercase letters.
Conversion character Description
e or E Display a floating-point value in exponential notation. When conversion character E is used, the output is displayed in uppercase letters.
F Display a floating-point value in decimal format.
g or G Display a floating-point value in either the floating-point format f or the exponential format e based on the magnitude of the value. If the magnitude is less than 10–3, or greater than or equal to 107, the floating-point value is printed with e (or E). Otherwise, the value is printed in format f. When conversion character G is used, the output is displayed in uppercase letters.
a or A Display a floating-point number in hexadecimal format. When conversion character A is used, the output is displayed in uppercase letters.
36
Printing Strings and Characters
• Conversion character c and C– Require ________________
– C displays the output in uppercase letters
• Conversion character s and S– String
– Object• Implicitly use object’s _______________ method
– S displays the output in uppercase letters
• View program demonstrating character conversion with printf, Fig. 28.5
37
Printing with Field Widths and Precisions
• Field width– Size of field in which data is printed
– If width larger than data, default __________ justified• If field width too small, ______________ to fit data
• Minus sign uses one character position in field
– Integer width inserted between % and conversion specifier• E.g., %4d – field width of 4
– Can be used with all format specifiers except the _________ separator (%n)
• View program demonstrating field width, Fig. 28.12
38
Printing with Field Widths and Precisions
• Precision– Meaning varies depending on data type– Floating point
• Number of digits to appear ____________ decimal (e or E and f)
• Maximum number of significant digits (g or G)
– Strings• ____________ number of characters to be written from string
– Format• Use a dot (.) then precision number after %
e.g., %.3f
• View program demonstrating precision, Fig. 28.13
39
Printing with Field Widths and Precisions
• Field width and precision– Can both be specified
• %width.precision
%5.3f
– ________________ field width – left justified
– Positive field width – right justified
– Precision must be _________________• Example:
printf( "%9.3f", 123.456789 );
40
2.5 Another Java Application: Adding Integers
• Program Fig. 2.7 to do keyboard input– Use ___________ to read two integers from user
– Use printf to display sum of the two values
– Use packages
41
2.5 Another Java Application: Adding Integers (Cont.)
– import declarations • Used by _________________ to identify and locate classes used
in Java programs
• Tells compiler to load class Scanner from java.util package
– Begins public class Addition• Recall that file name must be Addition.____________
– Lines 8-9: begins main
3 import java.util.Scanner; // program uses class Scanner
5 public class Addition 6 {
42
2.5 Another Java Application: Adding Integers (Cont.)
– Variable Declaration Statement– Variables
• Location in memory that stores a _____________– Declare with name and type before use
• Input is of type Scanner – Enables a program to read data for use
• Variable name: any valid identifier
– Declarations end with semicolons ;– Initialize variable in its ________________
• Equal sign• Standard input object
– System.in
10 // create Scanner to obtain input from command window11 Scanner input = new Scanner( System.in );
43
2.5 Another Java Application: Adding Integers (Cont.)
– Declare variable number1, number2 and sum of type int• int holds integer values (whole numbers): i.e., 0, -4, 97
• Types ___________ and double can hold decimal numbers
• Type char can hold a __________ character: i.e., x, $, \n, 7
• int, float, double and char are _____________ types
– Can add comments to describe purpose of variables
– Can declare ______________ variables of the same type in one declaration
– Use comma-separated list
13 int number1; // first number to add14 int number2; // second number to add15 int sum; // second number to add
int number1, // first number to add number2, // second number to add sum; // second number to add
44
2.5 Another Java Application: Adding Integers (Cont.)
– Message called a ____________ - directs user to perform an action
– Package java.lang
– Result of call to nextInt given to number1 using assignment operator =
• Assignment statement• = binary operator - takes ____________ operands
– Expression on right evaluated and assigned to variable on left
• Read as: number1 __________________ input.nextInt()
17 System.out.print( "Enter first integer: " ); // prompt
18 number1 = input.nextInt(); // read first number from user
45
2.5 Another Java Application: Adding Integers (Cont.)
– Similar to previous statement• Prompts the user to input the second integer
– Similar to previous statement• Assign variable number2 to second integer input
– Assignment statement• ___________ of number1 and number2 (right hand side)• Uses assignment operator = to assign result to variable sum• Read as: sum gets the value of number1 + number2• number1 and number2 are _________________
20 System.out.print( "Enter second integer: " ); // prompt
21 number2 = input.nextInt(); // read second number from user
23 sum = number1 + number2; // add numbers
46
2.5 Another Java Application: Adding Integers (Cont.)
– Use System.out.printf to display results
– _______________ specifier %d• Placeholder for an int value
– Calculations can also be performed inside _______________
– Parentheses around the expression number1 + number2 are not required
25 System.out.printf( "Sum is %d\n: " , sum ); // display sum
System.out.printf( "Sum is %d\n: " , ( number1 + number2 ) );
47
2.6 Memory Concepts
• Variables
– Every variable has a name, a ___________, a _______________ and a value
• Name corresponds to location in memory
– When new value is placed into a variable, replaces (and ______________) previous value
– ________________ variables from memory does not change them
48
2.7 Arithmetic
• Arithmetic calculations used in most programs
– Usage • * for multiplication
• / for division
• % for ___________________
• +, -
– Integer division _____________ remainder7 / 5 evaluates to 1
– Remainder operator % returns the remainder 7 % 5 evaluates to 2
49
Fig. 2.11 | Arithmetic operators.
50
2.7 Arithmetic (Cont.)
• Operator precedence – Some arithmetic operators act before others (i.e.,
multiplication before addition)• Use ___________________ when needed
– Example: Find the average of three variables a, b and c
• Do not use: a + b + c / 3
• Use: ( a + b + c ) / 3
51
Fig. 2.12 | Precedence of arithmetic operators.
Operator(s) Operation(s) Order of evaluation (precedence)
*
/
%
Multiplication
Division
Remainder
Evaluated first. If there are several operators of this type, they are evaluated from left to right.
+
-
Addition
Subtraction
Evaluated next. If there are several operators of this type, they are evaluated from left to right.
52
Operator Precedence Chart
Hierarchy of Java operators with the highest precedence shown first.• Expressions inside parentheses are evaluated first; nested parentheses are evaluated from the innermost parentheses to the outer. • Operators in the same row in the chart have equal precedence.
Operator Type Order of Evaluation
( ) [ ] .
ParenthesesArray subscriptMember access
left to right
++ -- Prefix increment, decrement
right to left
++ -- - Postfix increment, decrementUnary minus
right to left
* / % Multiplicative left to right
+ - Additive left to right
< > <= >= Relational left to right
== != Equality left to right
&& And left to right
|| Or left to right
? : Conditional right to left
= += -= *= /= %= Assignment right to left
53
View Flash Presentations
• Creating a workspace, project, and application
• Writing, compiling, running an application
3
• Introduction to Classes and Objects
55
3.2 Classes, Objects, Methods and Instance Variables
• Class provides one or more ______________• Method represents task in a program
– Describes the _____________ that actually perform its tasks
– Hides from its user the complex tasks that it performs
– Method _____________ tells method to perform its task
• Classes contain one or more attributes– Specified by instance variables– Carried with the object as it is used
56
3.3 Declaring a Class with a Method and Instantiating an Object of a Class
• Each class declaration that begins with keyword public
– must be stored in a _______________
– that has the same ___________ as the class and
– ends with the .__________ file-name extension.
57
Class GradeBook• keyword public is an ___________ modifier
• Class declarations include:
– Access modifier
– Keyword class
– Pair of left and right braces
• Method declarations
– Keyword ____________ indicates method is available to public
– Keyword void indicates _______________
– Access modifier, return type, name of method and parentheses comprise method header
58
Class GradeBookTest
• Java is ______________________
– Programmers can create new classes
– Test program the GradeBook class
• Class instance creation expression
– Keyword _____________
– Then name of class to create and parentheses
• Calling a method
– Object _______________, then dot separator (.)
– Then method name and parentheses
59
Compiling an Application with Multiple Classes
• Note we have two classes– Gradebook
– GradeBookTest
• Compiling multiple classes– Use the compile command in the IDE
– Compile each file ___________ (or use Compile Project command)
• Requires a ____________ in some IDE’s
60
3.4 Declaring a Method with a Parameter
• Method ___________________
– Additional information passed to a method
– Supplied in the method call with _________
•Scanner methods– _______________ reads next line of input
– next reads next ___________ of input
• See new improved GradeBook class, Figure 3.4 and GradeBookTest program, Figure 3.5
61
Outline
GradeBook.java
62
Notes on Import Declarations
•__________________ is implicitly imported into every program
• Default package
– Contains classes compiled in the ________________
– Implicitly imported into source code of other files in directory
• Packages unnecessary if fully-qualified names are used
63
3.5 Instance Variables, set Methods and get Methods
• Variables declared in the body of method
– Called _______________ variables
– Can only be used within that method
• Variables declared in a class declaration
– Called fields or _______________ variables
– Each object of the class has a separate instance of the variable
• Note set and get methods
64
Access Modifiers public and private
• private keyword
– Used for most instance variables
– private variables and methods are accessible only to methods of the ____________________________________
– Declaring instance variables private is known as data ____________________
• Return type
– Indicates item returned by method
– Declared in method header
65
GradeBookTest Class That Demonstrates Class GradeBook
• Default initial value– Provided for all fields not initialized
– Equal to _____________ for Strings
• Note private instance variables
– Cannot be accessed directly by ____________ of the object
– Use set methods to ____________ the value
– Use ______________ methods to retrieve the value
66
Primitive Types vs. Reference Types
• Types in Java– Primitive
•boolean, byte, char, short, _______, long, float, _______________
– Reference (sometimes called ____________ types)• Objects
• Default value of null• Used to invoke an object’s methods
67
3.7 Initializing Objects with Constructors
• Constructors
– _____________ an object of a class
– Java requires a constructor for every class
– Java will provide a default no-argument constructor if none is provided
• Called when keyword _________ is followed by the class name and parentheses
• Constructors which “incoming” initial value
68
AccountTest Class to use Class Account
• Note use of Scanner object
– Input floating point number
• Note use of ____________________ %f– Used to output floating-point numbers
– Place a decimal and a number between the percent sign and the f to mandate a ________________
69
Displaying Text in a Dialog Box
• Windows and dialog boxes– Many Java applications use these to display
output
– ________________ provides prepackaged dialog boxes called message dialogs
• Program to use dialog box
70
Displaying Text in a Dialog Box
• Package javax.swing– Contains classes to help create
_______________________________ (GUIs)
– Contains class JOptionPane• Declares static method showMessageDialog for displaying
a message dialog
71
Entering Text in a Dialog Box
• Input dialog– Allows user to input information
– Created using method _____________________ from class JOptionPane
72
Methods
Chapter 6
73
Program Modules in Java
• What we call "functions" in C++ are called "________________" in Java
• Purpose– Reuse code– ______________________ the program
• This can be done by putting the code in a method– Various objects in a program can invoke the same
method
74
Program Modules
• _______________ and ______________ technique
– Construct a large program from smaller pieces (or modules)
– Can be accomplished using methods
• ______________ methods can be called without the need for an object of the class
75
static Methods•static method (or class method)
– Applies to the class as a whole instead of a specific object of the class
– Call a static method by using the method call:_____________.methodName( arguments )
– All methods of the __________ class are static• example: Math.sqrt( 900.0 )
76
static Methods
• Method main–main is declared static so it can be invoked
_____________________________ of the class containing main
– Any class can contain a main method– The JVM invokes the main method belonging to
the class specified by the first command-line argument to the java command
77
Predefined Methods
• The Math class
• These methods are called by– The _____________ of the class– The dot . operator– The name of the ______________
• Example:double y = Math.cos(x);
78
Constants
• Constants– Keyword ___________________– Cannot be changed after initialization
• static fields (or class variables)– Are fields where one copy of the variable is
__________________ among all objects of the class
• Math.PI and Math.E are final static fields of the Math class
79
Method Declaration Syntax
modifiers returnType methodName (parameterDeclaration)
{ statements}• ___________ : describers (public, private, etc.)• returnType : type of value returned by method, or
____________ if it does not return a value• methodName : identifier that names the method• parameterDeclaration : list of parameters, separated
by _______________________• statements : define the behavior of the method
80
Method Declaration
• View declaration of methods in a class for finding maximums, Fig. 6.3– Note method for input, call of method ______________
– Note method for actual determining of maximum
• View test program, Fig 6.4– Note declaration of instance of new class– Note call of class methods
81
Alternative Method Declaration
• View alternative solution
• Declare methods in the __________________
• Have them follow method main()– Although they can be ____________ in the class
• Note they must be static
82
Declaring and Using Methods
• Three ways to call a method:– Use a method name by itself to call ____________
of the same class– Use a containing a reference to an object,
followed by a dot (.) and the method name to call a method of the referenced object
– Use the class name and a dot (.) to call a _______ method of a class
– Note: static methods cannot call non-static methods of the same class directly
83
Declaring and Using Methods
• Three ways to return control to the calling statement:
– If method does not return a result:• Program flow reaches the _________________ right
brace or …• Program executes the statement _____________;
– If method does return a result:• Program executes the statement
__________ expression;• expression is first evaluated and then its value is returned
to the caller
84
Argument Promotion
• Coercion of arguments
– _______________ arguments to appropriate type to pass to method System.out.println( Math.sqrt( 4 ) );
– Evaluates Math.sqrt( 4 )
– Then evaluates System.out.println()
85
Argument Promotion
• Promotion rules
– Specify how to convert types without data loss
Type Valid promotions
double None float double long float or double int long, float or double char int, long, float or double short int, long, float or double (but not char) byte short, int, long, float or double (but not char) boolean None (boolean values are not considered to be numbers in Java)
Type Valid promotions
double None float double long float or double int long, float or double char int, long, float or double short int, long, float or double (but not char) byte short, int, long, float or double (but not char) boolean None (boolean values are not considered to be numbers in Java)
86
Java API Packages
• _______________ classes grouped into categories of related classes– Called packages
• Called the Java Application Programming Interface (API)
• Note the often used API packages
87
Random-Number Generation
• Consider the random method in the Math class– Generates a random double 0 <= n < ______– The number can be manipulated and cast as an ______ to get desired range
– For the roll of a die1 + (int) (Math.random() * 6)
• Note Figure 6.7 and Figure 6.8
88
Game of Chance
Rules for "Craps"• Roll dice first time
– If sum equals 7 or 11, the player _________– If sum equals ____________, the player loses– Any other sum (4, 5, 6, 8, 9, 10) is that player’s
point• Keep rolling dice until…
– Sum matches player point• Player wins
– Sum equals _______• Player loses
89
Game of Chance
• Note the adapted version of Figure 6.9– An application
• Note– _____________ class variables– Public methods– The __________________ function requires Character. (a non instantiating class)
90
Scope of Declarations
• Scope of a ______________ is body of method where declaration appears
• Scope of local variable is from point of declaration to end of ________________
• Scope of label in labeled break/continue is statement enclosed by labeled statement
• Scope of local-variable in initialization of for( ) is for _______________________ and rest of header
• Scope of method or field of class is body of ____________
91
Shadowing
• A field is shadowed (or hidden) if a _____________ variable or parameter has the same name as the field
• This lasts until the local variable or parameter goes out of ______________
• View example– Figure 6.11 Variables with different scopes– Figure 6.12 Test program
92
Method Overloading
• Multiple methods with _____________ can be declared in same class
• Methods must have different ___________– Different numbers, types, order of parameters
• Example– Figure 6.13 Overload example class– Figure 6.14 Overload test program
93
Recursion
Recursive method• Calls ___________ (directly or indirectly)
through another method• Method knows how to solve only a ______
case• Method divides problem
– Base case– Simpler problem – Method now divides simpler
problem until solvable
• Recursive call• Recursive step
94
2! = 2 * 1 = 2 is returned
(a) Sequence of recursive calls.
(b) Values returned from each
recursive call.
Final value = 120
5! = 5 * 24 = 120 is returned
4! = 4 * 6 = 24 is returned
3! = 3 * 2 = 6 is returned
1 returned
5!
1
4 * 3!
3 * 2!
2 * 1!
5!
1
4 * 3!
3 * 2!
2 * 1!
5 * 4! 5 * 4!
Recursive Evaluation of 5!
95
Recursive Factorial Program
• Function factorial() in Figure 6.15
• Note– Initial call to factorial()– ____________ or base case– Recursive call
96
Recursive Fibonacci Program
• Consider function from program public long fibonacci( long n ) { // base case if ( n == 0 || n == 1 ) return n; // recursive step else return fibonacci( n - 1 ) + fibonacci( n - 2 ); } // end method fibonacci
• Note why this would be extremely _________
97
Recursive Fibonacci Program
return
return
+
+ return 1
return 1
fibonacci( 2 ) fibonacci( 1 )
fibonacci( 1 ) fibonacci( 0 )
return 0
fibonacci( 3 )
98
Recursion vs. Iteration
• Both the recursive functions shown can be done with either for or while loops
• In fact they are done more efficiently ____________
• Recursion has overhead– Processor time– Memory space
• General rule: If it can be done either recursively or iteratively … choose __________
99
Arrays
Chapter 7
100
Declaring and Creating Arrays
• Recall that an array is a collection of elements all of the _____________
• Array objects in Java must be created with the key word _______________
• Syntaxint c[] = new int [12];
• Results:– 12 integer locations are allocated– They are _____________________
(null for reference variables, false for boolean)
101
Using Arrays
• View example Figure 7.2
• Note– Declaration of the array– Allocation of memory with new– Initialization of array elements– Use of array attribute (_______________)– Printing of array contents
102
The Array Initializer• A comma separated list of expressions
– The ______________ list– Enclosed in _________________
• View the Example– Note again, how the array knows its own _______
for (int count = 0 ; count < array.length ; count++) . . .
103
Processing Elements of An Array
• Finding and using the arithmetic mean– __________________ the array, create– Read in values, ___________________– Declare a summation variable, initialize – ______________ the array, calculate average– _______________ the array– Print results, accessing the array
• See sample program
104
Histogram Program
• Use the value in the array to– Print the value– Print a string of asterisks for __________________
of size of the value
• View Figure 7.6,
105
Using Array Elements as Counters
• Recall program which tested random number generator (Figure 6.8)– Used 6 different variables– Used switch statement to increment– At the time we noted the ________________
• Consider a new version of the program– Uses _______________ to total the number of rolls
of each number 1 – 6– No ___________ statement needed
• View Figure 7.7
106
Enhanced for Statement
• Enhanced for statement– New feature of J2SE 5.0– Allows iterates through elements of an array or a
collection _______________________– Syntax
for ( parameter : arrayName )statement
– View example, Figure 7.12
107
References and Reference Parameters
• In Java, primitive-type variables are always passed by _________– Incoming data only
• Objects are not passed to methods– __________ to objects are passed– The reference is passed by value
• With a reference to the object the method can _____________ the object directly
108
References and Reference Parameters
• Passing arrays by reference– Improves _______________– Saves time
• ________________ of large array not required
– Saves _______________• Use memory already occupied by array• No new memory allocation required
– View example program, Figure 7.13
109
Using Arrays
• Sorting Arrays– Recall previous example
• Searching Arrays– ________________ search (see example)
• Step through array until desired value located
– Binary search• Array must be _________________• Look in middle, then above or below
– Look in middle of sub-section then above or below– Etc.
110
Multidimensional Arrays
• Java does not support ________________ arrays directly
• Does allow declaration of arrays whose elements are ______________!
int b[][];b = new int[ 2 ][ ]; // allocate rowsb[ 0 ] = new int[ 5 ]; // allocate columns for row 0b[ 1 ] = new int[ 3 ]; // allocate columns for row 1
111
Fig. 7.16 | Two-dimensional array with three
rows and four columns.
Multidimensional Arrays
112
Creating Two-dimensional Arrays
– Can be created dynamically– 3-by-4 array
int b[][]; b = new int[ 3 ][ 4 ];
– Rows can have different number of ____________ int b[][]; b = new int[ 2 ][ ]; // create 2 rows b[ 0 ] = new int[ 5 ]; // create 5 columns for row 0 b[ 1 ] = new int[ 3 ];
// create 3 columns for row
113
Variable-Length Argument Lists
• New feature in J2SE 5.0
• ___________________ number of arguments
• Use ellipsis (…) in method’s parameter list– Can occur _______________ in parameter list– Must be placed at the __________ of parameter list
• Array whose elements are all of the same type
• View example, Fig. 7.20
114
Using Command-Line Arguments
• Pass arguments from the command line– String args[]
• Appear after the _____________ in the java command– java MyClass a b
• _________________ of arguments passed in from command line– args.length
• First command-line argument– args[ 0 ]
115
Object Based Programming
Chapter 8
116
Contrast
• ____________________ Languages– Action oriented– Concentrate on writing ________________– Data supports the actions
• Object Oriented Languages– Concentrate on creating reference types– Look for ____________ which indicate classes
• Fields are data members• Methods support manipulation of the objects
117
Find the Objects … the Verbs
In this game, what are nouns that are potential classes?
In this game, what are nouns that are potential classes?
What are verbs that represent things that the
objects do?
What are verbs that represent things that the
objects do?
118
Abstract Data Types (ADTs)
• Classes in Java make creation of ADTs easier– Implementation details ____________ from users of
the class– Client code not dependent on ________________
• Example of a class– Figure 8.1 – Time class – keeps track of time in 24 hour format
119
Declaring Classes
• Usually data fields are specified as __________
• ______________ are declared as public
• Any class member (data or method) which does not need to be accessed outside the class should be private
• It ____________________________ which comes first, data fields or methods– The author prefers data fields first
120
Constructors
• Methods which have the same name as the _____________________
• Included in a class to ensure that instance variables contain __________________ when objects are created
• The constructor is called when a class object is created with the __________________
• Note:– Do not have the constructor return a _________
121
Using Classes
• View Figure 8.2• Note
– Creation of a time object with new– Call of the constructor– Use of public functions to ____________ the private data
values– Use of toString functions– Use of DecimalFormat class
• Advantages of classes– Simplifies client __________________ of classes– Reduces number of _______________________
122
Class Scope
• Variables and methods belong to the class's scope
• _________________ the class's scope– All class members are available, accessible
• Outside the class's scope– Client code that uses the class– Only _____________ members are available,
accessible
• Access modifiers public and private control this availability
123
Controlling Access to Members
• The following would not be allowed – why?
• The data members are ___________.
public class TimeTest2 { public static void main( String args[] ) { Time1 t = new Time1(); t.hour = 7; }}
public class TimeTest2 { public static void main( String args[] ) { Time1 t = new Time1(); t.hour = 7; }}
124
Using the this Reference
• Every object can access a reference to ______– Use the keyword this
• If a method has a ________ variable with same name as _________ variable, use the this to access the class variable
• Explicit use of this can increase program _____________ for human readers
• Note example, Figure 8.4
125
Using Overloaded Constructors
• ________________ constructors for the same class are allowed
• The _____________ of the constructors must be different– Different numbers and/or types of parameters
• See example in Figure 8.5 and 8.6
126
Using Set and Get Methods
• Private data fields manipulated only by provided _________________________– Some methods used to _________ the data values– Others used to get the values
• Return the value directly• Print the value
• Note: this is not the same as making the data values __________________– The set methods are written to ensure valid data
values
127
Composition
• A class can have references to __________________________ as members
• Example:– An alarm clock class contains a Time object as one
of its members– Employee class has Date object as one of its
members– See
• Date Class, Figure 8.7• Employee Class Figure 8.8• Employee Test program Figure 8.9
128
Enumerations – enum types
• Declared with an ___________ declaration
• A comma-separated list of enum constants
• Declares an enum class with the following restrictions:– enum types are implicitly _____________– enum constants are implicitly ______________– Attempting to create an object of an enum type with new is a compilation error
129
Enumerations – enum types•enum constants can be used anywhere
_____________ can•enum constructor
– Like class constructors, can specify ____________ and be overloaded
• See example, Figure 8.10
• Note test program, Figure 8.11
130
Enumerations – enum types•static method values
– Generated by the __________ for every enum– Returns an array of the enum’s constants in the
order in which they were declared
•static method _________ of class EnumSet– Takes two parameters, the first and last enum
constants in the desired range– Returns an EnumSet containing the constants in
that range, ________________– An enhanced _________ statement can iterate
over an EnumSet as it can over an array
131
Garbage Collection
• Garbage collection– JVM marks an object for garbage collection when there are
no more _________________ to that object– JVM’s garbage collector will retrieve those objects memory
so it can be used for other objects– See lines 27 – 32 of Figure 8.13
• _________________ method– All classes in Java have the finalize method
• Inherited from the Object class
– finalize is called by the ____________________ when it performs termination housekeeping
– finalize takes no parameters and has no return type _____________
132
static Class Members
• Normally each class object has its own copy of the instance variables
• Possible to specify a variable that is __________ by all existing objects of the class– Called a static variable– Also called a __________ variable – class wide information
• Also possible to have a static ______________– Can be called even if no object of the class has been
instantiated– Use class name, then dot, then static method name
• Note examples in Fig. 8.12, test pgm Fig. 8.13
133
static Class Members•String objects are _________________
– String concatenation operations actually result in the creation of a ___________ String object
•static methods ________________ non-static class members
– Also cannot use the ____________ reference
134
static Class Members
• static method _________ of class System– Indicates that the garbage collector should make a
best-effort attempt to reclaim objects eligible for garbage collection
– It is possible that _______ objects or only a _________ of eligible objects will be collected
• Note example call in Fig. 8.13
135
static Import
• Recall static fields and methods of class Math
• J2SE 5.0 enables importing static members as if ______________________ where used
• Note Figure 8.14import static java.lang.Math.*
136
Final Instance Variables
• Principle of least privilege– Code should have only the privilege and access it
needs to ________________, but no more
• final instance variables– Keyword ______________
• Specifies that a variable is ______ modifiable (is a constant)
– final instance variables can be initialized at their _______________________
• If they are not initialized in their declarations, they must be initialized in all constructors – Fig. 8.15
137
Software Reusability
• Many classes exist in the Java API
• Avoid "__________________"– Study capabilities of Java API– If it has a class that fits your needs, use it rather
than creating your own
138
Data Abstraction & Encapsulation
• Information hiding– Classes hide details of _______________ from
client
• Example:– Stack can be implemented with array or with linked
list– Client program which depends on one
implementation will have problems if new version with different implementation comes out
• Only use the ________________ provided
139
Object Oriented Programming: Inheritance
Chapter 9
140
Introduction
• Software Reusability– saves __________ in program development– encourages use of proven, ____________ code– reduces problems
• Write programs in ____________ fashion
• Enables software designers to deal with complexity of modern software
141
Introduction
• When creating a new class …– designate that class to ___________ data
members, functions of previously defined superclass
– result is a ___________________
• Subclass ____________ new data members and functions
• ________________ and refine existing members
142
Base Classes & Derived Classes
• Superclass is more ______________– student, shape, loan
• ________________ is more specific– grad student, undergrad– circle, triangle, rectangle– carloan, home improvement, mortgage
• Some languages talk of– ______________ class (Superclass)– Derived class (Subclass)
143
Superclass and Subclass
• Inheritance produces _________ like structures
144
Superclass and Subclass
• Inheritance produces tree like structures
145
Design Tip
• Important link between subclass and superclass– The “_____________” relationship
• Examples– A checking account IS-A banking account– A savings account IS NOT a checking account
• If there is no IS-A relationship, do not use __________________
146
protected Members
•protected access– ______________ level of protection between public and private
– protected members accessible by• superclass members• _________________ members• Class members in the same package
– Subclass access to superclass member• Keyword _____________ and a dot (.)
147
Comments on Private vs. Protected
• Use protected when – Superclass should provide a _____________ only
to its subclasses– Should not provide service to other clients
• Use private so that– ________________ implementation can change
without affecting subclass implementations
• Author advocates ______________ protected– Instead provide set and get methods to access
private data items (see Figures 9.12, 9.13 in text)
148
Relationship between Superclasses and Subclasses
• Superclass and subclass relationship– Example: CommissionEmployee/BasePlusCommissionEmployee inheritance hierarchy•CommissionEmployee
– First name, last name, SSN, commission rate, gross sale amount
•BasePlusCommissionEmployee– First name, last name, SSN, commission rate, gross sale
amount– Base salary
149
Creating and Using a CommissionEmployee Class
• Class CommissionEmployee– Extends class Object
• ______________________ extends• Every class in Java extends an existing class
– Except Object
• Every class inherits __________________ methods
• New class _________________ extends Object– If it does not extend another class
150
Creating and Using a CommissionEmployee Class
• Class CommissionEmployee– Extends class Object
• Keyword extends• Every class in Java extends an existing class
– Except Object
• Every class inherits Object’s methods• New class implicitly extends Object
– If it does not extend another class
• View class Figure 9.4
• View test program, Figure 9.5
151
Creating a BasePlusCommissionEmployee
Class without Using Inheritance• Class BasePlusCommissionEmployee
– Implicitly extends Object– Much of the code is similar to
CommissionEmployee•private ____________ variables•public methods• constructor
– ____________•private instance variable baseSalary• Methods setBaseSalary and getBaseSalary
152
Creating a CommissionEmployee-BasePlusCommiionEmployee Inheritance
Hierarchy
• Class BasePlusCommissionEmployee2– Extends class CommissionEmployee– Is a CommissionEmployee– Has ___________ variable baseSalary– _____________ public and protected
members– _______________ not inherited
• Note these points plus invalid references, Figure 9.8 – note compiler error messages
153
Using protected Instance Variables
• Use protected instance variables– Enable class BasePlusCommissionEmployee to
__________________ superclass instance variables
– Superclass’s protected members are inherited by all subclases of that superclass
• View version that now works, Figure 9.10
• Test program, Figure 9.11
154
Using protected Instance VariablesAdvantages
• Subclasses can _________________ values directly
• Slight __________________ in performance– Avoid set/get method call overhead
155
Using protected Instance VariablesDisadvantages
• No ________________ checking– subclass can assign illegal value
• Implementation dependent– subclass methods more likely __________ on
superclass implementation– superclass implementation changes may result in
subclass ___________________• Fragile (brittle) software
156
Reexamine Hierarchy
• Use the best software engineering practice– Declare instance variables as private– Provide public _____________________ methods– Use _____________ method to obtain values of
instance variables
• View new version of CommissionEmployee, Figure 9.12
• New version of BasePlusCommissiionEmployee, Figure 9.13
• Test program, Figure 9.14
157
Instantiating Subclass ObjectChain Of Constructor Calls
• Subclass constructor invokes superclass constructor– __________ or _________________
• Base of inheritance hierarchy– Last constructor called in chain is _________________
constructor– _______________ subclass constructor’s body finishes
executing last
158
Instantiating Subclass ObjectChain Of Constructor Calls
• Example, Figure 9.15 : CommissionEmployee3-BasePlusCommissionEmployee4 hierarchy– CommissionEmployee3 constructor called second last
(last is Object constructor)– CommissionEmployee3 constructor’s body finishes
execution second (first is Object constructor’s body)
• Figure 9.16, BasePlusCommissionEmploye5• Figure 9.17, Test program, demonstrates
constructor calls
159
Software Engineering with Inheritance
• At the design stage, certain classes found to be closely related– _______________ common attributes, behaviors– Place these in a ____________________– Use inheritance to develop subclasses with
inherited capabilities
• This avoids _____________ of classes, "reinventing the wheel"
• Note– Declaring a subclass ______________________
superclass source code
160
Object-Oriented Programming: Polymorphism
Chapter 10
161
Problem with Subclasses• Given the class hierarchy below• Consider the existence of a draw function for each
subclass• Consider also an _____________________ to the
superclass (which can also point to various objects of the subclasses)
• How do you specify which __________ statement to be called when using the references
Shape class hierarchy
Circle
Right Triangle Isosceles Triangle
Triangle
Square
Rectangle
Shape
162
Introduction
• Polymorphism– Enables “programming in the ______________”– The same invocation can produce
“____________________” of results
• Interfaces– Implemented by classes to assign common
functionality to possibly unrelated classes
163
Polymorphism
• When a program invokes a method through a superclass variable,
– the correct ______________ version of the method is called,
– based on the __________________ stored in the superclass variable
• The same method name and signature can cause different actions to occur,
– depending on the ________________ on which the method is invoked
164
Polymorphism
• Polymorphism enables programmers to deal in generalities and – let the ______________ environment handle the
specifics.
• Programmers can command objects to behave in manners appropriate to those objects, – ___________________ the types of the objects – (as long as the objects belong to the same
inheritance hierarchy).
165
Polymorphism Promotes Extensibility
• Software that invokes polymorphic behavior– independent of the ________________ to which
messages are sent.
• New object types that can respond to existing method calls can be – incorporated into a system without requiring
modification of the ____________________. – Only client code that ______________ new objects
must be modified to accommodate new types.
166
Demonstrating Polymorphic Behavior
• A superclass reference can be aimed at a ______________ object
– a subclass object “is-a” superclass object – the type of the actual referenced _____________,
not the type of the _____________, determines which method is called
• A subclass reference can be aimed at a superclass object only if the object is _________________
• View example, Figure 10.1
167
Polymorphism
• Promotes _____________________
• New objects types can respond to ______________ method calls– Can be incorporated into a system without
modifying base system
• Only client code that instantiates the new objects must be modified – To accommodate ________________
168
Abstract Classes and Methods
• Abstract classes – Are superclasses (called abstract superclasses)– Cannot be _______________________ – Incomplete
• subclasses fill in "missing pieces"
• _______________________ classes– Can be instantiated– ________________ every method they declare– Provide specifics
169
Abstract Classes and Methods
• Purpose of an abstract class– Declare common ________________ …– Declare common behaviors of classes in a class
hierarchy
• Contains one or more abstract _____________– Subclasses must ______________
• Instance variables, concrete methods of abstract class– subject to normal rules of ______________
170
Abstract Classes• Classes that are too ____________ to create
real objects
• Used only as abstract superclasses for concrete subclasses and to declare ___________________
• Many inheritance hierarchies have abstract superclasses occupying the top few levels
171
Keyword abstract
• Use to declare a class abstract• Also use to declare a _____________ abstract
• Abstract classes normally contain one or more abstract _______________
• All _____________ subclasses must override all inherited abstract methods
172
Abstract Classes and Methods•Iterator class
– __________________ all the objects in a collection, such as an array
– Often used in polymorphic programming to traverse a collection that contains references to objects from various levels of a hierarchy
173
Abstract Classes
• Declares common attributes and behaviors of the various classes in a class hierarchy.
• Typically contains one or more abstract _______________ – __________________ must override if the
subclasses are to be concrete.
• Instance variables and concrete methods of an abstract class subject to the normal rules of inheritance.
174
Beware! Compile Time Errors
• Attempting to ______________ an object of an abstract class
• Failure to ______________ a superclass’s abstract methods in a subclass – unless the subclass is also declared abstract.
175
Creating Abstract Superclass Employee
•abstract superclass Employee,Figure 10.4– earnings is declared abstract
• ______________________ can be given for earnings in the Employee abstract class
– An array of Employee variables will store _____________ to subclass objects•earnings method calls from these variables will call the
appropriate version of the earnings method
176
Example Based on Employee
Abstract Class
Concrete Classes
177
Polymorphic interface for the Employee hierarchy classes.
178
Note in Example Hierarchy
• Dynamic binding– Also known as _____________ binding– Calls to overridden methods are resolved at
______________ time, based on the type of object referenced
• instanceof operator– Determines whether an _____________ is an
instance of a certain type
179
How Do They Do That?
• How does it work?– Access a derived object via __________________– Invoke an abstract method– At run time the __________________ of the
method is used
• Design of the V-Table– Note description from C++
180
Note in Example Hierarchy• Downcasting
– Convert a reference to a superclass to a reference to a subclass
– Allowed only if the object has an_____________relationship with the subclass
• getClass method– Inherited from __________________– Returns an object of type Class
• _______________ method of class Class– Returns the class’s name
181
Superclass And Subclass Assignment Rules
• Assigning a superclass reference to superclass variable straightforward
• Subclass reference to subclass variable straightforward
• Subclass reference to superclass variable ________ – because of is-a relationship– Referring to subclass-only members through superclass
variables a compilation error
• Superclass reference to a subclass variable a ___________________– Downcasting can get around this error
182
final Methods and Classes
•final methods– Cannot be ______________ in a subclass– ___________ and __________ methods implicitly final
– final methods are resolved at __________ time, this is known as static binding• Compilers can optimize by inlining the code
•final classes– Cannot be _____________ by a subclass– All methods in a final class implicitly final
183
Why Use Interfaces
• Java has single _____________, only
• This means that a child class inherits from only one parent class
• Sometimes multiple inheritance would be convenient
• Interfaces give Java some of the advantages of multiple inheritance without incurring the disadvantages
184
What is an Interface?
• An interface is a collection of _____________ and method declarations
• The method declarations do not include an _________________ (there is no method body)
185
What is an Interface?
• A child class that extends a parent class can also _____________ an interface to gain some additional behavior
• Implementing an interface is a “______________” to include the specified method(s)
• A method in an interface cannot be made ________________
186
When A Class Definition Implements An Interface:
• It _____________________ each method in the interface
• Each method must be public (even though the interface might not say so)
• ________________ from the interface can be used as if they had been defined in the class (They should not be re-defined in the class)
187
Declaring Constants with Interfaces
• ________________ can be used to declare constants used in many class declarations
– These constants are implicitly public, static and final
– Using a __________________ declaration allows clients to use these constants with just their names
188
Implementation vs. Interface Inheritance
ImplementationInheritance
• Functionality ______ in the hierarchy
• Each new subclass inherits one or more methods declared in superclass
• _____________ uses superclass declarations
Interface Inheritance
• Functionality lower in hierarchy
• Superclass specifies one or more _________ methods
• Must be declared for each class in hierarchy
• Overridden for subclass-specific implementations
189
Creating and Using Interfaces
• Declaration begins with ________________ keyword
• Classes implement an _____________ (and its methods)
• Contains __________________ methods– Classes (that implement the interface) must
implement these methods
190
Creating and Using Interfaces
• Consider the possibility of having a class which manipulates mathematical functions
• You want to send a function as a parameter– Note that C++ allows this directly– Java does not
• This task can be accomplished with interfaces
191
Creating and Using Interfaces
• Declare interface Function• Declare class MyFunction which implements Function
• Note other functions which are subclass objects of MyFunction
• View test program which passes Function subclass objects to function manipulation methods
192
Graphical User Interface Components: Part 1
Chapter 11
193
Graphical User Interface (GUI)
• Gives program distinctive “______________”
• Provides users with basic level of familiarity
• Built from GUI ________________ (controls, widgets, etc.)– User interacts with GUI component via mouse,
keyboard, etc
• Check out this visual index of components
194
Netscape Window With GUI Components
menu barbutton combo boxmenus
scroll bars
195
Dialog Boxes
• Used by applications to interact with the user
• Provided by Java’s JOptionPane class– Contains input dialogs and message dialogs
• View example program, Figure 11.2
196
Dialog Boxes
• Note icon
• Other icons available
Message dialog type Icon Description
ERROR_MESSAGE
A dialog that indicates an error to the user.
INFORMATION_MESSAGE
A dialog with an informational message to the user.
WARNING_MESSAGE
A dialog warning the user of a potential problem.
QUESTION_MESSAGE
A dialog that poses a question to the user. This dialog normally requires a response, such as clicking a Yes or a No button.
PLAIN_MESSAGE no icon A dialog that contains a message, but no icon.
197
Some Basic GUI Components
Component Description
JLabel Displays uneditable text or icons.
JTextField Enables user to enter data from the keyboard. Can also be used to display editable or uneditable text.
JButton Triggers an event when clicked with the mouse.
JCheckBox Specifies an option that can be selected or not selected.
JComboBox Provides a drop-down list of items from which the user can make a selection by clicking an item or possibly by typing into the box.
JList Provides a list of items from which the user can make a selection by clicking on any item in the list. Multiple elements can be selected.
JPanel Provides an area in which components can be placed and organized. Can also be used as a drawing area for graphics.
Component Description
JLabel Displays uneditable text or icons.
JTextField Enables user to enter data from the keyboard. Can also be used to display editable or uneditable text.
JButton Triggers an event when clicked with the mouse.
JCheckBox Specifies an option that can be selected or not selected.
JComboBox Provides a drop-down list of items from which the user can make a selection by clicking an item or possibly by typing into the box.
JList Provides a list of items from which the user can make a selection by clicking on any item in the list. Multiple elements can be selected.
JPanel Provides an area in which components can be placed and organized. Can also be used as a drawing area for graphics.
198
Overview
• Swing GUI components– Declared in package __________________– Most are ____________ Java components– Part of the Java Foundation Classes (JFC)
• Abstract Window Toolkit (AWT)– ___________________ to Swing– Declared in package java.awt– Does not provide consistent, cross-platform look-
and-feel
199
Lightweight vs. Heavyweight
• Lightweight components– Not tied directly to ________________________
supported by underlying platform
• Heavyweight components– Tied directly to the ____________ platform– AWT components– Some Swing components
200
Superclasses of Swing’s Lightweight GUI Components
• Class Component – (package java.awt)– ______________________ of Object– Declares many behaviors and attributes common to
GUI components
201
Superclasses of Swing’s Lightweight GUI Components
• Class Container – (package java.awt)– Subclass of Component– _____________________ Components
202
Superclasses of Swing’s Lightweight GUI Components
• Class JComponent – (package javax.swing)– Subclass of Container– _________________ of all lightweight Swing
components
203
Common Lightweight Component Features
• Pluggable look-and-feel – _______________ the appearance of components
• Shortcut keys – mnemonics
• Common ____________________ capabilities
• Brief description of component’s purpose – tool tips
• Support for _____________________
204
Displaying Text and Images in a Window
• Class JFrame– Most windows are an instance or subclass of this
class– Provides _______________________– Provides min, max, close ______________
• Label– ______________________ or information stating
the purpose of each component– Created with class JLabel
205
Three Parts of a GUI Application
1. ________________________ that make up the Graphical User Interface
2. ________________ that receive the events and respond to them
3. ____________________ that does useful work for the user
206
Events Generated by Swing Components
Act that results in the event Listener type
User clicks a button, presses Return while typing in a text field, or chooses a menu item
User closes a frame (main window) WindowListener
User presses a while the cursor is over a component
MouseListener
User over a component
MouseMotionListener
Component becomes visible ComponentListener
Component gets the keyboard focus FocusListener
Table or list selection changes ListSelectionListener
207
Events Generated by Swing Components
• Each __________ is represented by an object – Object gives information about the event – Identifies the event _________________.
• Event sources are typically _____________, – Other kinds of objects can also be event sources.
• Each event source can have _____________ listeners registered on it. – Conversely, a
single listener can register with multiple event sources.
208
JLabel
• Label– Provide ________________ on GUI– Defined with class JLabel– Can display:
• Single line of read-only text• __________________________• Text and image
• View Figure 11.6 – Note uses of the JLabel Class
209
Creating and Attaching label1
• Method setToolTipText of class JComponent
– Specifies the tool tip
• Method add of class Container– Adds a _________________ to a container
210
Creating and Attaching label2
• Interface Icon– Can be added to a ________________ with
the setIcon method– Implemented by class ImageIcon
211
Creating and Attaching label2
• Interface SwingConstants– Declares a set of
___________________________________ such as those used to set the alignment of components
– Can be used with methods setHorizontalAlignment and setVerticalAlignment
212
Creating and Attaching label3
• Other JLabel methods– getText and ____________________
• For setting and retrieving the text of a label
– getIcon and setIcon• For setting and retrieving the _______________
displayed in the label
– getHorizontalTextPosition and setHorizontalTextPosition• For setting and retrieving the horizontal position of the
text displayed in the label
213
Some basic GUI Components.
Constant
Description
Horizontal-position constants
SwingConstants.LEFT Place text on the left. SwingConstants.CENTER Place text in the center. SwingConstants.RIGHT Place text on the right.
Vertical-position constants
SwingConstants.TOP Place text at the top. SwingConstants.CENTER Place text in the center. SwingConstants.BOTTOM Place text at the bottom.
214
Other JFrame Methods
• setDefaultCloseOperation– Dictates how the
____________________________ when the user clicks the close button
• setSize– Specifies the width and height of the __________
• setVisible– Determines whether the window is displayed (true)
or not (false)
215
Event Handling
• An event occurs every time the user– ________________ a character or – Pushes a _________________________
• Any object can be ________________ of the event.
• That object must:– ________________ the appropriate interface – Be registered as an event _____________ on the
appropriate event source.
216
Event Handling
• GUI's are _______________ driven– Events occur when user interacts with GUI– e.g., moving mouse, pressing button, typing in text
field, etc.
• Class java.awt.AWTEvent• Checkout Sun tutorial on event handling
217
Some Event Classes Of Package java.awt.event
218
Event Handling Model
• Three parts– Event _________________
• GUI component with which user interacts
– Event _________________• Encapsulates information about event that occurred
– Event _________________• Receives event object when notified, then responds
• Programmer must perform two tasks– ____________ event listener for event source– Implement event-handling method (event handler)
219
Event Listener Object
• When a GUI program is running, each action of the user generates an event
• The following are some types of events: – Moving the ______________ – Clicking the mouse on a button – ______________ some text into a text area
• For a program to respond to an event there must be an ____________ object in the GUI program that listens to that type of event
220
What is an Event Listener?
• An event listener is an _____________ – It "listens" for events from a specific GUI component
(itself an object)
• When an event is generated by the GUI component– A ____________ in the listener object is invoked to
respond to the event
221
What If …?
• When there is no event ______________ for an event – A program can ____________ events – If there is no listener for an event, the event is just
ignored
222
Event-listener
Interfaces Of Package java.awt.event
223
Textfields
• JTextField– __________ area in which user can enter text
• JPasswordField– Extends JTextField– ______________ characters that user enters
• View Figure 11.9– Illustrates capabilities of textfields– Note help on handling number fields
224
How Event Handling Works
• You must ______________ the event handler– Through component’s method addActionListener
225
How Event Handling Works
• The component knows to call actionPerformed because …– Event is _______________ only to listeners of
appropriate type– Each event type has corresponding event-listener
interface• Event _____________ specifies event type that occurred
226
Event Registration for JTextField textField1
227
JButton
• Button– Component user clicks to trigger a specific action– Several different types
• Command ________________• Check ________________• Toggle buttons• __________________ buttons
– javax.swing.AbstractButton subclasses• Command buttons are created with class JButton• Generate __________________________ when user
clicks button
228
Swing Button Hierarchy
229
JButton Example
• View, ButtonFrame class, Figure 11.15
• Test program, Figure 11.16
• Look for– Declaration of the buttons– Inner class ButtonHandler which does event
handling for the button– Call to .addActionListener(handler) method
registers buttons to receive events– The actionPerformed() method
230
Comments on JButton• To detect when user clicks button
– Program must have an _______________ that implements ActionListener interface
• Program must __________ object as an action listener on the button (the event source) – Using the addActionListener method
231
Comments on JButton• When user clicks the button, it fires an action
_________________. – Results in the invocation of the action listener's actionPerformed _____________
– The only method in the ActionListener interface
•JButtons can have a __________ icon– Appears when mouse is positioned over a button– Added to a JButton with method setRolloverIcon
232
Buttons That Maintain State
• Swing contains three types of ____________ buttons
•JToggleButton, JCheckBox and JRadioButton•JCheckBox and JRadioButton are
______________ of JToggleButton
233
JCheckBox
• Contains a check box ______________ that appears to right of check box by default
• Generates an ItemEvent when it is ____________
– ItemEvents are handled by an ItemListener– Passed to method _______________________
• Method isSelected returns whether check box is selected (true) or not (false)
• View example class Figure 11.17test Figure 11.18
234
JRadioButton
• Has two states – selected and unselected• Normally appear in a _____________ in which
only one radio button can be selected at once– Group maintained by a ButtonGroup object
• Declares method add to add a JRadioButton to group
• Usually represents mutually ____________ options
• View RadioButtonFrame, Figure 11.19Test program, Figure 11.20
235
Demonstration of JRadioButton
• When viewing Figure 11.19, look for the following– Declaration of JRadioButton references– Group specification– Instantiation of JRadioButton objects– Registration of JRadioButton's to receive events– RadioButtonHandler invokes method itemStateChanged
236
JComboBox
• JComboBox– List of items from which user can select– Also called a drop-down list
• Note features in Figure 11.21
• Instantiate JComboBox to show three Strings from names array at a time
• Register JComboBox to receive events
• ItemListener invokes method itemStateChanged
237
JList
• A list is a series of items– User can _____________ one or more items– Single-selection vs. multiple-selection
• JList demonstration, Figure 11.23– Note use of ColorNames array to populate JList– Specification of SINGLE_SELECTION– Registration of JList to __________ events– ListSelectionListener invokes method valueChanged
– Background set according to user choice
238
Multiple-Selection Lists
• Multiple-selection list capabilities– Select ______________ items from Jlist– Allows continuous _________ selection
• Look for the following in Figure 11.25
• Use of ColorNames array– Specification of MULTIPLE_INTERVAL_SELECTION
option– Use of JButton and JListCopyList method
239
Mouse Events
• Create a MouseEvent object
• Handled by MouseListeners and MouseMotionListeners
• MouseInputListener combines the two interfaces
• Interface MouseWheelListener declares method mouseWheelMoved to handle MouseWheelEvents
240
Mouse Event Handling
• Event-listener interfaces for mouse events– MouseListener– MouseMotionListener– Listen for MouseEvents
• In Figure 11.28 note use of…– Register JFrame to receive mouse events– Methods invoked for various mouse events
• (Note that program does not seem to perform as advertised when run under ReadyTo !!?)
241
Listener Interfaces
MouseListener and MouseMotionListener interface methods
Methods of interface MouseListener
public void mousePressed( MouseEvent event )
Called when a mouse button is pressed while the mouse cursor is on a component.
public void mouseClicked( MouseEvent event )
Called when a mouse button is pressed and released while the mouse cursor remains stationary on a component. This event is always preceded by a call to mousePressed.
public void mouseReleased( MouseEvent event )
Called when a mouse button is released after being pressed. This event is always preceded by a call to mousePressed and one or more calls to mouseDragged.
public void mouseEntered( MouseEvent event )
Called when the mouse cursor enters the bounds of a component.
242
Listener Interfaces
MouseListener and MouseMotionListener interface methods
public void mouseExited( MouseEvent event )
Called when the mouse cursor leaves the bounds of a component.
Methods of interface MouseMotionListener
public void mouseDragged( MouseEvent event )
Called when the mouse button is pressed while the mouse cursor is on a component and the mouse is moved while the mouse button remains pressed. This event is always preceded by a call to mousePressed. All drag events are sent to the component on which the user began to drag the mouse.
public void mouseMoved( MouseEvent event )
Called when the mouse is moved when the mouse cursor is on a component. All move events are sent to the component over which the mouse is currently positioned.
243
Listener Interfaces
• Suppose your class directly implements MouseListener, – Then you ___________________ all five MouseListener methods.
– Even if you care only about mouse clicks
• Methods for those events you don't care about can have ______________ bodies. – Resulting collection of empty method bodies can
make code harder to read and maintain
244
Adapter Classes
• Solution is to use __________________ classes
• For example, the MouseAdapter class implements the MouseListener interface.
• An adapter class implements ____________ of all its interface's methods.
245
Adapter Classes
• To use an adapter– Create a ________________ of it, instead of
directly implementing a listener interface. – By extending MouseAdapter, your class
_________________ empty definitions of all five of the methods that MouseListener contains.
246
Adapter Classes
• Characteristics of an adapter class– _________________ interface– Provides ________________ implementation of
each interface method– Used when all methods in interface is not needed
Event-adapter class in java.awt.event Implements interface
ComponentAdapter ComponentListener ContainerAdapter ContainerListener FocusAdapter FocusListener KeyAdapter KeyListener MouseAdapter MouseListener MouseMotionAdapter MouseMotionListener WindowAdapter WindowListener
247
Adapter Classes
• Example of use of an adapter class– Figure 11.34 , the Painter program
• Note– Registration of MouseMotionListener to listen
for window’s __________________ events– ____________________ method mouseDragged,
but not method mouseMoved– Store ________________ where mouse was
dragged, then repaint JFrame
248
Extending MouseAdapter
• The MouseDetails.java program, Note example, Figure 11.31
• Demonstrates– How to determine the __________ of mouse clicks– How to distinguish between _______________
mouse buttons
249
InputEvent Methods
• Help distinguish among – left-, – center- and – right-mouse-button clicksInputEvent method Description
isMetaDown() Returns true when the user clicks the right mouse button on a mouse with two or three buttons. To simulate a right-mouse-button click on a one-button mouse, the user can hold down the
Meta key on the keyboard and click the mouse button.
isAltDown() Returns true when the user clicks the middle mouse button on a mouse with three buttons. To simulate a middle-mouse-button click on a one- or two-button mouse, the user can press the Alt key on the keyboard and click the only- or left-mouse button, respectively.
250
Key Event Handling
• Interface KeyListener• Handles key events
– Generated when keys on keyboard are pressed and released
• KeyEvent– Contains ___________________ that represents
key
• Demonstrated in Figure 11.36
251
Layout Managers
• Layout manager capabilities– Provided for _________________ GUI components– Provide basic layout capabilities– Processes layout details– Programmer can concentrate on basic “look and
feel”– Interface LayoutManager
252
Layout Managers
• Layout manager methods
Layout manager Description
FlowLayout Default for javax.swing.JPanel. Places components sequentially (left to right) in the order they were added. It is also possible to specify the order of the components by using the Container method add, which takes a Component and an integer index position as arguments.
BorderLayout Default for JFrames (and other windows). Arranges the components into five areas: NORTH, SOUTH, EAST, WEST and CENTER.
GridLayout Arranges the components into rows and columns.
253
FlowLayout
• _____________________ layout manager
• GUI components placed in container from _________ to ______________
• Example program, Figure 11.39– Layout set as FlowLayout– Note results as user presses button
254
BorderLayout
• Arranges components into five ___________– NORTH (top of container)– SOUTH (bottom of container)– EAST (left of container)– WEST (right of container)– CENTER (center of container)
• View example, Figure 11.41
255
GridLayout
• Divides container into grid of specified ___________________________
• Components are added starting at top-left cell– Proceed left-to-fight until ____________ is full
• GridLayout demonstration, Figure 11.43– Clicking buttons toggles between different layouts
256
Panels
• Helps organize components
• Class JPanel is ____________ subclass
• May have components (and other _____________) added to them
• Panel example, Figure 11.45
257
Applying Concepts
• Suppose you wish to have a GUI which accomplishes the following– Enter numbers
in text boxes– Press button
to do calculations
258
Step By Step
• View code to create the window
• Note– Class (program) extends JFrame– Constructor sets up window using methods
inherited from JFrame– Method main()instantiates class object
259
Add the Text Labels
• View additional code
• Note– Declaration, instantiation of JLabels– Container reference, pane
Gets handle for contentPane– pane layout specified– JLabels added
260
Add the Text Boxes
• View next iteration of code for adding the JTextFields
• Note– Declaration, instantiation of JTextFields– Change grid layout of pane for 2 columns– Adding to pane
261
Final Version
• View final code version• Note
– Declaration, instantiation of buttons– Declaration, definition, instantiation of action
handlers• Different author, does not use inner anonymous classes
– Add action handlers to the buttons
• Our program never actually calls the action handlers
262
Implement an Event Handler Every event handler requires three bits of code:
1. Code that specifies that the class either 1. Implements a listener interface or 2. Extends a class that implements a listener interface.
For example:
public class MyClass implements ActionListener {… 2. Code that registers an instance of the event
handler class as a listener upon one or more components. For example: someComponent.addActionListener(instanceOfMyClass);
3. Code that implements the methods in the listener interface. For example: public void actionPerformed(ActionEvent e) { ...//code that reacts to the action... }
263
Exception Handling
Chapter 13
264
Motivation
• We seek programs• When something unexpected occurs
– Ensure program ________________________ the problem– Then program must do something about it
• Extensive testing of special situations can result in "____________________ code"
• Need mechanism to check for problem where it could occur
• When condition does occur– Have _________________ to code to handle the problem
265
Overview
• Exception– Indication of ___________________ during execution
• Uses of exception handling– Process exceptions from program components– Handle exceptions in a uniform manner ______________– Remove ___________ code from “main line” of execution
• A method detects an error and throws an exception– Exception handler processes the error– Uncaught exceptions yield _____________ effects
• Might terminate program execution
266
Overview
• Code that could generate errors put in ________ blocks – Code for error handling enclosed in a __________
clause– The ____________ clause always executes
• Termination model of exception handling– The block in which the exception occurs expires
• throws clause specifies _____________ method throws
267
Exception Handler
Exception "thrown" here
Exception handler
Exception handler
Thrown exception matched against first set of exception handlers
If it fails to match, it is matched against set of handlers, etc.
If exception matches ___________ of handlers, program is abandoned
268
Example
• Consider the problem of division by zero
• Note elements of Figure 13.1– try block– Following catch blocks– throws specification
269
Sequence of Events for throw
Preceding step
try block
throw statement
unmatched catch
matching catch
unmatched catch
next step
270
Sequence of Events for No throw
Preceding step
try block
throw statement
unmatched catch
matching catch
unmatched catch
next step
271
Java Exception Hierarchy
• __________________ Throwable– Subclass ________________
• Exceptional situations• Should be caught by program
– Subclass ______________• Typically not caught by program
• Checked exceptions– Catch or _________________
• Unchecked exceptions
272
Inheritance hierarchy for class Throwable
Throwable
Exception Error
AWTError ThreadDeathIOExceptionRuntimeException OutOfMemoryError
273
Handling Exceptions
• Rethrow exception if catch cannot handle it
• Resource leak– Caused when _____________________________
by a program
• The finally block– Appears after catch blocks– Always ________________– Optional– Use to release resources
274
Using finally
• View program, Figure 13.3• Note
– __________________ of exception– Code for throw exception– Blocks using ________________
• Suggestion– Do not use a try block for ____________________
which may cause a problem– Enclose _____________________ of statements– Follow by _______________ catch blocks
275
Sequence of Events for finally clause
Preceding step
try block
throw statement
unmatched catch
matching catch
unmatched catch
next step
finally
276
Stack Unwinding
• Exception not caught in scope– Method _________________– Stack ______________________ occurs– Another attempt to catch exception
• View Figure 13.4
• Note– Sequence of events during run– Resulting output
277
printStackTrace, getStackTrace and getMessage
• Throwable class– Method printStackTrace
• Prints method call __________________
– Method getStackTrace • Obtains stack-trace information
– Method getMessage• Returns _____________________ string
• View example of these, Figure 13.5
278
Chained Exceptions
• Useful for a catch handler to– Catch one exception type– Then throw a new exception of ________________– Indicates program-specific exception
• Chained exceptions enable– Exception object to ____________________ info
• Figure 13.6 demonstrates use of chained exceptions
279
Multithreading
Chapter 23
280
Introduction
• Consider ability of human body to ___________– Breathing, heartbeat, chew gum, walk …
• In many situations we need a computer to multitask
• Concurrency normally available in __________
• Java provides built-in multithreading– Multithreading improves the ___________ of some
programs
281
Thread States: Life Cycle of a Thread
• __________________ state– New thread begins its life cycle in the new state– Remains in this state until program starts the
thread, placing it in the runnable state
• runnable state– A thread in this state is ___________ its task
• waiting state– A thread ___________ to this state to wait for
another thread to perform a task
282
Thread States: Life Cycle of a Thread
• __________________ state– A thread enters this state to wait for another
thread or for an amount of time to elapse– A thread in this state returns to the ___________
state when it is signaled by another thread or when the timed interval expires
• terminated state– A runnable thread enters this state when it
_____________ its task
283
Operating System View Of runnable State
• ready state– ____________ waiting for another thread– Waiting for the ______________ to assign the
thread a processor
284
Operating System View Of runnable State
• running state– Currently has a _________________ and is
executing– Often executes for a small amount of processor
time called a _______________________ before transitioning back to the ready state
285
Thread Priorities and Thread Scheduling
• Java thread priority– Priority in range ______________
• Timeslicing– Each thread assigned time on the processor (called
a quantum)– Keeps ______________ threads running
286
Priorities and
Scheduling
Thread.MAX_PRIORITY
287
Creating and Executing Threads•Runnable interface
– Preferred means of creating a multithreaded application
– Declares method _______________– Executed by an object that implements the Executor interface
•Executor interface– Declares method ___________________– Creates and manages a group of threads called
a thread pool
288
Creating and Executing Threads
•ExecutorService interface– ______________________ of Executor that
declares other methods for managing the life cycle of an Executor
– Can be created using _______________ methods of class Executors
– Method shutdown _______________ when tasks are completed
289
Creating and Executing Threads
•Executors class– Method newFixedThreadPool creates a pool
consisting of a __________________________ of threads
– Method newCachedThreadPool creates a pool that creates new threads _____________________________
290
Creating and Executing Threads
• PrintTask class Figure 23.4
• RunnableTester, Figure 23.5
• Demonstrates– ____________ Thread objects– Using Thread methods ___________ and sleep– Creates 3 equal priority threads– Each is put to sleep for random number of
milliseconds– When awakened, it displays name, etc.
291
Producers and Consumers
• Producer– Generating
_______________
• Consumer– Receives and
_________________the output
292
Synchronization
• Problem– Sometimes the producer gets too far
____________ of the consumer • The objects produced fill up the holding area
(_____________)• The producer must wait for space to place objects
– Sometimes the ______________ gets ahead of the producer
• There are no objects to be processed (_____________ buffer)
• The consumer must wait for the producer
293
Thread Synchronization• Thread synchronization
– Provided to the programmer with _____________________• Exclusive access to a shared object
– Implemented in Java using _____________
•Lock interface– lock method obtains the lock, enforcing mutual
exclusion– unlock method ________________ the lock– Class ReentrantLock implements the Lock
interface
294
Thread Synchronization
• Condition variables– If a thread holding the lock cannot continue with its
task until a condition is satisfied, the thread can wait on a ____________________
– Create by calling Lock method newCondition– Represented by an object that implements the ___________________ interface
295
Thread Synchronization
• Condition interface– Declares methods await, to make a thread wait, – ____________________, to wake up a waiting
thread, and – signalAll, to wake up all waiting threads
296
Producer/Consumer Relationship without Synchronization
• Buffer– ____________________ memory region
• Producer thread– Generates _____________ to add to buffer– Calls wait if consumer has not read previous message in
buffer– Writes to empty buffer and calls ____________ for
consumer
• Consumer thread– Reads data from buffer– Calls wait if buffer ________________
• Synchronize threads to avoid corrupted data
297
Producer/Consumer Relationship without Synchronization
• View source code which establishes– Buffer, Figure 23.6
• An interface which specifies get and set methods
– Producer, Figure 23.7• ___________________ of Thread• Uses a shared Buffer object• Method run is _________________ from Thread class• Uses Buffer.set() method
– Consumer, Figure 23.8• Also a subclass of Thread, also uses shared Buffer• Uses the Buffer.get() method
298
Producer/Consumer Relationship without Synchronization
• View Figure 23.9 which implements the Buffer interface– Implements the _________________ methods
• This UnsynchronizedBuffer object is used in Figure 23.10 program– Buffer object declared, instantiated– Also Producer and Consumer objects– Both threads call method start()
299
Producer/Consumer Relationship without Synchronization
• Example randomly called producer and consumer
• You should note that in some cases the data was _________________– Consumer reads values _________ producer
generates– Consumer _______________ a value– Consumer reads same value multiple times
• We need to deal with problem so data is not corrupted
300
Producer/Consumer Relationship with Synchronization
• Solution is to _________________ the producer and consumer objects
• Figure 23.11 implements a buffer and synchronizes – Consumer consumes only ______ produces a value– Producer produces a value only after consumer
consumes ____________ value produced– Condition variable occupiedBufferCount
determines whose turn it is
• Program which uses this, Figure 23.12
301
Using Thread Methods
• Create Wait class
• Has _______________ methods
• Provide capability to have another application ______________ for a certain amount of time
• Note Example to act as a simple timer.
302
Circular Buffer• Features
– Multiple memory cells– Produce item if one or more empty cells– Consume item if one or more filled cells
• Caveats– Producer and consumers must be relatively
______________ speed• Otherwise buffer fills up or stays empty
– Synchronization still necessary– Seek to optimize buffer size
• ______________________ thread-wait time
303
Circular Buffer
• Circular Buffer class Figure 23.13– ______________ for mutual exclusion– Condition variables to control writing and reading– Circular buffer; provides three spaces for data– Obtain the lock ____________ writing data to the
circular buffer– Wait until a buffer space is ___________– Impose circularity of the buffer– ___________ waiting thread when to read data
from buffer– Release lock
304
Circular Buffer
• Circular Buffer test, Figure 23.14– Create instance of circular buffer– Execute producer, consumer in separate threads
305
Daemon Threads
• Run for benefit of _____________________– Do not prevent program from terminating– __________________ is a daemon thread
• Set daemon thread with method setDaemon– Must be done at __________________ time
• Do not assign _____________ tasks to daemon thread– Will be terminated without warning– May prevent those tasks from completing properly
306
Runnable Interface
• May be necessary to __________ a class that already extends a class other than Thread
• Java does not allow a class to extend more than one class at a time– Implement Runnable for ____________ support
• Program that uses a Runnable object to control a thread– Creates a Thread object– Associates the Runnable object with that Thread
class
307
Runnable Interface
• Illustration of using a Runnable interface– Figure 23.18
• Note methods start, stop, run
308
Files and Streams
Chapter 14
309
Introduction
• Storage of data in variables is ___________– when the program is done running,
when computer is turned off The data is gone!
• Data stored permanently (more or less) on secondary storage devices– magnetic ____________– ___________ disks– tapes
• We consider creation & use of files of data
310
The Data Hierarchy
• Lowest level of data storage is in ____________________– 0s and 1s -- bits
• Bits grouped together into _______________• Bytes grouped into characters• Characters and/or bytes grouped together to form
_________________• Fields grouped together to form records• Records grouped to form files
311
The Data Hierarchy
312
Sequential Devices -- Some History
• Tape Drives
313
Data Stored on Tape
Interblock Gap for purpose of _______________ or deceleration of tape past the read/write head.
Result is large percentage of tape length ___________ on the gaps.
Interblock Gap for purpose of _______________ or deceleration of tape past the read/write head.
Result is large percentage of tape length ___________ on the gaps.
314
Data Stored on Tape
Records _______________ in groups to save space wasted by the required gaps
Records _______________ in groups to save space wasted by the required gaps
315
Disk Components
• Cylinders• Tracks• Sectors
316
Disk Components
• _______________ heads move in and out
• Possible to have multiple fixed heads
• Need head for each _____________ surface
• __________________ of data on inside as outside tracks
317
Disk Components
• Track• Sector• Inner sectors have
same amount of data as outer outer (why?)
• Outer sectors less ____________ (bits per inch)
318
Timing Components
• Access motion time (_____________ time)– motion of read/write heads between tracks– this is the most time of the three
• Rotational delay
• Data __________ time
319
Storage of Sequential Files
• Any type of serial access storage device– originally ___________________– magnetic tape– even punched paper tape!
• Now would be placed on __________________ devices (disks)
320
Files and Streams
• Java views a file as a stream of __________ • File ends with end-of-file marker or a specific byte
number
• File as a stream of bytes associated with an object– Java also associates streams with _____________
•System.in, System.out, and System.err• Streams can be redirected
321
Files and Streams
• File processing with classes in package java.io– FileInputStream for
____________________ input from a file– FileOutputStream for
byte-based ________________ to a file– FileReader for -based
input from a file– ________________ for character-based
output to a file
322
Files and Streams
• Buffering– ____________________ performance of I/O– Copies each output to a region of memory called a buffer
• We can send the entire buffer to disk ___________– One long disk access takes ____________________ than
many smaller ones– Due to repeated head seeks required
• BufferedOutputStream buffers file output• BufferedInputStream buffers file input
323
Class File
• Methods from class File
324
Class File
• Methods from class File
325
Class File
• View Figure 17.4– Creates a GUI with JTextField– Enter file, directory name– _________________ displays information
• Program features– Body of if outputs information about file if it exists– Test if object is ______________, test if file exists– Create a reader to gather data from file– Read text _________________ in file– Get list of files in directory
326
Creating a Sequential-Access File
• Java imposes __________________ on a file
• _______________________ structures file according to application
• AccountRecord class specified in Figure 17.6 declares structure for file access examples … note …– Class compiled into _______________– Imlements ________________ for use without
I/O streams
327
Creating a Sequential-Access File
• Program in Figure 17.5 prepares GUI's for file access program
• Note– Class compiled as a package– Buttons provided for actions in later examples– Generic doTask buttons
328
Creating a Sequential-Access File
• Program in Figure 17.7 imports the GUI and record classes– Interface and references to buttons created– Instantiate, assign JFileChooser object– Selected file retrieved, opened– Method closeFile to close current file– Data retrieved from text fields– New record retrieved, written to file
329
Reading Data from Sequential Access Files
• Data stored in files• Retrieved for processing when needed• Accessing a sequential file
– Data must be read in ________________ it was written
• Note program of Figure 17.9– Create instance of interface– Respond to Open button, Next button– JFileChooser used as before– Method _______________ reads an Object from the ObjectInputStream
330
Reading Data from Sequential Access Files
• To read from file repeatedly– Must close and reopen file
• Each time through– Print only records which _________________
• Figure 17.19 allows inquiries– Note ____________ of FileInputStream in ObjectInputStream
– Note use of _______________ for EOFException
331
Updating Sequential Access Files
• Difficult to ____________ a sequential-access file– Entire file must be rewritten to change one field– Only acceptable if many records being updated at
once
• Note that this was done in the days of using magnetic tapes
332
Characteristics of Sequential Systems
• Two types of files– ___________ files -- files with relatively
permanent data– Transaction files -- file of _____________ records
• Updating master files– use transaction files– combine (_____________) old master with
transaction file– create new master file– Old master and Transaction file are the
_____________ for the New Master
333
Updating Master Files
Old Master
File Transaction
Update Program Exception
Report
New Master
334
Updating Master Files
• Transaction file contains– _______________ to be added– modifications to __________ records on old master– orders for deletions of records on the old master
• Possible errors– Adding => record for specified ID __________
exists– Modify => record does not exist– _____________ => record does not exist
335
Program Flow ChartOpen files, read 1st records
Trans key > OM key
Write OM record to NM file, Trans key yet to be matched
Trans key = = OM key
Compare keys
Trans Key < OM key
Type of Trans Type of
Trans
Add OK Other, Error
Other, Error
Modify, Make changes
Del, go on
336
Sequential U
pdate
337
Sequential Update
Transaction File Old Master New Master
10 M20 M25 I30 D35 D40 A50 M55 M80 M
102030405060708090100
338
Random-Access Files
• “Instant-access” applications– Record must be located ______________– Transaction-processing systems require rapid
access
• Random-access files– Access individual records directly and quickly– Use _______________ for every record
• Easy to calculate record locations
– Insert records without ______________ other data in file
339
Java's View of Random-Access File
340
Creating a Random-Access File
• RandomAccessFile objects– Like DataInputStream and DataOutputstream
– Reads or writes data in spot specified by file-position pointer
• Manipulates all data as ____________________• Normally writes one ______________ at a time to file
• Note Figure 17.12, a new class derived from AccountRecord
341
Creating a Random-Access File
• RandomAccessAccountRecord of Figure 17.12 adds features– Two ________________________– Routine to read a record– Routine to _______________ a record
• These will be used in the application to create a Random file, Figure 17.13– Window to name and open the new file– Program generates 100 empty records
342
Writing Data Random-Access File
• Figure 17.14– Opens the file previously created– First window has ______________ button, Open
dialog box appears– Uses BankUI graphical interface– Click _______________ button to save the record
• RandomAccessFile method ____________– Determines location in file where record is stored– Sets file-position pointer to a specific point in file
343
Reading from Random-Access File
• Read through random-access file, Figure 17.15– Opens the RandomAccessFile, specify file name
with Open file dialog box– Record displayed in BankUI window– Click on _____________ button to view next record– _________________ combination handles end of
file
344
Transaction-Processing Program
• Substantial transaction-processing system, Figure 17.21 class with methods for – Uses random-access file– Updates, adds and deletes accounts
• Note– Creation of ________________ object– Handling of action buttons– Creating new records– Updating, deleting records– __________________ records in text fields
345
Transaction-Processing Program
• FileEditor program, Figure 17.22• Uses the TransactionProcessor class• Features
– Create RandomAccessFile from name provided– Position ______________________– Read, edit, – Reposition file pointer, update record– Delete record by ____________________