Java Introduction
Java Introduction
Java Programming
Chapter 1
An Overview of Computers and Programming Languages
Java Programming 2
Chapter Objectives
Learn about different types of computers Explore the hardware and software components of a computer system Learn about the language of a computer Learn about the evolution of programming languages Examine high-level programming languages
Java Programming 3
Introduction
Computers have greatly affected our daily lives helping us complete many tasks Computer programs (software) are designed specifically for each task Software is created with programming languages Java is an example of a programming language
Java Programming 5
Java Programming
In 1946, ENIAC (Electronic Numerical Integrator and Calculator) was built at the University of Pennsylvania
Contained 18,000 vacuum tubes and weighed some 30 tons
Java Programming 8
Java Programming
11
Java Programming
12
Java Programming
13
Java Programming
14
Java Programming
15
Main Memory
Ordered sequence of cells (memory cells) Directly connected to CPU All programs must be brought into main memory before execution When power is turned off, everything in main memory is lost
Java Programming
16
Secondary Storage
Provides permanent storage for information Examples of secondary storage:
Hard disks Floppy disks Flash memory ZIP disks CD-ROMs Tapes
17
Java Programming
Input Devices
Definition: devices that feed data and computer programs into computers Examples
Keyboard Mouse Secondary storage
Java Programming
18
Output Devices
Definition: devices that the computer uses to display results Examples
Printer Monitor Secondary storage
Java Programming
19
Input/Output Devices
20
Software
Software consists of programs written to perform specific tasks Two types of programs
System programs Application programs
Java Programming
21
System Programs
System programs control the computer The operating system is first to load when you turn on a computer
Java Programming
22
Java Programming
Application Programs
Written using programming languages Perform a specific task Run by the OS Example programs
Word processors Spreadsheets Games
Java Programming 24
Language of a Computer
Machine language: the most basic language of a computer A sequence of 0s and 1s Every computer directly understands its own machine language A bit is a binary digit, 0 or 1 A byte is a sequence of eight bits
Java Programming 25
Java Programming
26
Java Programming
28
Java Programming
Java Programming
30
A Java Program
Output:
Java Programming
32
Java Programming
33
Java Programming
34
Problem-Analysis-CodingExecution Cycle
Algorithm: a step-by-step problem-solving process in which a solution is arrived at in a finite amount of time
38
Problem-Solving Process
1. Analyze the problem and outline the problem and its solution requirements 2. Design an algorithm to solve the problem 3. Implement the algorithm in a programming language, such as Java 4. Verify that the algorithm works 5. Maintain the program by using and improving it and modifying it if the problem domain changes
Java Programming 39
Java Programming
40
Programming Methodologies
Two basic approaches to programming design
Structured design Object-oriented design
Java Programming
41
Structured Design
1. A problem is divided into smaller subproblems 2. Each subproblem is solved 3. The solutions of all subproblems are then combined to solve the problem
Java Programming
42
In OOD, a program is a collection of interacting objects An object consists of data and operations Steps in OOD
1. Identify objects 2. Form the basis of the solution 3. Determine how these objects interact
Java Programming
43
Chapter Summary
A computer system is made up of hardware and software components Computers understand machine language; it is easiest for programmers to write in high-level languages A compiler translates high-level language into machine language Java steps to execute a program: edit, compile, load, and execute
Java Programming 44
Java Programming
Chapter Objectives
Become familiar with the basic components of a Java program, including methods, special symbols, and identifiers Explore primitive data types Discover how to use arithmetic operators Examine how a program evaluates arithmetic expressions Explore how mixed expressions are evaluated
Java Programming 47
Java Programming
48
Java Programming
49
Introduction
Computer program: a sequence of statements whose objective is to accomplish a task Programming: process of planning and creating a program
Java Programming
50
A Java Program
Sample Run:
Java Programming
51
52
Special Symbols
Java Programming
53
Java Programming
54
Java Identifiers
Names of things Consist of:
Letters Digits The underscore character (_) The dollar sign ($)
Illegal Identifiers
Java Programming
56
Data Types
Data type: set of values together with a set of operations
Java Programming
57
Java Programming
58
Java Programming
59
Java Programming
60
Java Programming
61
Literals (Constants)
Integer literals, integer constants, or integers: 23 and -67 Floating-point literals, floating-point constants, floating-point numbers: 12.34 and 25.60 Character literals, character constants, or characters: 'a' and '5'
Java Programming Programming: From Problem Analysis to Program Design, 4e 62
Unary operator: operator that has one operand Binary operator: operator that has two operands
Java Programming
63
Order of Precedence
1. * 2. +
/
-
Operators in 1 have a higher precedence than operators in 2 When operators have the same level of precedence, operations are performed from left to right
64
Java Programming
Expressions
Integral expressions Floating-point or decimal expressions Mixed expressions
Java Programming
65
Integral Expressions
All operands are integers Examples
2 + 3 * 5 3 + x y / 7 x + 2 * (y z) + 18
Java Programming
66
Floating-Point Expressions
All operands are floating-point numbers Examples 12.8 * 17.5 34.50 x * 10.5 + y - 16.2
Java Programming
67
Mixed Expressions
Operands of different types Examples 2 + 3.5 6 / 4 + 3.9 Integer operands yield an integer result; floatingpoint numbers yield floating-point results If both types of operands are present, the result is a floating-point number Precedence rules are followed
Java Programming 68
In this statement, because of the parentheses, you first evaluate num1 + num2
Because num1 and num2 are both int variables, num1 + num2 = 12 + 26 = 38 After this statement executes, the string assigned to str is:
"The sum = 38";
Java Programming 72
Input
Named constant
Cannot be changed during program execution Declared by using the reserved word final Initialized when it is declared
Example 2-11
double CENTIMETERS_PER_INCH = 2.54; int NO_OF_STUDENTS = 20; char BLANK = ' '; double PAY_RATE = 15.75;
73
Java Programming
Input (continued)
Variable (name, value, data type, size)
Content may change during program execution Must be declared before it can be used May not be automatically initialized If new value is assigned, old one is destroyed Value can only be changed by an assignment statement or an input (read) statement
Example 2-12
amountDue; counter; ch; num1, num2;
74
Java Programming
Input (continued)
The assignment statement
variable = expression;
Example 2-13
int num1; int num2; double sale; char first; String str; num1 = 4; num2 = 4 * 5 - 11; sale = 0.02 * 1000; first = 'D'; str = "It is a sunny day.";
Java Programming 75
Input (continued)
Example 2-14
1. num1 2. num1 3. num2 4. num3 5. num3 = = = = = 18; num1 + 27; num1; num2 / 5; num3 / 4;
76
Input (continued)
77
Input (continued)
78
Input (continued)
Standard input stream object: System.in
To read data:
1. Create an input stream object of the class Scanner 2. Use the methods such as next, nextLine, nextInt, and nextDouble
Java Programming 79
Input (continued)
static Scanner console = new Scanner(System.in);
Example 2-16
//Line 1 //Line 2
80
Output
Standard output object: System.out Methods
print println
Syntax
System.out.print(stringExp); System.out.println(stringExp); System.out.println();
Java Programming 82
Java Programming
83
Java Programming
84
import Statement
Used to import the components of a package into a program Reserved word import java.io.*;
Imports the (components of the) package java.io into the program
Java Programming
86
Java Programming
variable *= expression;
Similarly,
variable += expression;
Java Programming
88
Programming Examples
Convert Length program
Input: length in feet and inches Output: equivalent length in centimeters
Chapter Summary
Basic Elements of a Java program include:
The main method Reserved words Special symbols Identifiers Data types Expressions Input Output Statements
90
Java Programming
Java Programming
91
Java Programming
Chapter Objectives
Learn about objects and reference variables Explore how to use predefined methods in a program Become familiar with the class String
Learn how to use input and output dialog boxes in a program
Java Programming
93
Java Programming
94
Java Programming
95
Java Programming
96
97
Java Programming
98
Java Programming
99
Java Programming
102
Java Programming
103
Similar Statements
name = new String("Lisa Johnson"); name = "Lisa Johnson";
Java Programming
104
Java Programming
105
106
Java Programming
107
Java Programming
108
Java Programming
109
Java Programming
110
111
Input/Output
Input data Format output Output results Format output Read from and write to files
Java Programming
112
Java Programming
114
The option flags is a set of characters that modify the output format The option width is a (decimal) integer indicating the minimum number of characters to be written to the output
Java Programming 118
Java Programming
119
Java Programming
120
Java Programming
121
Java Programming
122
Java Programming
123
Java Programming
124
Syntax
str = JOptionPane.showInputDialog(strExpression)
Java Programming
127
Java Programming
128
JOptionPane Example
Java Programming
129
Java Programming
130
File Input/Output
File: area in secondary storage used to hold information You can also initialize a Scanner object to input sources other than the standard input device by passing an appropriate argument in place of the object System.in We make use of the class FileReader
Java Programming
131
Java Programming
132
Java Programming
133
Java Programming
134
Java Programming
135
Java Programming
137
This statement creates the PrintWriter object outFile and associates it with the file prog.out You can now use the methods print, println, and printf with outFile just the same way they have been used with the object System.out
Java Programming 138
Java Programming
139
throws Clause
During program execution, various things can happen; for example, division by zero or inputting a letter for a number In such cases, we say that an exception has occurred If an exception occurs in a method, the method should either handle the exception or throw it for the calling environment to handle If an input file does not exist, the program throws a FileNotFoundException
Java Programming 141
Java Programming
143
Java Programming
144
Java Programming
146
Chapter Summary
Primitive type variables store data into their memory space Reference variables store the address of the object containing the data An object is an instance of a class
Java Programming
148
Java Programming
Chapter 4 Control Structures I: Selection
Chapter Objectives
Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean) expressions Learn how to use the selection control structures if, ifelse, and switch in a program
Java Programming 152
Control Structures
Three methods of processing a program
In sequence Branching Looping
Branch: altering the flow of program execution by making a selection or choice Loop: altering the flow of program execution by repetition of statement(s)
Java Programming 153
Flow of Execution
Java Programming
154
Relational Operators
Relational operator
Allows you to make comparisons in a program Binary operator
Condition is represented by a logical expression in Java Logical expression: expression that has a value of either true or false
Java Programming 155
Java Programming
156
Java Programming
157
158
159
Java Programming
160
Java Programming
161
Java Programming
162
Java Programming
163
Java Programming
164
Precedence of Operators
Java Programming
165
166
Short-Circuit Evaluation
Definition: a process in which the computer evaluates a logical expression from left to right and stops as soon as the value of the expression is known
Java Programming
167
Selection
One-way selection Two-way selection Compound (block of) statements Multiple selections (nested if) Conditional operator switch structures
Java Programming 168
One-Way Selection
Syntax
if (expression) statement
Java Programming
169
Java Programming
170
//Line 4 //Line 5
JOptionPane.showMessageDialog(null, "The absolute value of " + temp + " is " + number, "Absolute Value", JOptionPane.INFORMATION_MESSAGE); //Line 6 System.exit(0); }
Java Programming
172
Two-Way Selection
Syntax if (expression) statement1 else statement2 else statement must be paired with an if
Java Programming 173
Java Programming
174
Java Programming
175
Because a semicolon follows the closing parenthesis of the if statement (Line 1), the else statement stands alone The semicolon at the end of the if statement (see Line 1) ends the if statement, so the statement at Line 2 separates the else clause from the if statement; that is, else is by itself Since there is no separate else statement in Java, this code generates a syntax error
Java Programming 176
Java Programming
177
Java Programming
178
Else associated with most recent incomplete if Multiple if statements can be used in place of ifelse statements May take longer to evaluate
179
Java Programming
Conditional (? :) Operator
Ternary operator Syntax
expression1 ? expression2 : expression3
If expression1 = true, then the result of the condition is expression 2; otherwise, the result of the condition is expression 3
Java Programming
180
switch Structures
Java Programming
181
183
184
Java Programming
185
Java Programming
186
Java Programming
187
Java Programming
188
Java Programming
190
Comparing Strings
class String Method compareTo Method equals
Java Programming
192
Java Programming
193
Java Programming
194
Chapter Summary
Control structures are used to process programs Logical expressions and order of precedence of operators are used in expressions If statements ifelse statements switch structures Proper syntax for using control statements Compare strings
Java Programming 195
Java Programming
Chapter Objectives
Learn about repetition (looping) control structures Explore how to construct and use countcontrolled, sentinel-controlled, flag-controlled, and EOF-controlled repetition structures Examine break and continue statements Discover how to form and use nested control structures
Java Programming
197
Java Programming
198
Expression is always true in an infinite loop Statements must change value of expression to false
Java Programming
199
Java Programming
200
Output:
0 5 10 15 20
Java Programming 201
Java Programming
202
Java Programming
203
Java Programming
204
Java Programming
205
The expression console.hasNext() evaluates to true if there is an input in the input stream; otherwise it returns false Expressions such as console.nextInt() act as the loop condition A general form of the EOF-controlled while loop that uses the Scanner object console to input data is of the form:
Java Programming
207
Java Programming
208
209
Input: first two Fibonacci numbers in sequence, position in sequence of desired Fibonacci number (n)
int previous1 = Fibonacci number 1 int previous2 = Fibonacci number 2 int nthFibonacci = position of nth Fibonacci number
Java Programming
212
Java Programming
213
Java Programming
214
Java Programming
215
Java Programming
218
219
Java Programming
220
222
Statements executed first, and then logical expression evaluated Statement(s) executed at least once and then continued if logical expression is true
Java Programming 223
Java Programming
224
225
If you do not know and the program cannot determine in advance the number of repetitions needed, and it is at least one, the do...while loop is the right choice
226
break Statements
Used to exit early from a loop Used to skip remainder of switch structure Can be placed within if statement of a loop
If condition is met, loop exited immediately
Java Programming
227
continue Statements
Used in while, for, and do...while structures When executed in a loop, the remaining statements in the loop are skipped; proceeds with the next iteration of the loop When executed in a while/dowhile structure, expression evaluated immediately after continue statement In a for structure, the update expression is executed after the continue statement; then the loop condition executes
Java Programming 228
Java Programming
229
Output:
* ** *** **** *****
Java Programming 230
Chapter Summary
Looping Mechanisms
Counter-controlled while loop Sentinel-controlled while loop Flag-controlled while loop EOF-controlled while loop for loop dowhile loop
Java Programming
Chapter Objectives
Learn about basic GUI components Explore how the GUI components JFrame, JLabel, JTextField, and JButton work Become familiar with the concept of eventdriven programming
Java Programming
233
Java Programming
234
Java Programming
235
Java Programming
236
Java Programming
237
GUI Components
Added to content pane of window Not added to window itself Pixel: picture element
Java Programming
238
Windows
Can be created using a JFrame object The class JFrame provides various methods to control attributes of a window Measured in pixels of height and width Attributes associated with windows
Title Width Height
Java Programming 239
class JFrame
GUI window instance created as instance of JFrame
Provides various methods to control window attributes
Java Programming
240
Java Programming
241
Java Programming
242
Second way
Create class containing application program by extending definition of class JFrame Utilizes mechanism of inheritance
Java Programming 243
Content Pane
Inner area of GUI window (below title bar, inside border) To access content pane:
Declare reference variable of type Container Use method getContentPane of class JFrame
Java Programming
244
Java Programming
245
class JLabel
Labels: objects of particular class type class JLabel: used to create labels Label attributes
Title Width Height
To create a label:
Instantiate object of type JLabel Modify attributes to control display of labels
Java Programming 246
Java Programming
247
class JTextField
Text fields: objects belonging to class JTextField
To create text field:
Declare reference variable of type JTextField Instantiate object
Java Programming
248
Java Programming
249
Java Programming
250
class JButton
Provided to create buttons in Java To create button:
Same technique as creating JLabel and JTextField
Java Programming
251
Java Programming
252
Handling an Event
Action event: event created when JButton is clicked
Event listener: object that receives message when JButton is clicked In Java, you must register the listener
Java Programming
253
Java Programming
254
Java Programming
255
Java Programming
256
Java Programming
257
Java Programming
258
Object-Oriented Design
Simplified methodology
1. Write down detailed description of problem 2. Identify all (relevant) nouns and verbs 3. From list of nouns, select objects 4. Identify data components of each object 5. From list of verbs, select operations
Java Programming
259
Nouns
Length, width, rectangle, perimeter, area
Java Programming
260
Java Programming
261
Java Programming
264
Java Programming
265
Java Programming
267
Java Programming
268
Java Programming
269
Java Programming
270
The expression:
num = 25; is referred to as autoboxing of the int type
Java Programming 271
x = num;
This statement is equivalent to the statement:
x = num.intValue();
This statement is referred to as auto-unboxing of the int type
Java Programming
272
If you want to compare the values of two Integer objects only for equality, then you can use the method equals
Java Programming
273
Java Programming
274
Java Programming
275
Chapter Summary
Every GUI contains a window Various components are added to content pane of window class JFrame is used to create windows JLabel is used to label GUI components and display information to user JTextFiled is used for input/output JButton generates action event
Action event is sent to action listener
Java Programming 276
Java Programming
Chapter Objectives
Understand how methods are used in Java programming Learn about standard (predefined) methods and discover how to use them in a program Learn about user-defined methods Examine value-returning methods, including actual and formal parameters
Java Programming 279
Predefined Classes
Methods already written and provided by Java Organized as a collection of classes (class libraries) To use: import package Method type: data type of value returned by method
Java Programming 281
Java Programming
282
Java Programming
283
Java Programming
284
Java Programming
285
Java Programming
286
Java Programming
287
Java Programming
288
Java Programming
289
User-Defined Methods
Value-returning methods
Used in expressions Calculate and return a value Can save value for later calculation or print value
modifiers: public, private, protected, static, abstract, final returnType: type of the value that the method calculates and returns (using return statement) methodName: Java identifier; name of method
Java Programming 290
Syntax
Syntax: formal parameter list
-The syntax of the formal parameter list is:
Method call
-The syntax to call a value-returning method is:
Java Programming
291
Syntax (continued)
Syntax: actual parameter list
-The syntax of the actual parameter list is:
return expr;
Java Programming 292
}
Java Programming 293
294
295
Java Programming
296
Java Programming
297
298
Palindrome Number
Palindrome: integer or string that reads the same forwards and backwards The method isPalindrome takes a string as a parameter and returns true if the string is a palindrome, false otherwise
Java Programming
299
}
Java Programming 300
Flow of Execution
Execution always begins with the first statement in the method main User-defined methods execute only when called Call to method transfers control from caller to called method In method call statement, specify only actual parameters, not data type or method type Control goes back to caller when method exits
Java Programming 301
Java Programming
304
Void Methods
Similar in structure to value-returning methods Call to method is always stand-alone statement Can use return statement to exit method early
Java Programming
305
Java Programming
306
Java Programming
307
Java Programming
309
Java Programming
310
Java Programming
311
Java Programming
312
Java Programming
313
Java Programming
314
315
316
317
Java Programming
318
The class StringBuffer contains the method append, which allows you to append a string to an existing string, and the method delete, which allows you to delete all the characters of the string The assignment operator cannot be used with StringBuffer variables; you must use the operator new (initially) to allocate memory space for a string
Java Programming
319
320
321
322
323
324
The class Integer does not provide a method to change the value of an existing Integer object The same is true of other wrapper classes
Java Programming 325
Java does not provide any class that wraps primitive type values in objects and when passed as parameters changes their values
If a method returns only one value of a primitive type, then you can write a value-returning method If you encounter a situation that requires you to write a method that needs to pass more than one value of a primitive type, then you should design your own classes
Appendix D provides the definitions of such classes and shows how to use them in a program
Java Programming Programming: From Problem Analysis to Program Design, 4e 326
Within a class, outside of every method definition (and every block), an identifier can be declared anywhere
Java Programming
328
Java Programming
329
...
} }
Java Programming
330
Scope Rules
Scope rules of an identifier declared within a class and accessed within a method (block) of the class An identifier, say X, declared within a method (block) is accessible:
Only within the block from the point at which it is declared until the end of the block By those blocks that are nested within that block
Java Programming
331
Java Programming
332
static final double rate = 10.50; static int z; static double t; public static void main(String[] args) { int num; double x, z; char ch; //... } public static void one(int x, char y) { //... }
Java Programming 333
}
}
Java Programming 334
Java Programming
335
Java Programming
336
Method Overloading
public public public public void methodOne(int x) void methodTwo(int x, double y) void methodThree(double y, int x) int methodFour(char ch, int x, double y) public int methodFive(char ch, int x, String name)
The methods methodSix and methodSeven both have three formal parameters and the data type of the corresponding parameters is the same These methods all have the same formal parameter lists
Java Programming 339
Java Programming
341
Both these method headings have the same name and same formal parameter list These method headings to overload the method methodABC are incorrect
ENG
HIS MTH PHY
1 2
1 2 1 2 1 2
82.00 78.20
77.69 84.15 83.57 84.29 83.22 82.60
Java Programming
345
Chapter Summary
Predefined methods User-defined methods
Value-returning methods Void methods Formal parameters Actual parameters
Flow of Execution
Java Programming 346
Java Programming
Java provides the classes Integer, Double, Character, Long, and Float so that the values of the primitive data types can be treated as objects
These classes have limitations
You can create objects of the type, say Integer, to store int values, but you cannot change the values stored in the objects
You can create objects of type IntClass and/or change the values of the objects
349
350
351
352
353
354
356
357
358
359
360
361
num1 = 10;
//Line 5
362
num1 = 10; //Line 5 num2.setNum(15); //Line 6 ch = 'A'; //Line 7 str = new StringBuffer("Sunny"); //Line 8
363
364
num = b.getNum();
//Line 14
365
366
367
368
369
370
371
372
373
Java Programming
Chapter Objectives
Learn about classes Learn about private, protected, public, and static members of a class Explore how classes are implemented Learn about the various operations on classes
Java Programming
375
Java Programming
376
Classes
} public String concat(String str) { //code to join two strings } public String toLowerCase() {
//code to convert all the characters of a //string to lowercase
} ... }
Java Programming 377
Classes (continued)
class: reserved word; collection of a fixed number of components Components: members of a class Members accessed by name Class categories/modifiers
private protected public
Java Programming 378
Classes (continued)
private: members of class are not accessible outside class public: members of class are accessible outside class Class members: can be methods or variables Variable members declared like any other variables
Java Programming 379
Syntax
The general syntax for defining a class is:
Java Programming
380
Syntax (continued)
If a member of a class is a named constant, you declare it just like any other named constant If a member of a class is a variable, you declare it just like any other variable If a member of a class is a method, you define it just like any other method
Java Programming
381
Syntax (continued)
If a member of a class is a method, it can (directly) access any member of the classdata members and methods - Therefore, when you write the definition of a
method (of the class), you can directly access any data member of the class (without passing it as a parameter)
Java Programming
382
class Clock:
Data Members (Instance Variables)
private int hr; //store hours private int min; //store minutes private int sec; //store seconds
Java Programming
383
Constructors
Two types of constructors
- With parameters - Without parameters (default constructor)
Java Programming
385
Constructors (continued)
Constructors have the following properties:
- The name of a constructor is the same as the name of the class - A constructor, even though it is a method, has no type - A class can have more than one constructor; all constructors of a class have the same name - If a class has more than one constructor, any two constructors must have different signatures - Constructors are automatically executed when a class object is instantiated - If there are multiple constructors, which constructor executes depends on the type of values passed to the class object when the class object is instantiated
Java Programming 386
Java Programming
387
Java Programming
388
or:
Clock myClock; Clock yourClock;
myClock = new Clock(); yourClock = new Clock(9, 35, 15);
Java Programming 389
Java Programming
390
Java Programming
391
myClock = yourClock;
Copies the value of the reference variable yourClock into the reference variable myClock
- After this statement executes, both yourClock and myClock refer to the same object
Java Programming 393
Shallow copying: two or more reference variables of the same type point to the same object Deep copying: each reference variable refers to its own object
Java Programming 394
Java Programming
395
Java Programming
396
Java Programming
397
Java Programming
398
Java Programming
399
Java Programming
400
Java Programming
401
Java Programming
402
Java Programming
403
Java Programming
404
Java Programming
405
Java Programming
406
Java Programming
407
Default Constructor
or
Java Programming
408
or
Java Programming
409
Java Programming
411
Java Programming
412
Java Programming
413
x = a;
}
y++;
}
}
Java Programming
417
Java Programming
418
Finalizers
Automatically execute when class object goes out of scope Have no parameters Only one finalizer per class Name of finalizer: finalize
Java Programming
419
Java Programming
420
Java Programming
421
Inner Classes
Defined within other classes Can be either a complete class definition or anonymous inner class definition Used to handle events
Java Programming
422
Java Programming
423
Write a two-part program to create a Java application program for this candy machine so that it can be put into operation
- In the first part, design a non-GUI application program - In the second part, design an application program that will create a GUI as described in the second part
Java Programming 424
Java Programming
426
Java Programming
427
Java Programming
428
Java Programming
429
Java Programming
430
Java Programming
431
Java Programming
432
Java Programming
433
Chapter Summary
Creating classes Members of a class
private protected public static
Java Programming
435
Java Programming
Chapter 9 Arrays
Chapter Objectives
Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of array index out of bounds Become familiar with the restrictions on array processing
Java Programming 437
Java Programming
438
Array
Definition: structured data type with a fixed number of elements Elements of an array are also called components of the array Every element is of the same type Elements are accessed using their relative positions in the array
Java Programming 439
One-Dimensional Arrays
Java Programming
440
Java Programming
441
Java Programming
442
Arrays
Array num: int[] num = new int[5];
Java Programming
443
Arrays (continued)
Array num: int[] num = new int[5];
Java Programming
444
Array List
Java Programming
445
Java Programming
446
Java Programming
447
Java Programming
448
Java Programming
449
Java Programming
450
Java Programming
451
Java Programming
452
This statement creates the array numList of 10 components and initializes each component to 0
Java Programming 453
These statements store 5, 10, 15, and 20, respectively, in the first four components of numList You can store the number of filled elements, that is, the actual number of elements, in the array in a variable, say numOfElement It is a common practice for a program to keep track of the number of filled elements in an array
Java Programming 454
for (i = 0; i < list.length; i++) list[i] = console.nextInt(); for (i = 0; i < list.length; i++) System.out.print(list[i] + " ");
Java Programming 455
Arrays (continued)
Some operations on arrays
Initialize Input data Output stored data Find largest/smallest/sum/average of elements
double[] sales = new double[10]; int index; double largestSale, sum, average;
Java Programming
456
Java Programming
457
Java Programming
458
Java Programming
459
Java Programming
460
Java Programming
461
Java Programming
462
Java Programming
463
If index < 0 or index > arraySize: ArrayIndexOutOfBoundsException exception is thrown Base address: memory location of first component in array
Java Programming 464
Java Programming
466
Java Programming
467
Java Programming
468
areEqualArrays(int[] firstArray,
int[] secondArray)
Java Programming
471
Java Programming
472
Java Programming
473
Java Programming
474
Java Programming
475
Suppose that you want to determine whether 27 is in the list; First you compare 27 with list[0] Because list[0] 27, you then compare 27 with list[1] Because list[1] 27, you compare 27 with list[2]; Because list[2] = 27, the search stops This search is successful
Java Programming 476
Search for 10 Search starts at the first element in the list, that is, at list[0] This time, the search item, which is 10, is compared with every item in the list; eventually, no more data is left in the list to compare with the search item; this is an unsuccessful search
Java Programming 477
public static int seqSearch(int[] list, int listLength, int searchItem) { int loc; boolean found = false; loc = 0; while (loc < listLength && !found) if (list[loc] == searchItem) found = true; else loc++; if (found) return loc; else return -1;
}
Java Programming 478
Arrays of Objects
Can use arrays to manipulate objects Example: create array named array1 with N objects of type T T[] array1 = new T[N] Can instantiate array1 as follows: for (int j = 0; j <array1.length; j++) array1[j] = new T();
Java Programming
479
Java Programming
480
Java Programming
481
Java Programming
482
Java Programming
483
Java Programming
484
Java Programming
485
Java Programming
486
Java Programming
487
The formal parameter name is of type String, the formal parameter num is of type double, and the formal parameter intList is of variable length The actual parameter corresponding to intList can be an int array or any number of int variables and/or int values
Java Programming 488
foreach Loop
The syntax to use this for loop to process the elements of an array is:
for (dataType identifier : arrayName) statements
identifier is a variable, and the data type of identifier is the same as the data type of the array components
Java Programming
490
The for statement in Line 2 is read: for each num in list The identifier num is initialized to list[0] In the next iteration, the value of num is list[1], and so on
for (double num : numList) { if (max < num) max = num; }
Java Programming 491
Two-Dimensional Arrays
Java Programming
492
Java Programming
493
Java Programming
494
Java Programming
495
Java Programming
496
is 15, the number of columns in the first row matrix[1].length gives the number of columns in the second row, which in this case is 15, and so on
Java Programming 498
Java Programming
499
Java Programming
500
Java Programming
501
Java Programming
502
Java Programming
503
Java Programming
504
Print
for (int row = 0; row < matrix.length; row++) { for (int col = 0; col < matrix[row].length; col++)
System.out.printf("%7d", matrix[row][col]);
System.out.println(); }
Java Programming 505
Sum by Row
for (int row = 0; row < matrix.length; row++) { sum = 0; for (int col = 0; col < matrix[row].length; col++) sum = sum + matrix[row][col];
System.out.println("Sum of row " + (row + 1) + " = "+ sum);
}
Java Programming 506
Java Programming
507
}
Java Programming 508
}
Java Programming 509
Java Programming
510
Java Programming
511
Java Programming
512
Multidimensional Arrays
Can define three-dimensional arrays or n-dimensional array (n can be any number) Syntax to declare and instantiate array dataType[][][] arrayName = new
dataType[intExp1][intExp2][intExpn];
Java Programming
514
Java Programming
515
Value in appropriate index incremented using methods and depending on character read from text
Java Programming 516
Chapter Summary
Arrays
Definition Uses
Different Arrays
One-dimensional Two-dimensional Multidimensional (n-dimensional) Arrays of objects Parallel arrays
517
Java Programming
Java Programming
Chapter Objectives
Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses and subclasses work
Java Programming
520
Java Programming
521
Inheritance
is-a relationship Single inheritance
Subclass is derived from one existing class (superclass)
Multiple inheritance
Subclass is derived from more than one superclass Not supported by Java In Java, a class can only extend the definition of one class
Java Programming 522
Inheritance (continued)
Java Programming
524
Java Programming
525
5. All data members of the superclass are also data members of the subclass
Similarly, the methods of the superclass (unless overridden) are also the methods of the subclass Remember Rule 1 when accessing a member of the superclass in the subclass
Java Programming 526
Inheritance (continued)
To write a methods definition of a subclass, specify a call to the public method of the superclass
If subclass overrides public method of superclass, specify call to public method of superclass: super.MethodName(parameter list) If subclass does not override public method of superclass, specify call to public method of superclass: MethodName(parameter list)
Java Programming 527
Java Programming
528
Java Programming
529
class Box
public String toString() { return super.toString() //retrieve length and width + "; Height = " + height; } public void setDimension(double l, double w, double h) { super.setDimension(l, w); if (h >= 0) height = h; else height = 0; } public double area() { return 2 * (getLength() * getWidth() + getLength() * height + getWidth() * height); }
Java Programming 530
Java Programming
532
Java Programming
533
Java Programming
535
Java Programming
536
Java Programming
537
Java Programming
538
Polymorphism
Java allows us to treat an object of a subclass as an object of its superclass
In other words, a reference variable of a superclass type can point to an object of its subclass
Person name, nameRef; PartTimeEmployee employee, employeeRef; name = new Person("John", "Blair"); employee = new PartTimeEmployee("Susan", "Johnson",
12.50, 45);
nameRef = employee; System.out.println("nameRef: " + nameRef); nameRef: Susan Johnson wages are: $562.5
Java Programming 539
Polymorphism (continued)
Late binding or dynamic binding (run-time binding)
Method executed determined at execution time, not compile time
The term polymorphism means assigning multiple meanings to the same method name In Java, polymorphism is implemented using late binding The reference variable name or nameRef can point to any object of the class Person or the class PartTimeEmployee
Java Programming 540
Polymorphism (continued)
These reference variables have many forms; that is, they are polymorphic reference variables
They can refer to objects of their own class or objects of the classes inherited from their class
You can declare a method of a class final using the key word final; for example, the following method is final:
public final void doSomeThing() { //... }
Java Programming 541
Polymorphism (continued)
If a method of a class is declared final, it cannot be overridden with a new definition in a derived class In a similar manner, you can also declare a class final using the keyword final If a class is declared final, then no other class can be derived from this class Java does not use late binding for methods that are private, marked final, or static
Java Programming 542
Polymorphism (continued)
You cannot automatically make reference variable of subclass type point to object of its superclass Suppose that supRef is a reference variable of a superclass type; moreover, suppose that supRef points to an object of its subclass You can use an appropriate cast operator on supRef and make a reference variable of the subclass point to the object
Java Programming 543
Polymorphism (continued)
On the other hand, if supRef does not point to a subclass object and you use a cast operator on supRef to make a reference variable of the subclass point to the object, then Java will throw a ClassCastExceptionindicating that the class cast is not allowed
Java Programming 544
Polymorphism (continued)
Operator instanceof: determines whether reference variable that points to object is of particular class type
p instanceof BoxShape
This expression evaluates to true if p points to an object of the class BoxShape; otherwise it evaluates to false
Java Programming 545
Abstract Methods
Abstract method: method that has only the heading with no body
Must be declared abstract
public void abstract print(); public abstract object larger(object, object); void abstract insert(int insertItem);
Java Programming 546
Abstract Classes
Abstract class: class that is declared with the reserved word abstract in its heading
An abstract class can contain instance variables, constructors, finalizer, and nonabstract methods An abstract class can contain abstract method(s) If a class contains an abstract method, then the class must be declared abstract You cannot instantiate an object of an abstract class type; you can only declare a reference variable of an abstract class type You can instantiate an object of a subclass of an abstract class, but only if the subclass gives the definitions of all the abstract methods of the superclass
Java Programming 547
Interfaces
Definition: class that contains only abstract methods and/or named constants How Java implements multiple inheritance To be able to handle a variety of events, Java allows a class to implement more than one interface
Java Programming
549
Composition (Aggregation)
Another way to relate two classes One or more members of a class are objects of another class type has-a relation between classes
e.g., every person has a date of birth
Java Programming
552
Java Programming
553
Java Programming
554
Java Programming
555
Java Programming
556
Java Programming
557
Java Programming
Java Programming
560
Chapter Summary
Inheritance
Single and multiple Rules Uses Superclasses/subclasses (objects) Overriding/overloading methods Constructors
Java Programming
Java Programming
Chapter Objectives
Learn what an exception is See how a try/catch block is used to handle exceptions Become aware of the hierarchy of exception classes Learn about checked and unchecked exceptions
Java Programming 564
Java Programming
565
Exception
Definition: an occurrence of an undesirable situation that can be detected during program execution Examples
Division by zero Trying to open an input file that does not exist An array index that goes out of bounds
Java Programming 566
Java Programming
567
try/catch/finally Block
Statements that might generate an exception are placed in a try block The try block might also contain statements that should not be executed if an exception occurs The try block is followed by zero or more catch blocks A catch block specifies the type of exception it can catch and contains an exception handler
Java Programming 570
Java Programming
572
Java Programming
575
Java Programming
577
Java Programming
578
Java Programming
579
Java Programming
580
Java Programming
581
Various exceptions categorized into separate classes and contained in various packages
Java Programming 582
Java Programming
583
Java Programming
584
Java Programming
585
Java Programming
586
Java Programming
587
Java Programming
588
Java Programming
589
Java Programming
590
Java Programming
591
Checked Exceptions
Definition: any exception that can be recognized by the compiler Examples
FileNotFoundExceptions
Java Programming
592
Unchecked Exceptions
Definition: exceptions that cannot be recognized when the program compiles (must be checked for by programmer) Examples
Division by zero Array index out of bounds
The method exceptionMethod throws exceptions of the type InputMismatchException and FileNotFoundException
Java Programming 594
System.out.print("Line 4: Enter the " + "dividend: "); dividend = console.nextInt(); System.out.println(); System.out.print("Line 7: Enter the " + "divisor: "); divisor = console.nextInt(); System.out.println(); quotient = dividend / divisor; System.out.println("Line 11: Quotient = " + quotient);
}
if (eRef instanceof ArithmeticException) System.out.println("Line 14: Exception " + eRef.toString()); else if (eRef instanceof InputMismatchException) System.out.println("Line 16: Exception " + eRef.toString());
}
Java Programming
596
import java.util.*; public class RethrowExceptionExmp1 { static Scanner console = new Scanner(System.in); public static void main(String[] args) { int number; try { number = getNumber(); System.out.println("Line 5: number = " + number); } catch (InputMismatchException imeRef) { System.out.println("Line 7: Exception " + imeRef.toString()); } } } Java Programming
599
Java Programming
601
import java.io.*; public class PrintStackTraceExample1 { public static void main(String[] args) { try { methodA(); } catch (Exception e) { e.printStackTrace(); } }
Java Programming
602
Java Programming
604
Exception-Handling Techniques
Terminate program
Output appropriate error message upon termination
Java Programming
606
Event Handling
Action events
Handled by implementing interface ActionListener
Window events
Handled by implementing interface WindowListener
Mouse events
Handled by implementing interface MouseListener
Key events
Handled by implementing interface KeyListener
Java Programming 608
class MouseAdapter
Implements interface MouseListener with empty bodies to methods
Java Programming
609
Registering Listeners
Registering window listener object to GUI component
Use method addWindowListener Window listener object being registered is passed as parameter to method addWindowListener
Java Programming
611
Java Programming
612
Java Programming
613
Java Programming
614
Chapter Summary
Exception
Definition
Exception
Hierarchy Classes
Java Programming 615
Java Programming
Chapter Objectives
Learn about applets Explore the class Graphics Learn about the class Font Explore the class Color
Java Programming
618
Java Programming
619
Java Programming
620
Java Programming
621
Java Programming
622
Java Programming
623
Java Programming
624
Java Programming
625
Applets
Applet: a Java program that is embedded within a Web page and executed by a Web browser Create an applet by extending the class JApplet class JApplet contained in package javax.swing
Java Programming 626
Java Programming
627
Java Programming
628
Applets (continued)
No main method Methods init, start, and paint guaranteed to be invoked in sequence To develop an applet:
Override any/all of the methods above
Java Programming
629
Applet Methods
init Method
Initializes variables Gets data from user Places various GUI components
paint Method
Performs output
Java Programming
630
Java Programming
631
Java Programming
633
class Font
Shows text in different fonts Contained in package java.awt Available fonts
Serif/SanSerif Monospaced Dialog/DialogInput
Java Programming
635
Java Programming
636
Java Programming
637
class Color
Shows text in different colors Changes background color of component Contained in package java.awt
Java Programming
638
Java Programming
639
Java Programming
640
Java Programming
641
Java Programming
642
Java Programming
643
class Graphics
Provides methods for drawing items such as lines, ovals, and rectangles on the screen Contains methods to set the properties of graphic elements including clipping area, fonts, and colors Contained in the package java.awt
Java Programming
644
Java Programming
645
Java Programming
646
Java Programming
647
Java Programming
648
Java Programming
649
Java Programming
650
Java Programming
651
Java Programming
652
GUI applications
class extends JFrame Invokes main method Uses constructors Uses method setVisible Uses setTitle method Uses method setSize Closes with Exit button
653
Java Programming
655
JTextArea
Can collect multiple lines of input from user Can display multiple lines of output Pressing Enter key separates lines of text Each line ends with newline character \n Derived from class JTextComponent
Java Programming
656
JTextArea (continued)
Java Programming
657
Java Programming
658
JTextArea Example
Java Programming
659
JCheckBox
User selects from predefined values Example of a toggle button Clicking JCheckBox generates item event Use interface ItemListener and its abstract method itemStateChanged to handle event
Java Programming
660
Java Programming
661
Java Programming
662
Java Programming
663
Java Programming
664
JRadioButton
Created same way as check boxes Placed in content pane of applet Forces user to select only one radio button at a time You create a button group to group radio buttons Generates an ItemEvent interface ItemListener and method itemStateChanged used to handle events
Java Programming 665
JRadioButton (continued)
Java Programming
666
JRadioButton (continued)
Java Programming
667
JRadioButton (continued)
Java Programming
668
JRadioButton (continued)
Java Programming
669
JComboBox
Commonly known as a drop-down list Used to select an item from a list of possibilities Generates an ItemEvent Event monitored by ItemListener ItemListener invokes method itemStateChanged
Java Programming 670
Java Programming
671
Java Programming
672
Java Programming
673
Java Programming
674
Java Programming
675
Layout Managers
FlowLayout
Default layout manager Places components from left to right, center by default, until no more items can be placed Can align each line left, center, or right Default alignment: LEFT
GridLayout
Similar to FlowLayout All rows (columns) have same number of components All components have the same size
Java Programming 676
NORTH and SOUTH components extend horizontally (completely span one edge to the other) EAST and WEST components extend vertically between components in NORTH and SOUTH regions CENTER component expands to occupy any unused regions
Java Programming 677
Menus
Allow for various functions without cluttering GUI with too many components Can be attached to objects such as JFrame and JApplet (setJMenuBar method) To set a menu bar:
private JMenuBar menuMB = new JMenuBar(); setJMenuBar(menuMB);
Add menus to menu bar; add menu items to menu Order of menus added = Order of appearance
Java Programming 678
Java Programming
679
Chapter Summary
Creating applets class Font class Graphics class Color Differences between applet and GUI application Converting GUI application to applet
Java Programming 680
Java Programming
Chapter 13 Recursion
Chapter Objectives
Learn about recursive definitions Explore the base case and the general case of a recursive definition Learn about recursive algorithms
Java Programming
683
Java Programming
684
Recursive Definitions
Recursion
Process of solving a problem by reducing it to smaller versions of itself
Recursive definition
Definition in which a problem is expressed in terms of a smaller version of itself Has one or more base cases
Java Programming
685
Java Programming
686
Recursive method
Method that calls itself
Base case
Case in recursive definition in which the solution is obtained directly Stops the recursion
Java Programming 687
General case
Case in recursive definition in which a smaller version of itself is called Must eventually be reduced to a base case
Java Programming
688
Java Programming
689
Java Programming
690
Recursive Definitions
Directly recursive: a method that calls itself Indirectly recursive: a method that calls another method and eventually results in the original method call Tail recursive method: recursive method in which the last statement executed is the recursive call Infinite recursion: the case where every recursive call results in another recursive call
Java Programming 691
Java Programming
692
Java Programming
693
Java Programming
694
Java Programming
695
Java Programming
696
Java Programming
699
Java Programming
700
Recursive Fibonacci
Java Programming
701
Java Programming
703
Java Programming
704
Java Programming
705
Java Programming
706
Recursion or Iteration?
Two ways to solve particular problem
Iteration Recursion
Iterative control structures: use looping to repeat a set of statements Tradeoffs between two options
Sometimes recursive solution is easier Recursive solution is often slower
Java Programming 708
Java Programming
709
Java Programming
710
Java Programming
711
713
Java Programming
714
Chapter Summary
Recursive definitions Recursive algorithms Recursive methods Base cases General cases
Java Programming
715
Java Programming
716