Part 1: Introduction. Course Contents. Goals. Books. Difference between conventional and objectoriented

Size: px
Start display at page:

Download "Part 1: Introduction. Course Contents. Goals. Books. Difference between conventional and objectoriented"

Transcription

1 1 Course Contents 2 Part 1: Introduction Difference between conventional and objectoriented programming Introduction to object-oriented programming with Java lots of Java details aimed at producing and maintaining medium sized software systems. Goals 3 Books 4 Sound knowledge of programming principles Sound knowledge of object-orientation Able to critically assess the quality of small and medium software systems Able to implement a medium-sized software systems in Java Java How to program Deitel & Deitel, Prentice Hall Objects First with Java A Practical Introduction using BlueJ David J. Barnes & Michael Kölling, Pearson Education, 2003 ISBN Object-Oriented Software Construction Bertrand Meyer (Pearson 1997), ISBN

2 Sources for Slides (Acknowledgements) 5 Webpage 6 David J. Barnes & Michael Kölling Sigi Benkner, University of Vienna, Inst. f. Software Science Donald Bell, California State Polytechnic University, Pomona Deitel & Deitel, Prentice Hall T. Fahringer, Inst. of Computer Science, UIBK The course web page is at dps.uibk.ac.at/~tf/lehre/ss04/seii/vorlesung.html There is also a mailing list for this course. Please check them regularly. They will be used for announcements and distribution of material. Course overview (1) 7 Software Engineering 8 Introduction to Computer Introduction to Java Applications Introduction to Java Applets Control Structures Arrays Object Oriented Programming Inheritance Polymorphism Exception Handling and much more Software Engineering should help to reach similar quality levels for large software systems as achieved for classical engineering disciplines. Goals: cost-effective software development high quality meet all time constraints

3 Example: Erroneous Software 22. Juli 1962, Cape Canaveral/Florida: Start of the 1st US Venus satellite Mariner 1. Excerpt of a Fortran program to control the carrier rocket Atlas-Agena B (NASA):... IF (TVAL. LT. 0.2E-2) GOTO 40 DO 40 M = 1, 3 WO = (M-1) *0,5... DO 5 K = 1. 3 T (K) = WO Z = 1.0/(X**2) *B1** E-4*BO**2 D (K) = 3.076E-2*2.0*(1.0/X*BO*B E-4(BO**2-X*BO**2-X*BO*B1))/Z E (K) = H**2* *WO/SIN (WO)*Z H = D (K) E (K) 5 CONTINUE 10 CONTINUE Y = H/WO-1 40 CONTINUE 9 Definition: Software Engineering F.L. Bauer (NATO Konferenz, 1968) The establishment and use of sound engineering principles in order to obtain economically software that is reliable and works efficently on real machines. Standard Glossar IEEE (1983)... Is the systematic approach to the development, operation, maintenance, and retirement of software. 10 Main Task of Software Development 11 Software 12 Development The term software comprises a set of artifacts: programs documents data Quality Assurance Maintenance Management Software products are developed for a certain customer (custom software) or for the general market (generic software).

4 Costs and Complexity of Software 13 Traditional Software Development 14 COST EFFORT LINES OF Products (US million) (Man Year) CODE Lotus V Space Shuttle CitiBank Teller Waterfall model Dominated software development for a long time Widely applied through many different variations Requirement Analysis Design Implementation Test Maintenance A paramount problem of software development is the handling of complexity. Trend towards more and more complex software: Distributed applications (Internet, Grid, Mobile Computing,...) Multimedia Real time applications Main problems: Strict classification of software projects Discrete transition among phases Late discovery of design errors (late design breakage) Late appearance of actual code Risk not to meet requirements Impedance mismatches Impedance mismatches 15 Traditional Software Development (1) 16 Structured Analysis and Design (SA/SD) As Management requested it. As the Project Leader defined it. As Systems designed it. Basis are analysis techniques developed between 1965 u Center: Modeling of processes through functions. Widely applied (conventional software development) Main focus: Implementation and Test Complex maintenance Aufwand As Programming developed it. As Operations installed it. What the user wanted. (Pre-1970 cartoon; origin unknown) Requirement Analysis Design Implementation Test

5 Traditional Software Development (2) Software Errors during Design and Implementation 17 Costs of Error Correction % of errors found before release x Coding 36% 64% Analyse/Design 1, 5-6 x 1 x Defintion Development After release 30% of errors found before release Object-Oriented Software Development At the end of the 80s a change of paradigm in software engineering occurred: object orientation Object-oriented Analysis and Design (OOA/OOD) Based on OO technology (starting in 1985) Object models are central (union of data and process models) centric: analysis and design Simplified maintenance Aufwand 19 Object-oriented versus Procedural Object-oriented Paradigm Data and Operations (Methods) define unit Class Center issue: What Smalltalk, C++, Java,... In contrast: procedural programming Separation of data and methods (procedures) Center issue: How Pascal, C, Fortran, Requirement Analysis Design Implementation Test

6 OOA/OOD versus SA/SD 21 Introduction to Objects 22 Library Information System Object-Oriented A/D Structured A/D Catalog Book Librarian Library OOA/OOD Classification based on concepts (objects) Record Loans System Add Resources Report Fines SA/SD Classification based on processes (functions) What are Objects? The Three Keys to Object Technology Definitions What are Objects? What are Objects? To a child they are something perceptible by one or more of the senses. Real objects are such things as: To an IT professional they are a software packets that abstract important features of a real object. Porsche

7 What are Objects? Real objects are such things as: 25 What are Objects? Real objects are such things as: 26 Los Angeles Alan Kay (Customer) What are Objects? Real objects are such things as: 27 What are Objects? Real objects are such things as: 28 Versateller 1. Things Porsche 2. Places Los Angeles 3. Roles Alan Kay 4. Systems Versateller

8 29 30 What are Objects? Real objects have characteristics: What are Objects? Real objects also have behaviors: 1. Porsches Top Speed 2. Los Angeles Population 3. Customers Balanced Owed 4. Versatellers Amount on Hand 1. Porsches Accelerate 2. Los Angeles Tax 3. Customers Purchase 4. Versatellers Dispense Cash What are Objects? What are Objects? Objekts have characteristics and behavior The Three Keys to Object Technology Porsche Top Speed, Accelerate Los Angeles Population, Tax Alan Kay Amount Owed, Purchase Versateller Amount on Hand, Dispense Cash Key 1 Key2 Key 3 A software object has both characteristics (variables) and behavior (methods) encapsulated in it. Software objects communicate by messages. Software objects can inherit characteristics and behavior just like many real objects.

9 The Three Keys to Object Technology Key one: Characteristics are encapsulated by the objects behavior Greeting Balance 33 The Three Keys to Object Technology Key two: Objects communicate by messages 34 Bank Location Call Bank Call Bank Location Dispense Money $100 The Three Keys to Object Technology Key two (also): Messages are polymorphic (mean different things to different objects) 35 The Three Keys to Object Technology Key three: Objects can be classified into classes 36 triangle.redraw() ellipse.redraw() rectangle.redraw() Classes are a template that is used to manufacture objects (instances) (Note that instance is a synonym of object) Polymorphism means different implementations can be hidden behind a common interface.

10 The Three Keys to Object Technology Key three (also): Classes contain the behavior called methods while the instances contain the characteristics called variables Balance Interest Withdraw 37 The Three Keys to Object Technology Key three (also): Each class can inherit both variables and methods ACCOUNT Account# Balance Open Deposit 38 SAVINGS Minimum Balance Withdrawal CHECKING Service Charge Check The Three Keys to Object Technology Key three (also): 39 Object Definitions 40 Methods and variables can override their parents (CD Deposit overrides Account Deposit) ACCOUNT Account# Balance Open Deposit A software packet that abstracts the salient behavior and characteristics of a real object into a software package that simulates the real object. CD Rate Due Date Renew Deposit SAVINGS Minimum Balance Withdrawal CHECKING Service Charge Check

11 Encapsulation Definitions 41 Message Definitions 42 The containment of the data behind a software membrane consisting of methods. The data can only be accessed through the encapsulated behavior. A signal from a client object requesting services from a server object. The message may contain arguments. The server object may return a response. Class Definitions 43 Instance Definitions 44 A template for defining new object instances. It is sometimes called an object class. The methods reside in the object class. A term used to refer to an actual object. Sometimes called an object instance.

12 Inheritance Definitions A technique to allow classes to use a parent classes methods and data. Inheritance can have many levels 45 Polymorphism Definitions A request handling mechanism that selects a method depending on the message and the target object. Thus the message means different things to different objects. 46 Overriding Definitions 47 Method Definitions 48 Where an overloaded method is chosen from the child class instead of from the parent class. The actual computer code that is encapsulated in the object class.

13 Definitions 49 Summary 50 Subclass A class that has a parent class to inherit from. Object technology is the current modern paradigm OO can enable reuse of system design and coding effort (and consequently save a lot of time and money) Systems built with object technology should be able to be built faster, be more reliable, and be more maintainable Use of object technology requires a different way of thinking than does traditional programming

14 1 1.2 What Is a Computer? 5 Part 2: Introduction to Computers Computer Performs computations and makes logical decisions Millions / billions times faster than human beings Computer programs Sets of instructions for which computer processes data Hardware Physical devices of computer system Software Programs that run on computers Operating System Controls resources (CPU, memory, disc, network) Distributes resources and uses resources as well Interface for programmers 1.3 Computer Organization (1) 6 Computer Organization (2) 7 Six logical units of a computer system Input unit Mouse, keyboard Output unit Printer, monitor, audio speakers Memory unit Retains input and processed information Arithmetic and logic unit (ALU) Performs calculations Central processing unit (CPU) Supervises operation of other devices Secondary storage unit Hard drives, floppy drives Computers have many devices Input/Output Devices memory Processor(s) Monitor Building blocks of a simple PC Bus

15 Computer Architecture Overview (1) 9 Computer Hardware Overview (1) MB 10 GB 20 MB 200 GB 200 GB 1 TB (a) a 3-step pipeline (b) a superscalar CPU memory hierarchy values are estimated 1.4 Evolution of Operating Systems Personal, Distributed and Client/Server Computing 15 Batch processing One job (task) at a time Operating systems developed Programs to make computers more convenient to use Switch jobs easier Multiprogrammed batch systems Multiple jobs share CPU without user interaction Time-sharing Timesharing operating systems User interaction possible Personal computing Computers for personal use Distributed computing Computing performed among several computers Client/server computing Servers offer common store of programs and data Clients access programs and data from server

16 1.6 Machine Languages, Assembly Languages and High-Level Languages Machine language Natural language of computer component Machine dependent Assembly language English-like abbreviations represent computer operations Translator (assembler) converts assembly to machine language High-level language Allows for writing more English-like instructions Contains commonly used mathematical operations Compiler convert to assembly language Interpreter Execute high-level language programs without compilation 16 Swap (int v[], int k) { int temp; kemp = v[k]; V[k] = v[k+1] = temp; } C Compiler Assembler Program Compilation swap: Program in high-level language (e.g.. in C) muli $2, $5,4 add $2, $4, $5 lw $15, 0($2) lw $16, 4($2) lw $16, 0($2) sw $15, 0($2) sw $15, 4($2) jr $ Assembly program (e.g. for MIPS processor) Machine code in binary form (e.g. for MIPS processor) History of Java Java Class Libraries 20 Java Originally developed for intelligent consumer-electronic devices by Sun Microsystems Goals: small, fast, reliable, and portable programs Then used for creating Web pages with dynamic content Now also used for: Developing large-scale enterprise applications Enhancing WWW server functionality Providing applications for consumer devices (cell phones, etc.) Grid computing and Web services Classes Include methods that perform tasks Return information after task completion Used to build Java programs Java contains class libraries Known as Java APIs (Application Programming Interfaces)

17 1.13 Basics of a Typical Java Environment Java programs normally undergo five phases Edit Programmer writes program (and stores program on disk) Compile Compiler creates bytecodes from program Load Class loader stores bytecodes in memory Verify Verifier ensures bytecodes do not violate security requirements Execute Interpreter translates bytecodes into machine language 24 Phase 1 Phase 2 Phase 3 Phase 4 Phase 5 Editor Compiler Class Loader Disk Bytecode Verifier Interpreter Disk Disk Primary Memory.... Primary Memory.... Primary Memory.... Program is created in an editor and stored on disk in a file ending with.java. Compiler creates bytecodes and stores them on disk in a file ending with.class. Class loader reads.class files containing bytecodes from disk and puts those bytecodes in memory. Bytecode verifier confirms that all bytecodes are valid and do not violate Java s security restrictions. Interpreter reads bytecodes and translates them into a language that the computer can understand, possibly storing data values as the program executes. 25 Fig. 1.1 Typical Java environment. The edit-compile-execute cycle 26 Summary 27 editor source file compiler (javac) class file virtual machine (java) Computer: set of hardware resources to process programs Computer programs: set of instructions to conduct applications Hardware: physical devices in a computer Software: all sorts of programs Operating System: controls hardware devices Compiler: translates user readable programs into machine readable programs Interpreter: interprets programs without compilation

18 1 Part 3 Introduction to Java Applications 3 In this chapter 2.1 Introduction Introduce examples to illustrate features of Java Two program styles - applications and applets

19 2.2 A First Program in Java: Printing a Line of Text 4 Application Program that executes using the java interpreter Sample program Show program, then analyze each line 1 // Fig. 2.1: Welcome1.java 2 // Text-printing program. 3 4 public class Welcome1 { 5 6 // main method begins execution of Java application 7 public static void main( String args[] ) 8 { 9 System.out.println( "Welcome to Java Programming!" ); } // end method main } // end class Welcome1 Welcome to Java Programming! Outline Welcome1.java Program Output 5

20 2.2 A First Program in Java: Printing a Line of Text 6 1 // Fig. 2.1: Welcome1.java 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 */ 2 // Text-printing program. Another line of comments Note: line numbers not part of program, added for reference 2.2 A Simple Program: Printing a Line of Text 7 3 Blank line Makes program more readable Blank lines, spaces, and tabs are white-space characters Ignored by compiler 4 public class Welcome1 { Begins class declaration for class Welcome1 Every Java program has at least one user-defined class Keyword: words reserved for use by Java class keyword followed by class name Naming classes: capitalize every word SampleClassName

21 2.2 A Simple Program: Printing a Line of Text 8 4 public class Welcome1 { Name of class called identifier Series of characters consisting of letters, digits, underscores ( _ ) and dollar signs ( $ ) Does not begin with a digit, has no spaces Examples: Welcome1, $value, _value, button7 7button is invalid Java is case sensitive (capitalization matters) a1and A1 are different For chapters 2 to 7, use public keyword Certain details not important now Mimic certain features, discussions later 2.2 A Simple Program: Printing a Line of Text 9 4 public class Welcome1 { Saving files File name must be class name with.java extension Welcome1.java Left brace { Begins body of every class Right brace ends declarations (line 13) 7 public static void main( String args[] ) Part of every Java application Applications begin executing at main Parenthesis indicate main is a method (ch. 6) Java applications contain one or more methods

22 2.2 A Simple Program: Printing a Line of Text 10 7 public static void main( String args[] ) Exactly one method must be called main Methods can perform tasks and return information void means main returns no information For now, mimic main's first line 8 { Left brace begins body of method declaration Ended by right brace } (line 11) 2.2 A Simple Program: Printing a Line of Text 11 9 System.out.println( "Welcome to Java Programming!" ); Instructs computer to perform an action Prints string of characters String - series characters inside double quotes White-spaces in strings 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 Argument inside parenthesis This line known as a statement Statements must end with semicolon ;

23 2.2 A Simple Program: Printing a Line of Text } // end method main Ends method declaration 13 } // end class Welcome1 Ends class declaration Can add comments to keep track of ending braces Remember, compiler ignores comments Comments can start on same line after code 2.2 A Simple Program: Printing a Line of Text 13 Compiling a program Open a command prompt window, go to directory where program is stored Type javac Welcome1.java If no errors, Welcome1.class created Has bytecodes that represent application Bytecodes passed to Java interpreter

24 2.2 A Simple Program: Printing a Line of Text 14 Executing a program Type java Welcome1 Interpreter loads.class file for class Welcome1.class extension omitted from command Interpreter calls method main Fig. 2.2 Executing Welcome1 in a Microsoft Windows 2000 Command Prompt. 2.3 Modifying Our First Java Program 15 Modify example in Fig. 2.1 to print same contents using different code

25 2.3 Modifying Our First Java Program 16 Modifying programs Welcome2.java (Fig. 2.3) produces same output as Welcome1.java (Fig. 2.1) Using different code 9 System.out.print( "Welcome to " ); 10 System.out.println( "Java Programming!" ); Line 9 displays Welcome to with cursor remaining on printed line Line 10 displays Java Programming! on same line with cursor on next line 1 // Fig. 2.3: Welcome2.java 2 // Printing a line of text with multiple statements. 3 4 public class Welcome2 { 5 6 // main method begins execution of Java application 7 public static void main( String args[] ) 8 { 9 System.out.print( "Welcome to " ); 10 System.out.println( "Java Programming!" ); } // end method main } // end class Welcome2 Outline Welcome2.java 1. Comments 2. Blank line 3. Begin class Welcome2 3.1 Method main System.out.print keeps the cursor on the same line, so System.out.println 4. Method continues on the same line. System.out.prin t Method System.out.prin tln Welcome to Java Programming! 5. end main, Welcome2 Program Output

26 Modifying Our First Java Program Newline characters (\n) Interpreted as special characters by methods System.out.print and System.out.println Indicates cursor should be on next line Welcome3.java (Fig. 2.4) 9 System.out.println( "Welcome\nto\nJava\nProgramming!" ); Line breaks at \n Usage Can use in System.out.println or System.out.print to create new lines System.out.println( "Welcome\nto\nJava\nProgramming!" ); 1 // Fig. 2.4: Welcome3.java 2 // Printing multiple lines of text with a single statement. 3 4 public class Welcome3 { 5 6 // main method begins execution of Java application 7 public static void main( String args[] ) 8 { 9 System.out.println( "Welcome\nto\nJava\nProgramming!" ); } // end method main } // end class Welcome3 Outline Welcome3.java 1. main System.out.prin tln (uses \n for new line) Welcome to Java Programming! Program Output Notice how a new line is output for each \n escape sequence.

27 2.3 Modifying Our First Java Program 20 Escape characters Backslash ( \ ) Indicates special characters be output Esc a p e Description se q u e n c e \n Newline. Position the screen cursor at the beginning of the next line. \t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Position the screen cursor at the beginning of the current line; do not advance to the next line. Any characters output after the carriage return overwrite the characters previously output on that line. \\ Backslash. Used to print a backslash character. \" Double quote. Used to print a double-quote character. For example, System.out.println( "\"in quotes\"" ); displays "in quotes" Fig. 2.5 Some common escape sequences. 2.4 Displaying Text in a Dialog Box 21 Display Most Java applications use windows or a dialog box We have used command window Class JOptionPane allows us to use dialog boxes Packages Set of predefined classes for us to use Groups of related classes called packages Group of all packages known as Java class library or Java applications programming interface (Java API) JOptionPane is in the javax.swing package Package has classes for using Graphical User Interfaces (GUIs)

28 Displaying Text in a Dialog Box b utton menu menu bar te xt field Web browsers display Web pages in their own windows programs enable a user to edit and read mails in windows programs display important messages to the user in dialog boxes Displaying Text in a Dialog Box Upcoming program Application that uses dialog boxes Explanation will come afterwards Demonstrate another way to display output Packages, methods and GUI

29 1 1 // // Fig. Fig. 2.6: 2.6: Welcome4.java 2 // Printing multiple lines in a dialog box. 2 // Printing multiple lines in a dialog box 3 4 3// import Java packages javax.swing.joptionpane; // import class JOptionPane 5 4import javax.swing.joptionpane; // program uses JOptionPane public class Welcome4 { public class Welcome4 { 8 6 public static void main( String args] ) 9 // main method begins execution of Java application 7 { 10 public static void main( String args[] ) 11 8 { JOptionPane.showMessageDialog( 12 9 JOptionPane.showMessageDialog( null, "Welcome\nto\nJava\nProgramming!" ); 13 null, "Welcome\nto\nJava\nProgramming!" ); System.exit( 0 ); 0 );// // terminate application the program with window } } // end method main } // end class Welcome4 Outline Welcome4.java 1. import declaration 2. Class Welcome4 2.1 main showmessagedial og 2.3 System.exit Program Output 2.4 Displaying Text in a Dialog Box 25 Lines 1-2: comments as before 4 // Java packages Two groups of packages in Java API Core packages Begin with java Included with Java 2 Software Development Kit Extension packages Begin with javax New Java packages 5 import javax.swing.joptionpane; // program uses OptionPane import declarations Used by compiler to identify and locate classes used in Java programs Tells compiler to load class JOptionPane from javax.swing package

30 Displaying Text in a Dialog Box Lines 6-11: Blank line, begin class Welcome4 and main 12 JOptionPane.showMessageDialog( 13 null, "Welcome\nto\nJava\nProgramming!" ); Call method showmessagedialog of class JOptionPane Requires two arguments Multiple arguments separated by commas (,) For now, first argument always null Second argument is string to display showmessagedialog is a static method of class JOptionPane static methods called using class name, dot (.) then method name Displaying Text in a Dialog Box All statements end with ; A single statement can span multiple lines Cannot split statement in middle of identifier or string Executing lines 12 and 13 displays the dialog box Automatically includes an OK button Hides or dismisses dialog box Title bar has string Message

31 Displaying Text in a Dialog Box 15 System.exit( 0 ); // terminate application with window Calls static method exit of class System Terminates application Use with any application displaying a GUI Because method is static, needs class name and dot (.) Identifiers starting with capital letters usually class names Argument of 0 means application ended successfully Non-zero usually means an error occurred Class System part of package java.lang No import declaration needed java.lang automatically imported in every Java program Lines 17-19: Braces to end Welcome4 and main 2.5 Another Java Application: Adding Integers 29 Upcoming program Use input dialogs to input two values from user Use message dialog to display sum of the two values

32 1 // Fig. 2.9: Addition.java 2 // Addition program that displays the sum of two numbers. 3 4 // Java packages 5 import javax.swing.joptionpane; // program uses JOptionPane 6 7 public class Addition { 8 9 // main method begins execution Declare of Java variables: application name and type. 10 public static void main( String args[] ) 11 { 12 String firstnumber; // first string entered by user 13 String secondnumber; // second string entered by user int number1; // first number to add 16 int number2; // second Input number first integer to add as a String, assign 17 int sum; // sum to of firstnumber. number1 and number // read in first number from user as a String 20 firstnumber = JOptionPane.showInputDialog( "Enter first integer" ); // read in second number from user as a String 23 secondnumber = 24 JOptionPane.showInputDialog( "Enter second integer" ); // convert numbers from type String Add, to type place int result in sum. 27 number1 = Integer.parseInt( firstnumber ); 28 number2 = Integer.parseInt( secondnumber ); // add numbers 31 sum = number1 + number2; 32 Convert strings to integers. Outline Addition.java 1. import 2. class Addition Declare variables (name and type) 3. showinputdialog 4. parseint 5. Add numbers, put result in sum 33 // display result 34 JOptionPane.showMessageDialog( null, "The sum is " + sum, 35 "Results", JOptionPane.PLAIN_MESSAGE ); System.exit( 0 ); // terminate application with window } // end method main } // end class Addition Outline Program output 31

33 2.5 Another Java Application: Adding Integers 32 5 import javax.swing.joptionpane; // program uses JOptionPane Location of JOptionPane for use in the program 7 public class Addition { Begins public class Addition Recall that file name must be Addition.java Lines 10-11: main 12 String firstnumber; // first string entered by user 13 String secondnumber; // second string entered by user Declaration firstnumber and secondnumber are variables 2.5 Another Java Application: Adding Integers String firstnumber; // first string entered by user 13 String secondnumber; // second string entered by user Variables Location in memory that stores a value Declare with name and type before use firstnumber and secondnumber are of type String (package java.lang) Hold strings Variable name: any valid identifier Declarations end with semicolons ; String firstnumber, secondnumber; Can declare multiple variables of the same type at a time Use comma separated list Can add comments to describe purpose of variables

34 2.5 Another Java Application: Adding Integers int number1; // first number to add 16 int number2; // second number to add 17 int sum; // sum of number1 and number2 Declares variables number1, number2, and sum of type int int holds integer values (whole numbers): i.e., 0, -4, 97 Types float and double can hold decimal numbers Type char can hold a single character: i.e., x, $, \n, 7 Primitive types - more in Chapter Another Java Application: Adding Integers firstnumber = JOptionPane.showInputDialog( "Enter first integer" ); Reads String from the user, representing the first number to be added Method JOptionPane.showInputDialog displays the following: Message called a prompt - directs user to perform an action Argument appears as prompt text If wrong type of data entered (non-integer) or click Cancel, error occurs

35 2.5 Another Java Application: Adding Integers firstnumber = JOptionPane.showInputDialog( "Enter first integer" ); Result of call to showinputdialog given to firstnumber using assignment operator = Assignment statement =binary operator - takes two operands Expression on right evaluated and assigned to variable on left Read as: firstnumber gets value of JOptionPane.showInputDialog( "Enter first integer" ) 2.5 Another Java Application: Adding Integers secondnumber = 24 JOptionPane.showInputDialog( "Enter second integer" ); Similar to previous statement Assigns variable secondnumber to second integer input 27 number1 = Integer.parseInt( firstnumber ); 28 number2 = Integer.parseInt( secondnumber ); Method Integer.parseInt Converts String argument into an integer (type int) Class Integer in java.lang Integer returned by Integer.parseInt is assigned to variable number1 (line 27) Remember that number1 was declared as type int Line 28 similar

36 2.5 Another Java Application: Adding Integers sum = number1 + number2; Assignment statement Calculates sum 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 operands 2.5 Another Java Application: Adding Integers JOptionPane.showMessageDialog( null, "The sum is " + sum, 35 "Results", JOptionPane.PLAIN_MESSAGE ); Use showmessagedialog to display results "Thesumis"+sum Uses the operator + to "add" the string literal "The sum is" and sum Concatenation of a String and another type Results in a new string If sum contains 117, then "The sum is "+sumresults in the new string "The sum is 117" Note the space in "The sum is " More on strings in Chapter 11

37 2.5 Another Java Application: Adding Integers JOptionPane.showMessageDialog( null, "The sum is " + sum, 35 "Results", JOptionPane.PLAIN_MESSAGE ); Different version of showmessagedialog Requires four arguments (instead of two as before) First argument: null for now Second: string to display Third: string in title bar Fourth: type of message dialog with icon Line 35 no icon: JOptionPane.PLAIN_MESSAGE 2.5 Another Java Application: Adding Integers 41 M e ssa g e d ia lo g typ e Ic o n Desc ription JOptionPane.ERROR_MESSAGE JOptionPane.INFORMATION_MESSAGE JOptionPane.WARNING_MESSAGE JOptionPane.QUESTION_MESSAGE Displays a dialog that indicates an error to the user. Displays a dialog with an informational message to the user. The user can simply dismiss the dialog. Displays a dialog that warns the user of a potential problem. Displays a dialog that poses a question to the user. This dialog normally requires a response, such as clicking on a Yes or a No button. JOptionPane.PLAIN_MESSAGE no icon Displays a dialog that simply contains a message, with no icon. Fig JOptionPane c o nsta nts fo r m e ssa g e d ia lo g s.

38 42 Variables 2.6 Memory Concepts Every variable has a name, a type, a size and a value Name corresponds to location in memory When new value is placed into a variable, replaces (and destroys) previous value Reading variables from memory does not change them 43 Visual Representation 2.6 Memory Concepts Sum = 0; number1 = 1; number2 = 2; sum 0 Sum = number1 + number2; after execution of statement sum 3

39 Arithmetic Arithmetic calculations used in most programs Usage *for multiplication /for division +, - No operator for exponentiation (more in Chapter 5) Integer division truncates remainder 7 / 5 evaluates to 1 Remainder operator % returns the remainder 7 % 5 evaluates to 2 45 Operator precedence 2.7 Arithmetic Some arithmetic operators act before others (i.e., multiplication before addition) Use parenthesis 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 Follows PEMDAS Parentheses, Exponents, Multiplication, Division, Addition, Subtraction

40 2.7 Arithmetic 46 Operator(s) * / + - Fig Operation(s) Order of evaluation (precedence) Multiplication Evaluated first. If there are several of this type Division of operator, they are evaluated from left to Remainder right. Addition Subtraction Precedence of arithmetic operators. Evaluated next. If there are several of this type of operator, they are evaluated from left to right. 2.8 Decision Making: Equality and Relational Operators 47 ifcontrol statement Simple version in this section, more detail later If a condition is true, then the body of the if statement executed 0interpreted as false, non-zero is true Control always resumes after the if structure Conditions for if statements can be formed using equality or relational operators (next slide) if ( condition ) statement executed if condition true No semicolon needed after condition Else conditional task not performed

41 2.8 Decision Making: Equality and Relational Operators 48 Standard algebraic equality or relational operator Ja va eq ua lity or relational operator Example of Java c ond ition Meaning of Java condition Equality operators = == x == y x is equal to y!= x!= y x is not equal to y Relational operators > > x > y x is greater than y < < x < y x is less than y >= x >= y x is greater than or equal to y <= x <= y x is less than or equal to y Fig Equality and relational operators. Upcoming program uses if statements Discussion afterwards 1 // Fig. 2.20: Comparison.java 2 // Compare integers using if statements, relational operators 3 // and equality operators. 4 5 // Java packages 6 import javax.swing.joptionpane; 7 8 public class Comparison { 9 10 // main method begins execution of Java application 11 public static void main( String args[] ) 12 { 13 String firstnumber; // first string entered by user 14 String secondnumber; // second string entered by user 15 String result; // a string containing the output int number1; // first number to compare 18 int number2; // second number to compare // read first number from user as a string 21 firstnumber = JOptionPane.showInputDialog( "Enter first integer:" ); // read second number from user as a string 24 secondnumber = 25 JOptionPane.showInputDialog( "Enter second integer:" ); // convert numbers from type String to type int 28 number1 = Integer.parseInt( firstnumber ); 29 number2 = Integer.parseInt( secondnumber ); // initialize result to empty String 32 result = ""; 33 Outline 49 Comparison.java 1. import 2. Class Comparison 2.1 main 2.2 Declarations 2.3 Input data (showinputdialo g) 2.4 parseint 2.5 Initialize result

42 34 if ( number1 == number2 ) 35 result = result + number1 + " == " + number2; if ( number1!= number2 ) 38 result = result + number1 + "!= " + number2; if ( number1 < number2 ) 41 result = result + "\n" + number1 + " < " + number2; if ( number1 > number2 ) 44 result = result + "\n" + number1 + " > " + number2; if ( number1 <= number2 ) 47 result = result + "\n" + number1 + " <= " + number2; if ( number1 >= number2 ) 50 result = result + "\n" + number1 + " >= " + number2; // Display results 53 JOptionPane.showMessageDialog( null, result, "Comparison Results", 54 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end method main } // end class Comparison Outline Test for equality, create Comparison.java new string, assign to result. Notice use of JOptionPane.INFORMATION_MESSAGE 3. if statements showmessagedialo g Outline 51 Program Output

43 2.8 Decision Making: Equality and Relational Operators 52 Lines 1-12: Comments, import JOptionPane, begin class Comparison and main Lines 13-18: declare variables Can use comma-separated lists instead: 13 String firstnumber, 14 secondnumber, 15 result; Lines 21-30: obtain user-input numbers and parses input string into integer variables 2.8 Decision Making: Equality and Relational Operators result = ""; Initialize result with empty string 34 if ( number1 == number2 ) 35 result = result + number1 + " == " + number2; ifstatement to test for equality using (==) If variables equal (condition true) result concatenated using + operator result = result + other strings Right side evaluated first, new string assigned to result If variables not equal, statement skipped

44 2.8 Decision Making: Equality and Relational Operators 54 Lines 37-50: other if statements testing for less than, more than, etc. If number1 = 123 and number2 = 123 Line 34 evaluates true (if number1 = = number 2) Because number1 equals number2 Line 40 evaluates false (if number1 < number 2) Because number1 is not less than number2 Line 49 evaluates true (if number1 >= number2) Because number1 is greater than or equal to number2 Lines 53-54: result displayed in a dialog box using showmessagedialog 2.8 Decision Making: Equality and Relational Operators 55 Precedence of operators All operators except for = (assignment) associates from left to right For example: x = y = z is evaluated x = (y = z) Operators Assoc ia tivity Ty p e * / % left to right multiplicative + - left to right additive < <= > >= left to right relational ==!= left to right equality = right to left assignment Fig Pre c e d e nc e a nd a sso c ia tivity o f the o p e ra to rs d isc usse d so fa r.

45 56 Summary Simple Java programs Input/output constructs Dialog boxes Memory concepts and variables Arithmetic, equality and relational operators Precedences and associativity

46 1 Part 4 Introduction to Java Applets 2003 Prentice Hall, Inc. All rights reserved. 3 Applet 3.1 Introduction Program that runs in appletviewer (test utility for applets) Web browser(ie, Communicator) Browser that executes applet is called applet container. Executes when HTML (Hypertext Markup Language) document containing applet is opened and downloaded Applications run in command windows Notes Mimic several features of Chapter 2 to reinforce them Focus on fundamental programming concepts first Explanations will come later

47 3.2 Sample Applets from the Java 2 Software Development Kit 4 Sample Applets Provided in Java 2 Software Development Kit (J2SDK) Source code included (.java files) Study and mimic source code to learn new features All programmers begin by mimicking existing programs Located in demo directory of J2SDK install Can download demos and J2SDK from java.sun.com/j2se/1.4.1/ 3.2 Sample Applets from the Java 2 Software Development Kit 5 Running applets In command prompt, change to demo subdirectory of applet cd c:\j2sdk1.4.1\demo\applets cd appletdirectoryname There will be an HTML file used to execute applet Type appletviewer example1.html appletviewer loads the html file specified as its commandline argument From the HTML file, determines which applet to load (more section 3.3) Applet will run, Reload and Quit commands under Applet menu

48 3.2 Sample Applets from the Java 2 Software Development Kit You start as player "X" 6 Fig. 3.2 Sample execution of applet TicTacToe. 3.2 Sample Applets from the Java 2 Software Development Kit 7 Fig. 3.4 Sample execution of applet DrawTest. Drag the mouse pointer in the white area to draw. Select the drawing color by clicking the circle for the color you want. These GUI components are commonly known as radio buttons. Select the shape to draw by clicking the down arrow, then clicking Lines or Points. This GUI component is commonly known as a combo box, choice or drop-down list.

49 Click a tab to select a twodimensional graphics demo. 3.2 Sample Applets from the Java 2 Software Development Kit Demonstrates 2D drawing capabilities built into Java2 Try changing the options to see their effect on the demonstration Simple Java Applet: Drawing a String Now, create applets of our own Take a while before we can write applets like in the demos Cover many of same techniques Upcoming program Create an applet to display "Welcome to Java Programming!" Show applet and HTML file, then discuss them line by line 9

50 1 // Fig. 3.6: WelcomeApplet.java 2 // A first applet in Java. 3 4 // Java packages 5 import java.awt.graphics; // import class Graphics 6 import javax.swing.japplet; // import class JApplet 7 8 public class WelcomeApplet extends JApplet { 9 10 // draw text on applet s background 11 public void paint( Graphics g ) 12 { 13 // call superclass version of method paint 14 super.paint( g ); // draw a String at x-coordinate 25 and y-coordinate g.drawstring( "Welcome to Java Programming!", 25, 25 ); } // end method paint } // end class WelcomeApplet import allows us to use predefined classes (allowing us to use applets and graphics, in this case). extends allows us to inherit the capabilities of class JApplet. Method paint is guaranteed to be called in all applets. Its first line must be defined as above. Outline Java applet 10 Program Output 2003 Prentice Hall, Inc. All rights reserved. 3.3 Simple Java Applet: Drawing a String 11 1 // Fig. 3.6: WelcomeApplet.java 2 // A first applet in Java. Comments Name of source code and description of applet 5 import java.awt.graphics; // import class Graphics 6 import javax.swing.japplet; // import class JApplet Import predefined classes grouped into packages import declarations tell compiler where to locate classes used When you create applets, import the JApplet class (package javax.swing) import the Graphics class (package java.awt) to draw graphics Can draw lines, rectangles ovals, strings of characters import specifies directory structure

51 3.3 Simple Java Applet: Drawing a String 12 Applets have at least one class declaration (like applications) Rarely create classes from scratch Use pieces of existing classes Inheritance - create new classes from old ones (ch. 9) 8 public class WelcomeApplet extends JApplet { Begins class declaration for class WelcomeApplet Keyword class then class name extends followed by class name Indicates class to extend (JApplet) JApplet : superclass (base class) WelcomeApplet : subclass (derived class) WelcomeApplet now has methods and data of JApplet 3.3 Simple Java Applet: Drawing a String 13 8 public class WelcomeApplet extends JApplet { Class JApplet defined for us Someone else defined "what it means to be an applet" Applets require over 200 methods! extends JApplet Inherit methods, do not have to declare them all Do not need to know every detail of class JApplet

52 3.3 Simple Java Applet: Drawing a String 14 8 public class WelcomeApplet extends JApplet { Class WelcomeApplet is a blueprint appletviewer or browser creates an object of class WelcomeApplet Keyword public required File can only have one public class public class name must be file name 3.3 Simple Java Applet: Drawing a String public void paint( Graphics g ) Our class inherits method paint from JApplet By default, paint has empty body Override (redefine) paint in our class Methods paint, init, and start Guaranteed to be called automatically Our applet gets "free" version of these by inheriting from JApplet Free versions have empty body (do nothing) Every applet does not need all three methods Override the ones you need Applet container draws itself by calling method paint

53 3.3 Simple Java Applet: Drawing a String public void paint( Graphics g ) Method paint Lines are the declaration of paint Draws graphics on screen void indicates paint returns nothing when finishes task Parenthesis define parameter list - where methods receive data to perform tasks Normally, data passed by programmer, as in JOptionPane.showMessageDialog paint gets parameters automatically Graphics object used by paint Mimic paint's first line 3.3 Simple Java Applet: Drawing a String super.paint( g ); Calls version of method paint from superclass JApplet Should be first statement in every applet s paint method 17 g.drawstring( "Welcome to Java Programming!", 25, 25 ); Body of paint Method drawstring (of class Graphics) Called using Graphics object g and dot (.) Method name, then parenthesis with arguments First argument: String to draw Second: x coordinate (in pixels) location Third: y coordinate (in pixels) location Java coordinate system Measured in pixels (picture elements) Upper left is (0,0)

54 Simple Java Applet: Drawing a String Running the applet Compile javac WelcomeApplet.java If no errors, bytecodes stored in WelcomeApplet.class Create an HTML file Loads the applet into appletviewer or a browser Ends in.htm or.html To execute an applet Create an HTML file indicating which applet the browser (or appletviewer) should load and execute Simple Java Applet: Drawing a String 1 <html> 2 <applet code = "WelcomeApplet.class" width = "300" height = "45"> 3 </applet> 4 </html> Simple HTML file (WelcomeApplet.html) Usually in same directory as.class file Remember,.class file created after compilation HTML codes (tags) Usually come in pairs Begin with < and end with > Lines 1 and 4 - begin and end the HTML tags Line 2 - begins <applet> tag Specifies code to use for applet Specifies width and height of display area in pixels Line 3 - ends <applet> tag

55 3.3 Simple Java Applet: Drawing a String 20 1 <html> 2 <applet code = "WelcomeApplet.class" width = "300" height = "45"> 3 </applet> 4 </html> appletviewer only understands <applet> tags Ignores everything else Minimal browser Executing the applet appletviewer WelcomeApplet.html Perform in directory containing.class file 3.3 Simple Java Applet: Drawing a String 21 Running the applet in a Web browser

56 3.4 Drawing Strings and Lines 22 More applets First example Display two lines of text Use drawstring to simulate a new line with two drawstring statements Second example Method g.drawline(x1, y1, x2, y2 ) Draws a line from (x1, y1) to (x2, y2) Remember that (0, 0) is upper left Use drawline to draw a line beneath and above a string 1 // Fig. 3.9: WelcomeApplet2.java 2 // Displaying multiple strings in an applet. 3 4 // Java packages 5 import java.awt.graphics; // import class Graphics 6 import javax.swing.japplet; // import class JApplet 7 8 public class WelcomeApplet2 extends JApplet { 9 10 // draw text on applet s background 11 public void paint( Graphics g ) 12 { 13 // call superclass version of method paint 14 super.paint( g ); // draw two Strings at different locations 17 g.drawstring( "Welcome to", 25, 25 ); 18 g.drawstring( "Java Programming!", 25, 40 ); } // end method paint } // end class WelcomeApplet2 Outline 23 WelcomeApplet2.j ava 1. import 2. Class WelcomeApplet2 (extends JApplet) 3. paint 3.1 drawstring The two drawstring 3.2 drawstring statements simulate a newline. on same In x coordinate, fact, the concept of lines but of 15 text pixels down does not exist when drawing strings Prentice Hall, Inc. All rights reserved.

57 Outline 24 1 <html> 2 <applet code = "WelcomeApplet2.class" width = "300" height = "60"> 3 </applet> 4 </html> HTML file Program Output 2003 Prentice Hall, Inc. All rights reserved. 1 // Fig. 3.11: WelcomeLines.java 2 // Displaying text and lines 3 4 // Java packages 5 import java.awt.graphics; // import class Graphics 6 import javax.swing.japplet; // import class JApplet 7 8 public class WelcomeLines extends JApplet { 9 10 // draw lines and a string on applet s background 11 public void paint( Graphics g ) 12 { 13 // call superclass version of method paint 14 super.paint( g ); // draw horizontal line from (15, 10) to (210, 10) 17 g.drawline( 15, 10, 210, 10 ); // draw horizontal line from (15, 30) to (210, 30) 20 g.drawline( 15, 30, 210, 30 ); // draw String between lines at location (25, 25) 23 g.drawstring( "Welcome to Java Programming!", 25, 25 ); } // end method paint } // end class WelcomeLines Outline 2003 Prentice Hall, Inc. All rights reserved. 25 WelcomeLines.ja va 2. Class WelcomeLines (extends JApplet) 3. paint 3.1 drawline 3.2 drawline Draw horizontal lines with drawline (endpoints 3.3 drawstring have same y coordinate). Program Output

58 1 <html> 2 <applet code = "WelcomeLines.class" width = "300" height = "40"> 3 </applet> 4 </html> HTML file Outline Prentice Hall, Inc. All rights reserved Drawing Strings and Lines Method drawline of class Graphics Takes as arguments Graphics object and line s end points x and y coordinate of first endpoint x and y coordinate of second endpoint

59 3.5 Adding Floating-Point Numbers 28 Next applet Mimics application for adding two integers (Fig 2.9) This time, use floating point numbers (numbers with a decimal point) Using primitive types double double precision floating-point numbers float single precision floating-point numbers Show program, then discuss 1 // Fig. 3.13: AdditionApplet.java 2 2 // Adding two floating-point numbers. 3 3 import java.awt.graphics; // import class Graphics 4 // Java packages 5 5 import java.awt.graphics; // import class Graphics 6 6 public import javax.swing.*; class AdditionApplet // extends import package JApplet javax.swing { 7 7 double sum; // sum of the values entered by the user 8 public class AdditionApplet extends JApplet { 8 9 double sum; // sum of values entered by user 9 public void init() 10 * allows any class in the 10 { 11 // initialize applet by obtaining values 11 String firstnumber, // first string package from user entered to be used. by user 12 public void init() { secondnumber; // second string entered by user String double firstnumber; number1, // first // first string number entered to add by user String secondnumber; number2; // second // second string number entered to add by user Field sum may be used anywhere double // read number1; in first number // first from number user in to the add class, even in other methods double firstnumber number2; = // second number to add JOptionPane.showInputDialog( Type double can store floating // obtain "Enter first first number floating-point from user point value" numbers. ); firstnumber = JOptionPane.showInputDialog( //"Enter read in first second floating-point number from value" user); secondnumber = // obtain JOptionPane.showInputDialog( second number from user secondnumber = JOptionPane.showInputDialog( "Enter second floating-point value" ); 26 "Enter second floating-point value" ); // convert numbers from type String to type double 29 number1 = Double.parseDouble( firstnumber ); 30 number2 = Double.parseDouble( secondnumber ); 31 Outline 2003 Prentice Hall, Inc. All rights reserved. 29 AdditionApplet. java 1. import 2. Class AdditionApplet (extends JApplet) 3. Fields 4. init 4.1 Declare variables 4.2 showinputdialog 4.3 parsedouble

60 // // add add numbers the numbers Outline sum sum = = number1 + number2; + number2; } 35 } // end method init Draw applet public void paint( Graphics g ) contents 37 // draw results a rectangle on applet s background public { void paint( Graphics g ) { // draw the results with g.drawstring 5.1 Draw a rectangle // g.drawrect( call superclass 15, 10, version 270, of 20 method ); paint 41 super.paint( g ); 39 g.drawstring( "The sum is " + sum, 25, 25 ); 5.2 Draw the results } 43 // draw rectangle starting from (15, 10) that is } // pixels wide and 20 pixels tall 45 g.drawrect( 15, 10, 270, 20 ); 1 <html> <applet // draw code="additionapplet.class" results a String at (25, width=300 25) height=50> 48 3 </applet> g.drawstring( "The sum is " + sum, 25, 25 ); </html> 50 } // end method paint drawrect takes the upper left coordinate, width, and height of the rectangle to draw. 52 } // end class AdditionApplet HTML file 1 <html> 2 <applet code = "AdditionApplet.class" width = "300" height = "65"> 3 </applet> 4 </html> 2003 Prentice Hall, Inc. All rights reserved. Outline 31 Program Output 2003 Prentice Hall, Inc. All rights reserved.

61 Adding Floating-Point Numbers Lines 1-2: Comments 5 import java.awt.graphics; // import class Graphics Line 5: imports class Graphics import not needed if use full package and class name public void paint ( java.awt.graphics g ) 6 import javax.swing.*; // import package javax.swing Line 8: specify entire javax.swing package *indicates all classes in javax.swing are available Includes JApplet and JOptionPane Use JOptionPane instead of javax.swing.joptionpane *does not not load all classes Compiler only loads classes it uses Adding Floating-Point Numbers 8 public class AdditionApplet extends JApplet { Begin class declaration Extend JApplet, imported from package javax.swing 9 double sum; // sum of values entered by user Field declaration Each object of class gets own copy of the field Declared in body of class, but not inside methods Variables declared in methods are local variables Can only be used in body of method Fields can be used anywhere in class Have default value (0.0 in this case) Fields are also known as instance variables. Explicitly initializing fields rather than relying on automatic initialization improves program readability.

62 3.5 Adding Floating-Point Numbers 34 9 double sum; // sum of values entered by user Primitive type double Used to store floating point (decimal) numbers 12 public void init() Method init Normally initializes fields and applet class Guaranteed to be first method called in applet First line must always appear as above Returns nothing (void), takes no arguments 13 { Begins body of method init 3.5 Adding Floating-Point Numbers String firstnumber; // first string entered by user 15 String secondnumber; // second string entered by user double number1; // first number to add 18 double number2; // second number to add Declare variables Two types of variables Reference variables (called references) Refer to objects (contain location in memory) Objects defined in a class definition Can contain multiple data and methods paint receives a reference called g to a Graphics object Reference used to call methods on the Graphics object Primitive types (called variables) Contain one piece of data Boolean, char, byte, short, int, long, float, and double

63 3.5 Adding Floating-Point Numbers String firstnumber; // first string entered by user 15 String secondnumber; // second string entered by user double number1; // first number to add 18 double number2; // second number to add Distinguishing references and variables If type is a class name, then reference String is a class firstnumber, secondnumber If type a primitive type, then variable double is a primitive type number1, number2 3.5 Adding Floating-Point Numbers firstnumber = JOptionPane.showInputDialog( 22 "Enter first floating-point value" ); Method JOptionPane.showInputDialog Prompts user for input with string Enter value in text field, click OK If not of correct type, error occurs In Chapter 15 learn how to deal with this Returns string user inputs Assignment statement to string Lines 25-26: As above, assigns input to secondnumber

64 3.5 Adding Floating-Point Numbers number1 = Double.parseDouble( firstnumber ); 30 number2 = Double.parseDouble( secondnumber ); static method Double.parseDouble Converts String argument to a double Returns the double value Remember static method syntax ClassName.methodName( arguments ) 33 sum = number1 + number2; Assignment statement sum a field, can use anywhere in class Not defined in init but still used 3.5 Adding Floating-Point Numbers } // end method init Ends method init appletviewer (or browser) calls inherited method start start usually used with multithreading Advanced concept, in Chapter 16 We do not declare it, so empty declaration in JApplet used Next, method paint called 45 g.drawrect( 15, 10, 270, 20 ); Method drawrect( x1, y1, width, height ) Draw rectangle, upper left corner (x1, y1), specified width and height Line 45 draws rectangle starting at (15, 10) with a width of 270 pixels and a height of 20 pixels

65 3.5 Adding Floating-Point Numbers g.drawstring( "The sum is " + sum, 25, 25 ); Sends drawstring message (calls method) to Graphics object using reference g "The sum is" + sum - string concatenation sum converted to a string sum can be used, even though not defined in paint field, can be used anywhere in class Non-local variable in method drawstring 3.6 Java Applet Internet and World Wide Web Resources 41 Many Java applet resources available java.sun.com/applets/ Many resources and free applets Has demo applets from J2SDK Sun site developer.java.sun.com/developer Tech support, discussion forums, training, articles, links, etc. Registration required Rates applets, top 1, 5 and 25 percent View best applets on web

66 42 Summary Applets Program that runs in appletviewer (test utility for applets) Web browser (IE, Communicator) Browser that executes applet is called applet container. Executes when HTML (Hypertext Markup Language) document containing applet is opened and downloaded Applications run in command windows

67 1 Part 5 Program Analysis Principles and Techniques Front end 2 source code scanner tokens parser il errors Responsibilities: Recognize legal programs Report errors Produce il Preliminary storage map Shape the code for the back end Much of front end construction can be automated

68 3 Scanner source code scanner tokens parser il Scanner errors Maps characters into tokens the basic unit of syntax x = x + y; Becomes <id,x> = <id,x> + <id,y> ; character string for token is a lexeme Typical tokens: number, id, +, -, *, /, do, end Eliminates white space ( tables, blanks, comments) A key issue is speed use specialized recognizer (lex) 4 Specifying patterns A scanner must recognize various parts of the language s syntax. Some parts are easy: White space some combination of <b> and tab Keywords and operators specified as literal patterns do, end Comments opening and closing delimiters - /* */

69 Specifying patterns 5 Other parts are much harder: Identifiers alphabetic followed by k alphanumerics Special symbols (-, $, &, ) Numbers interger 0 or digit from 1-9 followed by digitals from 0-9 decimals integer. digits from 0-9 reals (integer or decimal) E (+ or -) digits from 0-9 complex ( real, real ) We need a powerful notation to specify these patterns. Definitions 6 Operation Definition Union of L and M written L M Concatenation of L and M written LM Kleene closure of L written L* Positive closure of L written L+ L M = { s s L or s M } LM = {st s L and t M} L* = i=0 L i L+ = i=1 L i

70 Regular expressions 7 Patterns are often specified as regular languages. Notations used to describe a regular language (or a regular set) include both regular expressions and regular grammars. Regular expressions (over an alphabet Σ): 1. is a RE denoting the set { } 2. If a Є Σ, then a is RE denoting {a} Regular expressions 8 Regular expressions (over an alphabet Σ): 3. If r and s are REs, denoting L(r) and L(s), then: (r) is a RE denoting L(r) (r) (s) is a RE denoting L(r) L(s) (r) (s) is a RE denoting L(r) L(s) (r)* is a RE denoting L(r)* (r)+ is a RE denoting L(r)+ If we adopt a precedence for operators, the extra parentheses can go away. We assume closure, then concatenation, the alternation as the order of precedence.

71 9 RE examples identifier letter (a b c z A B C Z) digit ( ) id letter (letter digit)* numbers integer ( + - ) ( ) (digit)* decimal integer. (digit)* real (integer decimal) E (+ -) (digit)* Complex ( real. real ) 10 RE examples Most programming language tokens can be described with regular expressions. We can use regular expressions to automatically build scanners.

72 21 Regular expressions Regular expressions represent languages Languages are sets of strings. Operations include Kleene closure, concatenation, and union. Regular expression (a) (a) (b) (a)(b) (a)* (a)+ Language { a } { a, b } { ab } {, a, aa, } { a, aa, } 22 Regular expressions We assume that closure, concatenation, union as the order of precedence. ab cd* = (ab) (c(d*)) = { ab, c, cd, cdd, } a (bc)* = { a, abc, abcbc, }

73 Recognizers 23 From a regular expression, we can construct a deterministic finite automan (dfa). Recognizer for the identifier: letter digit S0 letter S1 other S2 digit other accept S3 error Recognizers 24 Identifier: letter (a b c z A B C Z) digit ( ) id letter (letter digit)*

74 So what is hard? 25 Language features that can cause problems: Reserved words PL/I had no reserved words if then then then = else; else else = then; Significant blanks FORTRAN and Algol68 ignore blanks do 10 I = 1,25 do 10 I = 1.25 So what is hard? 26 String constants special charaters in strings newline, tab, quote, comment, Finite closures some languages limit identifier lengths adds states to count length FORTRAN 66 6 characters These problems can be swept under the rug (avoided) by intelligent language design.

75 27 Methods and parameters What is a lexical error? 1234G6 Illegal character What should the scanner do? Report the error Try to connect it? Error connection techniques Minimum distance corrections Hard token recovery Skip until match 28 Scanners source code scanner tokens parser IL errors A scanner separates input into tokens based on lexical analysis. Legal tokens are usually specified by regular expressions (REs). Regular expressions specify regular languages.

76 Limits of regular languages 31 Not all languages are regular. You cannot construct dfa s to recognize these languages: L = { p k q k } L = { wcw τ w Σ* } Note: neither of these is a regular expression! (dfa s cannot count!) Limits of regular languages 32 But, this is a little subtle. You can construct dfa s for: Alternating 0 s and 1 s ( 1) (01)* ( 0) Sets of pairs of 0 s and 1 s (01 10)+

77 More regular languages 33 Let s look at another regular language the set of strings containing an even number of zeros and an even number of ones. The regular expression is: Start S2 1 1 S (00 11)* ((01 10)(00 11)*(01 10)(00 11)*)* 1 1 S3 Summary 34 Scanners Break up input into tokens Catch lexical errors Difficulty affected by language design Scanner generators Tokens specified by regular expressions Construct dfa to recognize language Highly efficient in practise

78 The role of the parser 35 source code scanner tokens parser il errors Parser: Perform context-free syntax anaylsis Guide the context-sensitive anaylsis Construct an intermediate representation Produce meaningful error messages Attempt error correction Syntax analysis Context-free syntax is specified with a grammar. 36 Formally, a context-free grammar G is a four-tuple (T, NT, S, P) T is the set of terminal symbols in the grammar. For our purposes, the set of terminals is equivalent to the set of tokens returned by the lexical analyzer.

79 37 Syntax analysis NT is a set of syntactic variables that denote sets of (sub)strings occurring in the language. These are used to impose a structure on the grammar. S is a distinguished nonterminal (S NT) that denotes the entire set of strings in L(G). This is sometimes called a goal symbol. S cannot appear on the right hand side of some production. P is a set of productions that specify the way that terminals and non-terminals can be combined to from strings in the language. Each production must have a single non-terminal on its left hand side. 38 Syntax analysis Grammars are often written in BNF, or Backus-Naur Form 1. <goal> ::= <expr> 2. <expr> ::= <expr> <op> <expr> 3. number 4. id 5. <op> ::= * 8. /

80 Syntax analysis 39 This grammar gives simple expressions over numbers and identifiers. In a BNF for a grammar, we represent Non-terminal with brackets or capital letters, Terminals with typewriter font or underline, Productions as in example Why use context-free grammars? 40 Many advantages: Precise syntactic specification of a programming language Easy to understand, avoids ad hoc definition Easier to maintain, add new language features Can automatically construct efficient parser Parser construction reveals ambiguity, other difficulties Imparts structure to language Supports syntax-directed translation

81 Grammars for regular languages 41 Can we place a restriction on the form of grammar to ensure that it describes a regular language? Provable fact: For any RE r, there is a grammar g such, that L(r) = L(g) The grammar that generate regular sets are called regular grammar Grammars for regular languages 42 Defintion: In a regular grammar, all productions have one of two forms: 1. A aa 2. A a Where A is a non-terminal and a is a terminal symbol. These are also called type 3 grammars (Chlomsky).

82 Scanning vs. parsing 43 Where do we draw the line? term [a-za-z] ( [ a-za-z ] [0-9 ] )* 0 [1-9 ] [0-9 ] * op + - * / expr (term op)* term Regular expressions are use to classify. identifiers, numbers, keywords Scanning vs. parsing 44 Context-free grammars are used to count. Brackets ( ), begin end, if then else, imposing structure - expressions Grammar for cc has 188 productions.

83 47 Derivations We can view the productions of a cfg as rewriting rules. Using a example: <goal> <expr> <expr> <op> <expr> <expr> <op> <expr> <op> <expr> <id,x> <op> <expr> <op> <expr> <id,x> + <expr> <op> <expr> <id,x> + <num,2> <op> <expr> <id,x> + <num,2> * <expr> <id,x> + <num,2> * <id,y> 48 Derivations We have derived the sentence x + 2 * y We denote this <goal> id + num * id. Such a sequence of rewrites is a derivation or a parse. The process of discovering a derivation is called parsing.

84 49 Derivations At each step, we chose a non-terminal to replace. This choice can lead to different derivations. Two are of particular interest Leftmost derivation the leftmost non-terminal is replaced at each step Rightmost derivation the rightmost non-terminal is replaced at each step. The example was a leftmost derivation. 50 For the string x y: Rightmost Derivation <goal> <expr> <expr> <op> <expr> <expr> <op> <id,y> <expr> * <id,y> <expr> <op> <expr> * <id,y> <expr> <op> <num,2> * <id,y> <expr> + <num,2> * <id,y> <term> + <num,2> * <id,y> <id,x> + <num,2> * <id,y> Again, <goal>... id + num * id.

85 Parse tree 51 Let s look at the parse tree goal Treewalk evaluation would give the wrong answer. (x + 2) * y instead of x + (2 * y) expr <id,x> expr op term + <num,2> expr op * expr <id,y> Precedence 52 These two derivations point out a problem with the grammar. The grammar has no notion of precedence, or implied order of evaluation.

86 53 Precedence To add precedence takes additional machinery 1. <goal> ::= <expr> 2. <expr> ::= <expr> + <term> 3. <expr> - <term> 4. <term> 5. <term> ::= <term> * <factor> 6. <term> / < factor> 7. <factor> 8. <factor> ::= number 9. id 54 Precedence This grammar enforces a precedence on the derivation termsmust be derived from expressions forces the "correct" tree

87 Precedence 55 Now, for the string x + 2 * y: <goal> <expr> <expr> + <term> <expr> + <term> * <factor> <expr> + <term> * <id,y> <expr> + <factor> * <id,y> <expr> + <num,2> * <id,y> <term> + <num,2> * <id,y> <factor> + <num,2> * <id,y> <id,x> + <num,2> * <id,y> Again, <goal>... id + num * id, but this time, we build the desired tree. Precedence 56 This time, we get the desired parse tree. Treewalk evaluation computes x + (2 * y). <id,x> <num,2>

88 57 Ambiguity If a grammar has multiple leftmost derivations for a single (terminal) word of the language, the grammar is ambiguous. Similarly, a grammar with multiple rightmost derivations for a single (terminal) word of the language is ambiguous. Example <stmt> ::= if <expr> then <stmt> if <expr> then <stmt> else <stmt> other stmts 58 Ambiguity Consider deriving the sentential form: ife 1 then if E 2 then S 1 else S 2 It has two derivations. This ambiguity is purely grammatical. It is a context-free ambiguity.

89 Ambiguity 59 We may be able to eliminate ambiguities by rearranging the grammar. <stmt> ::= <ms> <us> <ms> ::= if <expr> then <ms> else <ms> other stmts <us> ::= if <expr> then <stmt> if <expr> then <ms> else <us> Ambiguity 60 This grammar generates the same language as the ambiguous grammar, but applies the common sense rule match each else with the closest unmatched then This is pretty clearly the language designer's intent.

90 Ambiguity 61 Ambiguity generally refers to a confusion in the context-free specification. Context-sensitive confusions can arise from overloading. a = f(17) In many Algol-like languages, f could be either a function or a subscripted variable. Ambiguity 62 Disambiguating this Statement requires context. need values of declarations not context free really an issue of type Rather than complicate parsing, we will handle this separately.

91 66 Summary: Parser Parser performs context-free syntax analysis Recognizes structure over set of tokens Deals with ambiguity and precedences

92 1 Part 6 Control Structures (1) Operators Primitive data types 2003 Prentice Hall, Inc. All rights reserved. 4 Algorithm 4.2 Algorithms Series of actions in specific order The actions executed The order in which actions execute Program control Specifying the order in which actions execute Control structures help specify this order

93 5 Pseudocode 4.3 Pseudocode Informal language for developing algorithms Not executed on computers Helps developers think out algorithms 6 Sequential execution 4.4 Control Structures Program statements execute one after the other Transfer of control Three control statements can specify order of statements Sequence structure Selection structure Repetition structure Activity diagram Models the workflow Action-state symbols Transition arrows

94 7 add grade to total Corresponding Java statement: total = total + grade; add 1 to counter Corresponding Java statement: counter = counter + 1; Fig 4.1 Sequence structure activity diagram. 8 Ja va Keyword s abstract assert boolean break byte case catch char class continue default do double else extends final finally float for if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while Keywords that are reserved, but not currently used const goto Fig. 4.2 Ja va keyword s.

95 9 4.4 Control Structures Java has a sequence structure built-in Java provides three selection structures if If else switch Java provides three repetition structures while do while do Each of these words is a Java keyword if Single-Selection Statement Single-entry/single-exit control structure Perform action only when condition is true Action/decision programming model

96 11 [grade >= 60] print Passed [grade < 60] Fig 4.3 if single-selections statement activity diagram if else Selection Statement Perform action only when condition is true Perform different specified action when condition is false Conditional operator (?:) Nested if else selection structures

97 13 print Failed [grade < 60] [grade >= 60] print Passed Fig 4.4 if else double-selections statement activity diagram. 4.7 while Repetition Statement 14 Repeat action while condition remains true

98 15 merge decision [product <= 1000] double product value [product > 1000] Corresponding Java statement: product = 2 * product; Fig 4.5 while repetition statement activity diagram. 4.8 Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition) 16 Counter Variable that controls number of times set of statements executes Average1.java calculates grade averages uses counters to control repetition

99 17 Set total to zero Set grade counter to one While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average Fig. 4.6 Pseudocode algorithm that uses countercontrolled repetition to solve the class-average problem. 1 // Fig. 4.7: Average1.java 2 // Class-average program with counter-controlled repetition. 3 import javax.swing.joptionpane; 4 5 public class Average1 { Declare variables; 6 7 public static void main( String args[] ) 8 { 9 int total; // sum of grades input by user 10 int gradecounter; // number of grade to be entered next 11 int grade; // grade value 12 int average; // average of grades String gradestring; // grade typed by user // initialization phase 17 total = 0; // initialize total 18 gradecounter = 1; // initialize loop counter // processing phase 21 while ( gradecounter <= 10 ) { // loop 10 times // prompt for input and read grade from user 24 gradestring = JOptionPane.showInputDialog( 25 "Enter integer grade: " ); // convert gradestring to int 28 grade = Integer.parseInt( gradestring ); 29 gradecounter is the counter Continue looping as long as gradecounter is less than or equal to 10 Outline Average1.java gradecounter Line 21 18

100 30 total = total + grade; // add grade to total 31 gradecounter = gradecounter + 1; // increment counter } // end while // termination phase 36 average = total / 10; // integer division // display average of exam grades 39 JOptionPane.showMessageDialog( null, "Class average is " + average, 40 "Class Average", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate the program } // end main } // end class Average1 Outline Average1.java 19 Outline 20 Average1.java

101 4.9 Formulating Algorithms with Top- Down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition) Sentinel value Used to indicated the end of data entry Average2.java has indefinite repetition User enters sentinel value (-1) to end repetition Initialize total to zero Initialize counter to zero Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) If the counter is not equal to zero Set the average to the total divided by the counter Print the average else Print No grades were entered Fig. 4.8 Class-average problem pseudocode algorithm with sentinel-controlled repetition.

102 1 // Fig. 4.9: Average2.java 2 // Class-average program with sentinel-controlled repetition. 3 import java.text.decimalformat; // class to format numbers 4 import javax.swing.joptionpane; 5 6 public class Average2 { 7 8 public static void main( String args[] ) 9 { 10 int total; // sum of grades 11 int gradecounter; // number of grades entered 12 int grade; // grade value double average; // number with decimal point for average String gradestring; // grade typed by user // initialization phase 19 total = 0; // initialize total 20 gradecounter = 0; // initialize loop counter // processing phase 23 // get first grade from user 24 gradestring = JOptionPane.showInputDialog( 25 "Enter Integer Grade or -1 to Quit:" ); // convert gradestring to int 28 grade = Integer.parseInt( gradestring ); 29 Outline Average2.java // loop until sentinel value read from user 31 while ( grade!= -1 ) { 32 total = total + grade; // add grade to total 33 gradecounter = gradecounter + 1; // increment counter // get next grade from user 36 gradestring = JOptionPane.showInputDialog( 37 "Enter Integer Grade or -1 to Quit:" ); // convert gradestring to int 40 grade = Integer.parseInt( gradestring ); hundredth } // end while // termination phase 45 DecimalFormat twodigits = new DecimalFormat( "0.00" ); // if user entered at least one grade if ( gradecounter!= 0 ) { // calculate average of all grades entered 51 average = (double) total / gradecounter; // display average with two digits of precision 54 JOptionPane.showMessageDialog( null, 55 "Class average is " + twodigits.format( average ), 56 "Class Average", JOptionPane.INFORMATION_MESSAGE ); } // end if part of if...else 59 loop until gradecounter equals sentinel value (-1) Format numbers to nearest Outline Average2.java Line 31 Line 45 24

103 60 else // if no grades entered, output appropriate message 61 JOptionPane.showMessageDialog( null, "No grades were entered", 62 "Class Average", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class Average2 Outline Average2.java Formulating Algorithms with Top- Down, Stepwise Refinement: Case Study 3 (Nested Control Structures) Nested control structures 26

104 27 Initialize passes to zero Initialize failures to zero Initialize student to one While student counter is less than or equal to ten Input the next exam result If the student passed Add one to passes else Add one to failures Add one to student counter Print the number of passes Print the number of failures If more than eight students passed Print Raise tuition Fig 4.10 Pseudocode for examination-results problem. 1 // Fig. 4.11: Analysis.java 2 // Analysis of examination results. 3 import javax.swing.joptionpane; 4 5 public class Analysis { 6 7 public static void main( String args[] ) 8 { 9 // initializing variables in declarations 10 int passes = 0; // number of passes 11 int failures = 0; // number of failures 12 int studentcounter = 1; // student counter 13 int result; // one exam result String input; // user-entered value 16 String output; // output string // process 10 students using counter-controlled loop 19 while ( studentcounter <= 10 ) { // prompt user for input and obtain value from user 22 input = JOptionPane.showInputDialog( 23 "Enter result (1 = pass, 2 = fail)" ); // convert result to int 26 result = Integer.parseInt( input ); // if result 1, increment passes; if...else nested in while 29 if ( result == 1 ) 30 passes = passes + 1; Line 19 Line 29 Outline Loop until student counter is greater than 10 Analysis.java Nested control structure 28

105 31 32 else // if result not 1, increment failures 33 failures = failures + 1; // increment studentcounter so loop eventually terminates 36 studentcounter = studentcounter + 1; } // end while // termination phase; prepare and display results 41 output = "Passed: " + passes + "\nfailed: " + failures; // determine whether more than 8 students passed 44 if ( passes > 8 ) 45 output = output + "\nraise Tuition"; JOptionPane.showMessageDialog( null, output, 48 "Analysis of Examination Results", 49 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class Analysis Outline Analysis.java Compound Assignment Operators Assignment Operators Abbreviate assignment expressions Any statement of form variable = variable operator expression; Can be written as variable operator= expression; e.g., addition assignment operator += c = c + 3 can be written as c += 3

106 31 A ssig nm e nt operator Sa m p le expression Explanation A ssig ns Assume: int c = 3, d = 5, e = 4, f = 6, g = 12; += c += 7 c = c to c -= d -= 4 d = d to d *= e *= 5 e = e * 5 20 to e /= f /= 3 f = f / 3 2 to f %= g %= 9 g = g % 9 3 to g Fig A rithm e tic a ssig nm e nt o p e ra to rs Increment and Decrement Operators 32 Unary increment operator (++) Increment variable s value by 1 Unary decrement operator (--) Decrement variable s value by 1 Preincrement / predecrement operator Post-increment / post-decrement operator

107 33 Operator Ca lled Sa m p le expression Explanation ++ preincrement ++a Increment a by 1, then use the new value of a in the expression in which a resides. ++ postincrement a++ Use the current value of a in the expression in which a resides, then increment a by predecrement --b Decrement b by 1, then use the new value of b in the expression in which b resides. -- postdecrement b-- Use the current value of b in the expression in which b resides, then decrement b by 1. Fig The increment and decrement operators. 1 // Fig. 4.14: Increment.java 2 // Preincrementing and postincrementing operators. 3 4 public class Increment { 5 6 public static void main( String args[] ) 7 { 8 int c; 9 10 // demonstrate postincrement 11 c = 5; // assign 5 to c 12 System.out.println( c ); // print 5 13 System.out.println( c++ ); // print 5 then postincrement 14 System.out.println( c ); // print System.out.println(); // skip a line // demonstrate preincrement 19 c = 5; // assign 5 to c 20 System.out.println( c ); // print 5 21 System.out.println( ++c ); // preincrement then print 6 22 System.out.println( c ); // print } // end main } // end class Increment Line 13 postincrements c Line 21 preincrements c Outline 34 Increment.java Line 13 postincrement Line 21 preincrement 5 6 6

108 35 Operators Assoc ia tivity Typ e right to left unary postfix (type) right to left unary * / % left to right multiplicative + - left to right additive < <= > >= left to right relational ==!= left to right equality?: right to left conditional = += -= *= /= %= right to left assignment Fig Pre c e d e nc e a nd a sso c ia tivity o f the o p e ra to rs d isc usse d so fa r Primitive Types Primitive types building blocks for more complicated types Java is strongly typed All variables in a Java program must have a type Java primitive types portable across computer platforms that support Java

109 37 Ty p e Size in b it s Values St a n d a rd boolean true or false [Note: The representation of a boolean is specific to the Java Virtual Machine on each computer platform.] char 16 '\u0000' to '\uffff' (ISO Unicode character set) (0 to 65535) byte to +127 ( 2 7 to 2 7 1) short 16 32,768 to +32,767 ( 2 15 to ) int 32 2,147,483,648 to +2,147,483,647 ( 2 31 to ) long 64 9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 ( 2 63 to ) float 32 Negative range: (IEEE 754 floating point) E+38 to e 45 Positive range: e 45 to E+38 double 64 Negative range: E+308 to e 324 Positive range: e 324 to E+308 (IEEE 754 floating point) Fig The Ja va p rimitive typ es. 5.2 Essentials of Counter-Controlled Repetition 45 Counter-controlled repetition requires: Control variable (loop counter) Initial value of the control variable Increment/decrement of control variable through each loop Condition that tests for the final value of the control variable

110 1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition. 3 import java.awt.graphics; 4 5 import javax.swing.japplet; 6 7 public class WhileCounter extends JApplet { 8 9 // draw lines on applet s background 10 public void paint( Graphics g ) 11 { Control-variable Condition name is counter tests for counter s final value Control-variable initial value is 1 12 super.paint( g ); // call paint method inherited from JApplet int counter = 1; // initialization while ( counter <= 10 ) { // repetition condition 17 g.drawline( 10, 10, 250, counter * 10 ); 18 ++counter; // increment } // end while } // end method paint } // end class WhileCounter Outline 46 WhileCounter.ja va Line 14 Line 16 Increment Line for counter for Repetition Statement 47 Handles counter-controlled-repetition details

111 1 // Fig. 5.2: ForCounter.java 2 // Counter-controlled repetition with the for statement. 3 import java.awt.graphics; 4 5 import javax.swing.japplet; Condition tests for 6 Control-variable name is counter 7 public class ForCounter extends JApplet { 8 Control-variable initial value is 1 9 // draw lines on applet s background 10 public void paint( Graphics g ) 11 { 12 super.paint( g ); // call paint method inherited from JApplet // for statement header includes initialization, 15 // repetition condition and increment 16 for ( int counter = 1; counter <= 10; counter++ ) 17 g.drawline( 10, 10, 250, counter * 10 ); } // end method paint } // end class ForCounter counter s final value Increment for counter Outline 48 ForCounter.java Line 16 int counter = 1; Line 16 counter <= 10; Line 16 counter++; 49 for keyword Control variable Required semicolon separator Final value of control variable for which the condition is true Required semicolon separator for ( int counter = 1; counter <= 10; counter++ ) Initial value of control variable Loop-continuation condition Increment of control variable Fig. 5.3 for statement header components.

112 5.3 for Repetition Structure (cont.) 50 for ( initialization; loopcontinuationcondition; increment ) statement; can usually be rewritten as: initialization; while ( loopcontinuationcondition ){ statement; increment; } 51 Establish initial value of control variable int counter = 1 [counter > 10] [counter <= 10] Draw a line on the applet Increment the control variable Determine whether the final value of control variable has been reached g.drawline( 10, 10, 250, counter * 10 ); counter++ Fig. 5.4 for statement activity diagram.

113 5.4 Examples Using the for Statement 52 Varying control variable in for statement Vary control variable from 1 to 100 in increments of 1 for ( int i = 1; i <= 100; i++ ) Vary control variable from 100 to 1 in increments of 1 for ( int i = 100; i >= 1; i-- ) Vary control variable from 7 to 77 in increments of 7 for ( int i = 7; i <= 77; i += 7 ) 1 // Fig. 5.5: Sum.java 2 // Summing integers with the for statement. 3 import javax.swing.joptionpane; 4 5 public class Sum { 6 7 public static void main( String args[] ) 8 { 9 int total = 0; // initialize sum // total even integers from 2 through for ( int number = 2; number <= 100; number += 2 ) 13 total += number; // display results 16 JOptionPane.showMessageDialog( null, "The sum is " + total, 17 "Total Even Integers from 2 to 100", 18 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class Sum increment number by 2 each iteration Outline Sum.java Line 12 53

114 1 // Fig. 5.6: Interest.java 2 // Calculating compound interest. 3 import java.text.numberformat; // class for numeric formatting 4 import java.util.locale; // class for country-specific information 5 6 import javax.swing.joptionpane; 7 import javax.swing.jtextarea; 8 9 public class Interest { 10 Java treats floating-points as type double NumberFormat can format numeric values as currency Display currency values with 11 public static void main( String args[] ) 12 { dollar sign ($) 13 double amount; // amount on deposit at end of each year 14 double principal = ; // initial amount before interest 15 double rate = 0.05; // interest rate // create NumberFormat for currency in US dollar format 18 NumberFormat moneyformat = 19 NumberFormat.getCurrencyInstance( Locale.US ); // create JTextArea to display output 22 JTextArea outputtextarea = new JTextArea(); // set first line of text in outputtextarea 25 outputtextarea.settext( "Year\tAmount on deposit\n" ); 26 Outline Interest.java Lines Line 18 Line // calculate amount on deposit for each of ten years 28 for ( int year = 1; year <= 10; year++ ) { // calculate new amount for specified year 31 amount = principal * Math.pow( rate, year ); // append one line of text to outputtextarea 34 outputtextarea.append( year + "\t" + 35 moneyformat.format( amount ) + "\n" ); } // end for // display results 40 JOptionPane.showMessageDialog( null, outputtextarea, 41 "Compound Interest", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate the application } // end main } // end class Interest Outline Calculate amount with for Interest.java statement Lines

115 5.5 do while Repetition Statement 56 do while structure Similar to while structure Tests loop-continuation after performing body of loop i.e., loop body always executes at least once 1 // Fig. 5.7: DoWhileTest.java 2 // Using the do...while statement. 3 import java.awt.graphics; 4 5 import javax.swing.japplet; 6 Oval is drawn before testing 7 public class DoWhileTest extends JApplet { 8 counter s final value 9 // draw lines on applet 10 public void paint( Graphics g ) 11 { 12 super.paint( g ); // call paint method inherited from JApplet int counter = 1; // initialize counter do { 17 g.drawoval( counter * 10, counter * 10, 18 counter * 20, counter * 20 ); 19 ++counter; 20 } while ( counter <= 10 ); // end do...while } // end method paint } // end class DoWhileTest Outline 57 DoWhileTest.jav a Lines 16-20

116 58 action state condition [true] [false] Fig. 5.8 do while repetition statement activity diagram switch Multiple-Selection Statement switch statement Used for multiple selections

117 1 // Fig. 5.9: SwitchTest.java 2 // Drawing lines, rectangles or ovals based on user input. 3 import java.awt.graphics; 4 5 import javax.swing.*; 6 7 public class SwitchTest extends JApplet { 8 int choice; // user's choice of which shape to draw 9 10 // initialize applet by obtaining user's choice 11 public void init() 12 { 13 String input; // user's input Get user s input in JApplet // obtain user's choice 16 input = JOptionPane.showInputDialog( 17 "Enter 1 to draw lines\n" + 18 "Enter 2 to draw rectangles\n" + 19 "Enter 3 to draw ovals\n" ); choice = Integer.parseInt( input ); // convert input to int } // end method init // draw shapes on applet's background 26 public void paint( Graphics g ) 27 { 28 super.paint( g ); // call paint method inherited from JApplet for ( int i = 0; i < 10; i++ ) { // loop 10 times (0-9) 31 Outline 60 SwitchTest.java Lines 16-21: Getting user s input 32 switch ( choice ) { // determine shape to draw case 1: // draw a line 35 g.drawline( 10, 10, 250, 10 + i * 10 ); 36 break; // done processing case case 2: // draw a rectangle 39 g.drawrect( 10 + i * 10, 10 + i * 10, i * 10, 50 + i * 10 ); 41 break; // done processing case case 3: // draw an oval 44 g.drawoval( 10 + i * 10, 10 + i * 10, i * 10, 50 + i * 10 ); 46 break; // done processing case default: // draw string indicating invalid value entered 49 g.drawstring( "Invalid value entered", 50 10, 20 + i * 15 ); } // end switch } // end for } // end method paint } // end class SwitchTest Outline user input (choice) is switch controlling statement expression determines which case label to execute, SwitchTest.java depending on controlling expression Line 32: controlling expression Line 32: switch statement Line 48 default case for invalid entries 61

118 Outline 62 SwitchTest.java Outline 63 SwitchTest.java

119 64 case a [false] [true] case a action(s) break case b [false] [true] case b action(s) break. [true] case z [false] case z action(s) break default action(s) Fig switch multiple-selection statement activity diagram with break statements break and continue Statements break/continue Alter flow of control break statement Causes immediate exit from control structure Used in while, for, do while or switch statements continue statement Skips remaining statements in loop body Proceeds to next iteration Used in while, for or do while statements

120 1 // Fig. 5.11: BreakTest.java 2 // Terminating a loop with break. 3 import javax.swing.joptionpane; 4 5 public class BreakTest { 6 7 public static void main( String args[] ) 8 { 9 String output = ""; 10 int count; for ( count = 1; count <= 10; count++ ) { // loop 10 times if ( count == 5 ) // if count is 5, 15 break; // terminate loop output += count + " "; } // end for output += "\nbroke out of loop at count = " + count; 22 JOptionPane.showMessageDialog( null, output ); System.exit( 0 ); // terminate application } // end main } // end class BreakTest Outline BreakTest.java exit for structure (break) Line 12 when count equals 5 Loop 10 times Lines // Fig. 5.12: ContinueTest.java 2 // Continuing with the next iteration of a loop. 3 import javax.swing.joptionpane; 4 5 public class ContinueTest { 6 7 public static void main( String args[] ) 8 { 9 String output = ""; for ( int count = 1; count <= 10; count++ ) { // loop 10 times if ( count == 5 ) // if count is 5, 14 continue; // skip remaining code in loop output += count + " "; } // end for output += "\nused continue to skip printing 5"; 21 JOptionPane.showMessageDialog( null, output ); System.exit( 0 ); // terminate application } // end main } // end class ContinueTest Outline ContinueTest.ja Skip line 16 and proceed va to line 11 when count equals 5 Loop 10 times Line 11 Lines

121 73 Logical operators 5.9 Logical Operators Allows for forming more complex conditions Combines simple conditions Java logical operators && (conditional AND) & (boolean logical AND) (conditional OR) (boolean logical inclusive OR) ^ (boolean logical exclusive OR)! (logical NOT) 74 expression1 expression2 expression1 && expression2 false false false false true false true false false true true true Fig && (conditional AND) operator truth table. expression1 expression2 expression1 expression2 false false false false true true true false true true true true Fig (conditional OR) operator truth table.

122 75 expression1 expression2 expression1 ^ expression2 false false false false true true true false true true true false Fig ^ (boolean logical exclusive OR) operator truth table. expression!expression false true true false Fig. 5.18! (logical negation, or logical NOT) operator truth table. 1 // Fig. 5.19: LogicalOperators.java 2 // Logical operators. 3 import javax.swing.*; 4 5 public class LogicalOperators 6 7 public static void main( String args[] ) 8 { 9 // create JTextArea to display results 10 JTextArea outputarea = new JTextArea( 17, 20 ); // attach JTextArea to a JScrollPane so user can scroll results 13 JScrollPane scroller = new JScrollPane( outputarea ); // create truth table for && (conditional AND) operator 16 String output = "Logical AND (&&)" + 17 "\nfalse && false: " + ( false && false ) + 18 "\nfalse && true: " + ( false && true ) + 19 "\ntrue && false: " + ( true && false ) + 20 "\ntrue && true: " + ( true && true ); // create truth table for (conditional OR) operator 23 output += "\n\nlogical OR ( )" + 24 "\nfalse false: " + ( false false ) + 25 "\nfalse true: " + ( false true ) + 26 "\ntrue false: " + ( true false ) + 27 "\ntrue true: " + ( true true ); 28 Conditional AND truth table Outline 76 LogicalOperator s.java Lines Lines Conditional OR truth table

123 29 // create truth table for & (boolean logical AND) operator 30 output += "\n\nboolean logical AND (&)" + 31 "\nfalse & false: " + ( false & false ) + 32 "\nfalse & true: " + ( false & true ) + 33 "\ntrue & false: " + ( true & false ) + 34 "\ntrue & true: " + ( true & true ); 35 Boolean logical AND truth table 36 // create truth table for (boolean logical inclusive OR) operator 37 output += "\n\nboolean logical inclusive OR ( )" + 38 "\nfalse false: " + ( false false ) + 39 "\nfalse true: " + ( false true ) + 40 "\ntrue false: " + ( true false ) + 41 "\ntrue true: " + ( true true ); // create truth table for ^ (boolean logical exclusive OR) operator 44 output += "\n\nboolean logical exclusive OR (^)" + 45 "\nfalse ^ false: " + ( false ^ false ) + 46 "\nfalse ^ true: " + ( false ^ true ) + 47 "\ntrue ^ false: " + ( true ^ false ) + 48 "\ntrue ^ true: " + ( true ^ true ); // create truth table for! (logical negation) operator 51 output += "\n\nlogical NOT (!)" + 52 "\n!false: " + (!false ) + 53 "\n!true: " + (!true ); outputarea.settext( output ); // place results in JTextArea 56 Outline 77 LogicalOperator s.java Lines Lines Boolean logical inclusive Lines OR truth table Lines Boolean logical exclusive OR truth table Logical NOT truth table 57 JOptionPane.showMessageDialog( null, scroller, 58 "Truth Tables", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class LogicalOperators Outline 78 LogicalOperator s.java

124 79 Operators Associativity Type right to left unary postfix (type) + -! right to left unary * / % left to right multiplicative + - left to right additive < <= > >= left to right relational ==!= left to right equality & left to right boolean logical AND ^ left to right boolean logical exclusive OR left to right boolean logical inclusive OR && left to right conditional AND left to right conditional OR?: right to left conditional = += -= *= /= %= right to left assignment Fig Precedence/associativity of the operators discussed so far Structured Programming Summary 80 Sequence structure built-in to Java Selection structure if, if else and switch Repetition structure while, do while and for

125 Part 7 Arrays 2003 Prentice Hall, Inc. All rights reserved. 7.1 Introduction Arrays Data structures Related data items of same type Can hold any data type or object Remain same size once created Fixed-length entries Array Group of variables Have same type (primitive versus reference types) Reference type (objects and arrays)

126 Name of array (note that all elements of this array have the same name, c) Index (or subscript) of the element in array c c[ 0 ] c[ 1 ] c[ 2 ] c[ 3 ] c[ 4 ] c[ 5 ] c[ 6 ] c[ 7 ] c[ 8 ] c[ 9 ] c[ 10 ] c[ 11 ] Fig. 7.1 A 12-element array. 7.2 Arrays (cont.) Index Also called subscript Position number in square brackets Must be positive integer or integer expression a = 5; b = 6; c[ a + b ] += 2; Adds 2 to c[ 11 ] Using a value of type long as an index results in a compilation error.

127 7.2 Arrays (cont.) Examine array c c is the array name c.length accesses array c s length (field of array object c) c has 12 elements ( c[0], c[1], c[11] ) The value of c[0] is 45 Difference between i-th element of array versus array element i 7.3 Declaring and Creating Arrays Declaring and Creating arrays Arrays are objects that occupy memory Created dynamically with keyword new int c[] = new int[ 12 ]; Equivalent to int c[]; // declare array variable c = new int[ 12 ]; // create array We can create arrays of objects too String b[] = new String[ 100 ]; int c[12]; // C/C++ syntax produces Java syntax error When creating arrays (default values for array elements): Zero for numeric type elements False for boolean elements Null for references (any non-primitive type)

128 7.4 Examples Using Arrays Declaring arrays Creating arrays Initializing arrays Manipulating array elements 1 // Fig. 7.2: InitArray.java 2 // Creating an array. 3 import javax.swing.*; 4 5 public class InitArray { 6 7 public static void main( String args[] ) 8 { 9 int array[]; // declare reference to an array array = new int[ 10 ]; // create array String output = "Index\tValue\n"; // append each array element's value to String output 16 for ( int counter = 0; counter < array.length; counter++ ) 17 output += counter + "\t" + array[ counter ] + "\n"; JTextArea outputarea = new JTextArea(); 20 outputarea.settext( output ); JOptionPane.showMessageDialog( null, outputarea, 23 "Initializing an Array of int Values", 24 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class InitArray Outline InitArray.java Create 10 ints for array; each Declare array int as is initialized an to 0 by default array of ints Line 9 Declare array as an array of ints array.length returns length of array Line 11 Create 10 ints for array; eachint is initialized to 0 by default Line 16 array.length returns length of array array[counter] returns Line int 17 associated with index in array array[counter] returnsint associated with index in array

129 Outline InitArray.java Each int is initialized to 0 by default Each int is initialized to 0 by default 7.4 Examples Using Arrays (Cont.) Using an array initializer Use initializer list Items enclosed in braces ({}) Items in list separated by commas int n[] = { 10, 20, 30, 40, 50 }; Creates a five-element array Index values of 0, 1, 2, 3, 4 Do not need keyword new

130 1 // Fig. 7.3: InitArray.java 2 // Initializing an array with a declaration. 3 import javax.swing.*; 4 5 public class InitArray { 6 7 public static void main( String args[] ) 8 { 9 // array initializer specifies number of elements and 10 // value for each element 11 int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; String output = "Index\tValue\n"; // append each array element's value to String output 16 for ( int counter = 0; counter < array.length; counter++ ) 17 output += counter + "\t" + array[ counter ] + "\n"; JTextArea outputarea = new JTextArea(); 20 outputarea.settext( output ); JOptionPane.showMessageDialog( null, outputarea, 23 "Initializing an Array with a Declaration", 24 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class InitArray Declare array as an array of ints Outline InitArray.java Line 11 Compiler uses initializerdeclare list array as an to allocate array array ofints Line 11 Compiler uses initializer list to allocate array Outline InitArray.java Each array element corresponds to element in initializer list Each array element corresponds to element in initializer list

131 7.4 Examples Using Arrays (Cont.) Calculating the value to store in each array element Initialize elements of 10-element array to even integers 1 // Fig. 7.4: InitArray.java 2 // Initialize array with the even integers from 2 to import javax.swing.*; 4 5 public class InitArray { 6 7 public static void main( String args[] ) 8 { 9 final int ARRAY_LENGTH = 10; // constant 10 int array[]; // reference to int array array = new int[ ARRAY_LENGTH ]; // create array // calculate value for each array element 15 for ( int counter = 0; counter < array.length; counter++ ) 16 array[ counter ] = * counter; String output = "Index\tValue\n"; for ( int counter = 0; counter < array.length; counter++ ) 21 output += counter + "\t" + array[ counter ] + "\n"; JTextArea outputarea = new JTextArea(); 24 outputarea.settext( output ); 25 Declare array as an array of ints Outline InitArray.java Line 10 Create 10 ints for array Declare array as an array ofints Use array index to assign array value Line 12 Create 10 ints for array Line 16 Use array index to assign array value

132 26 JOptionPane.showMessageDialog( null, outputarea, 27 "Initializing to Even Numbers from 2 to 20", 28 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class InitArray Outline InitArray.java 7.4 Examples Using Arrays (Cont.) Summing the elements of an array Array elements can represent a series of values We can sum these values

133 1 // Fig. 7.5: SumArray.java 2 // Total the values of the elements of an array. 3 import javax.swing.*; 4 5 public class SumArray { 6 7 public static void main( String args[] ) 8 { 9 int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 10 int total = 0; // add each element's value to total 13 for ( int counter = 0; counter < array.length; counter++ ) 14 total += array[ counter ]; JOptionPane.showMessageDialog( null, 17 "Total of array elements: " + total, 18 "Sum the Elements of an Array", 19 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class SumArray Declare array with initializer list Sum all array values Outline SumArray.java Line 9 Declare array with initializer list Lines Sum all array values 7.4 Examples Using Arrays (Cont.) Using histograms do display array data graphically Histogram Plot each numeric value as bar of asterisks (*)

134 1 // Fig. 7.6: Histogram.java 2 // Histogram printing program. 3 import javax.swing.*; 4 5 public class Histogram { 6 7 public static void main( String args[] ) 8 { 9 int array[] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; String output = "Element\tValue\tHistogram"; // for each array element, output a bar in histogram 14 for ( int counter = 0; counter < array.length; counter++ ) { 15 output += "\n" + counter + "\t" + array[ counter ] + "\t"; // print bar of asterisks 18 for ( int stars = 0; stars < array[ counter ]; stars++ ) 19 output += "*"; } // end outer for JTextArea outputarea = new JTextArea(); 24 outputarea.settext( output ); 25 Declare array with initializer list For each array element, print associated number of asterisks Outline Histogram.java Line 9 Declare array with initializer list Line 19 For each array element, print associated number of asterisks 26 JOptionPane.showMessageDialog( null, outputarea, 27 "Histogram Printing Program", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class Histogram Outline Histogram.java

135 7.4 Examples Using Arrays (Cont.) Using the elements of an array as counters Use a series of counter variables to summarize data 1 // Fig. 7.7: RollDie.java 2 // Roll a six-sided die 6000 times. 3 import javax.swing.*; 4 5 public class RollDie { 6 7 public static void main( String args[] ) 8 { 9 int frequency[] = new int[ 7 ]; // roll die 6000 times; use die value as frequency index 12 for ( int roll = 1; roll <= 6000; roll++ ) 13 ++frequency[ 1 + ( int ) ( Math.random() * 6 ) ]; String output = "Face\tFrequency"; // append frequencies to String output 18 for ( int face = 1; face < frequency.length; face++ ) 19 output += "\n" + face + "\t" + frequency[ face ]; JTextArea outputarea = new JTextArea(); 22 outputarea.settext( output ); JOptionPane.showMessageDialog( null, outputarea, 25 "Rolling a Die 6000 Times", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class RollDie Outline Declare frequency RollDie.java as array of 7ints Line 9 Generate 6000 random Declare frequency integers in range 1-6 as array of 7ints Increment frequency values at index associated with random number Lines Generate 6000 random integers in range 1-6 Line 13 Increment frequency values at index associated with random number

136 7.4 Examples Using Arrays (Cont.) Using arrays to analyze survey results 40 students rate the quality of food 1-10 Rating scale: 1 mean awful, 10 means excellent Place 40 responses in array of integers Summarize results 1 // Fig. 7.8: StudentPoll.java 2 // Student poll program. 3 import javax.swing.*; 4 5 public class StudentPoll { 6 7 public static void main( String args[] ) 8 { 9 int responses[] = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6, 10 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 11 4, 8, 6, 8, 10 }; 12 int frequency[] = new int[ 11 ]; // for each answer, select responses element and use that value 15 // as frequency index to determine element to increment 16 for ( int answer = 0; answer < responses.length; answer++ ) 17 ++frequency[ responses[ answer ] ]; String output = "Rating\tFrequency\n"; // append frequencies to String output 22 for ( int rating = 1; rating < frequency.length; rating++ ) 23 output += rating + "\t" + frequency[ rating ] + "\n"; JTextArea outputarea = new JTextArea(); 26 outputarea.settext( output ); 27 Outline Declare responses as array to store Declare 40 responses frequency as array of 11 int and ignore the first StudentPoll.jav element a For each response, increment frequency values at index associated with that response Lines 9-11 Declare responses as array to store 40 responses Line 12 Declare frequency as array of 11int and ignore the first element Lines For each response, increment frequency values at index associated with that response

137 28 JOptionPane.showMessageDialog( null, outputarea, 29 "Student Poll Program", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class StudentPoll Outline StudentPoll.jav a 7.4 Examples Using Arrays (Cont.) Some additional points When looping through an array Index should never go below 0 Index should be less than total number of array elements When invalid array reference occurs (0 > index or index >= length ) Java generates ArrayIndexOutOfBoundsException Chapter 15 discusses exception handling

138 7.5 References and Reference Parameters Two ways to pass arguments to methods Pass-by-value Copy of argument s value is passed to called method In Java, every primitive is pass-by-value changes of arguments in method do not affect value of caller. Pass-by-reference Caller gives called method direct access to caller s data Called method can manipulate this data Improved performance over pass-by-value In Java, every object is pass-by-reference In Java, arrays are objects Therefore, arrays are passed to methods by reference Java does not allow programmers to choose whether to pass an argument by pass-by-value or by pass-by-reference. 7.6 Passing Arrays to Methods and Return Information To pass array argument to a method Specify array name without brackets Array hourlytemperatures is declared as int hourlytemperatures = new int[ 24 ]; The method call modifyarray( hourlytemperatures ); Passes array hourlytemperatures to method modifyarray Return information of a method: primitive types are returned by value objects are returned by reference

139 1 // Fig. 7.9: PassArray.java 2 // Passing arrays and individual array elements to methods. 3 import java.awt.container; 4 import javax.swing.*; 5 6 public class PassArray extends JApplet { 7 8 // initialize applet 9 public void init() 10 { 11 JTextArea outputarea = new JTextArea(); 12 Container container = getcontentpane(); 13 container.add( outputarea ); int array[] = { 1, 2, 3, 4, 5 }; String output = "Effects of passing entire array by reference:\n" + 18 "The values of the original array are:\n"; // append original array elements to String output 21 for ( int counter = 0; counter < array.length; counter++ ) 22 output += " " + array[ counter ]; 23 Declare 5-int array with initializer list 24 modifyarray( array ); // array passed by reference output += "\n\nthe values of the modified array are:\n"; 27 Outline PassArray.java Line 15 Declare 5-int array with initializer list Line 24 Pass array by Pass array by reference reference to to method method modifyarray modifyarray 28 // append modified array elements to String output 29 for ( int counter = 0; counter < array.length; counter++ ) 30 output += " " + array[ counter ]; output += "\n\neffects of passing array element by value:\n" + 33 "array[3] before modifyelement: " + array[ 3 ]; modifyelement( array[ 3 ] ); // attempt to modify array[ 3 ] output += "\narray[3] after modifyelement: " + array[ 3 ]; 38 outputarea.settext( output ); } // end method init // multiply each element of an array by 2 43 public void modifyarray( int array2[] ) 44 { 45 for ( int counter = 0; counter < array2.length; counter++ ) 46 array2[ counter ] *= 2; 47 } // multiply argument by 2 50 public void modifyelement( int element ) 51 { 52 element *= 2; 53 } } // end class PassArray Pass array[3] by value to method modifyelement Method modifyarray manipulates the array directly Method modifyelement manipulates a primitive s copy The original primitive is left unmodified Outline PassArray.java Line 35 Pass array[3] by value to method modifyelement Lines Method modifyarray manipulates the array directly Lines Method modifyelement manipulates a primitive s copy Lines 52 The original primitive is left unmodified

140 Outline PassArray.java The object passed-by-reference is modified The primitive passed-by-value is unmodified 7.7 Sorting Arrays Sorting data Attracted intense research in computer-science field Bubble sort Smaller values bubble their way to top of array Larger values sink to bottom of array Use nested loops to make several passes through array Each pass compares successive pairs of elements Pairs are left along if increasing order (or equal) Pairs are swapped if decreasing order

141 1 // Fig. 7.10: BubbleSort.java 2 // Sort an array's values into ascending order. 3 import java.awt.*; 4 import javax.swing.*; 5 6 public class BubbleSort extends JApplet { 7 8 // initialize applet 9 public void init() 10 { 11 JTextArea outputarea = new JTextArea(); 12 Container container = getcontentpane(); 13 container.add( outputarea ); int array[] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; String output = "Data items in original order\n"; // append original array values to String output 20 for ( int counter = 0; counter < array.length; counter++ ) 21 output += " " + array[ counter ]; bubblesort( array ); // sort array 24 Declare 10-intarray with initializer list 25 output += "\n\ndata items in ascending order\n"; 26 Pass array by reference to method bubblesort to sort array Outline BubbleSort.java Line 15 Declare 10-int array with initializer list Line 23 Pass array by reference to method bubblesort to sort array 27 // append sorted\ array values to String output 28 for ( int counter = 0; counter < array.length; counter++ ) 29 output += " " + array[ counter ]; outputarea.settext( output ); } // end method init // sort elements of array with bubble sort 36 public void bubblesort( int array2[] ) 37 { 38 // loop to control number of passes 39 for ( int pass = 1; pass < array2.length; pass++ ) { // loop to control number of comparisons 42 for ( int element = 0; 43 element < array2.length - 1; 44 element++ ) { // compare side-by-side elements and swap them if 47 // first element is greater than second element 48 if ( array2[ element ] > array2[ element + 1 ] ) 49 swap( array2, element, element + 1 ); } // end loop to control comparisons } // end loop to control passes } // end method bubblesort Method bubblesort receives array reference as parameter Outline BubbleSort.java Line 36 Method bubblesort receives array reference as parameter Lines Use loop and nested Use loop and nested loop to make loop to make passes passes through array through array If pairs are in decreasing order, invoke method swap to swap pairs Lines If pairs are in decreasing order, invoke method swap to swap pairs

142 56 57 // swap two elements of an array 58 public void swap( int array3[], int first, int second ) 59 { 60 int hold; // temporary holding area for swap hold = array3[ first ]; 63 array3[ first ] = array3[ second ]; 64 array3[ second ] = hold; 65 } } // end class BubbleSort Method swap swaps two values in array reference Outline BubbleSort.java Lines Method swap swaps two values in array reference 7.8 Searching Arrays: Linear Search and Binary Search Searching Finding elements in large amounts of data Determine whether array contains value matching key value Linear searching Binary searching

143 7.8 Searching Arrays: Linear Search and Binary Search (Cont.) Linear search Compare each array element with search key If search key found, return element index If search key not found, return 1 (invalid index) Works best for small or unsorted arrays Inefficient for larger arrays 1 // Fig. 7.11: LinearSearch.java 2 // Linear search of an array. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class LinearSearch extends JApplet implements ActionListener { 8 9 JLabel enterlabel, resultlabel; 10 JTextField enterfield, resultfield; 11 int array[]; // set up applet's GUI 14 public void init() 15 { 16 // get content pane and set its layout to FlowLayout 17 Container container = getcontentpane(); 18 container.setlayout( new FlowLayout() ); // set up JLabel and JTextField for user input 21 enterlabel = new JLabel( "Enter integer search key" ); 22 container.add( enterlabel ); enterfield = new JTextField( 10 ); 25 container.add( enterfield ); // register this applet as enterfield's action listener 28 enterfield.addactionlistener( this ); 29 Declare array of ints Outline LinearSearch.ja va Line 11 Declare array of ints

144 30 // set up JLabel and JTextField for displaying results 31 resultlabel = new JLabel( "Result" ); 32 container.add( resultlabel ); resultfield = new JTextField( 20 ); 35 resultfield.seteditable( false ); 36 container.add( resultfield ); // create array and populate with even integers 0 to array = new int[ 100 ]; for ( int counter = 0; counter < array.length; counter++ ) 42 array[ counter ] = 2 * counter; } // end method init // search array for specified key value 47 public int linearsearch( int array2[], int key ) 48 { 49 // loop through array elements 50 for ( int counter = 0; counter < array2.length; counter++ ) // if array element equals key value, return location 53 if ( array2[ counter ] == key ) 54 return counter; return -1; // key not found } // end method linearsearch Create 100ints for array and populate array with evenints Loop through array If array element at index matches search key, return index Outline LinearSearch.ja va Lines Allocate 100 ints for array and populate array with evenints Line 50 Loop through array Lines If array element at index matches search key, return index // obtain user input and call method linearsearch 61 public void actionperformed( ActionEvent actionevent ) 62 { 63 // input also can be obtained with enterfield.gettext() 64 String searchkey = actionevent.getactioncommand(); // pass array reference to linearsearch; normally, a reference to an 67 // array is passed to a method to search corresponding array object 68 int element = linearsearch( array, Integer.parseInt( searchkey ) ); // display search result 71 if ( element!= -1 ) 72 resultfield.settext( "Found value in element " + element ); 73 else 74 resultfield.settext( "Value not found" ); } // method actionperformed } // end class LinearSearch Invoked when user presses Enter Outline LinearSearch.ja va Line 61 Invoked when user presses Enter Invoke method linearsearch, using array and search key as arguments Line 68 Invoke method linearsearch, using array and search key as arguments

145 7.8 Searching Arrays: Linear Search and Binary Search (Cont.) Binary search Efficient for large, sorted arrays Eliminates half of the elements in search through each pass Compare middle array element to search key If element equals key Return array index If element is less than key Repeat search on first half of array If element is greater then key Repeat search on second half of array Continue search until element equals search key (success) Search contains one element not equal to key (failure) 1 // Fig. 7.12: BinarySearch.java 2 // Binary search of an array. 3 import java.awt.*; 4 import java.awt.event.*; 5 import java.text.*; 6 7 import javax.swing.*; 8 9 public class BinarySearch extends JApplet implements ActionListener { 10 JLabel enterlabel, resultlabel; 11 JTextField enterfield, resultfield; 12 JTextArea output; int array[]; 15 String display = ""; // set up applet's GUI 18 public void init() 19 { 20 // get content pane and set its layout to FlowLayout 21 Container container = getcontentpane(); 22 container.setlayout( new FlowLayout() ); // set up JLabel and JTextField for user input 25 enterlabel = new JLabel( "Enter integer search key" ); 26 container.add( enterlabel ); enterfield = new JTextField( 10 ); 29 container.add( enterfield ); 30 Declare array of ints Outline BinarySearch.ja va Line 14 Declare array of ints

146 31 // register this applet as enterfield's action listener 32 enterfield.addactionlistener( this ); // set up JLabel and JTextField for displaying results 35 resultlabel = new JLabel( "Result" ); 36 container.add( resultlabel ); resultfield = new JTextField( 20 ); 39 resultfield.seteditable( false ); 40 container.add( resultfield ); // set up JTextArea for displaying comparison data 43 output = new JTextArea( 6, 60 ); 44 output.setfont( new Font( "Monospaced", Font.PLAIN, 12 ) ); 45 container.add( output ); // create array and fill with even integers 0 to array = new int[ 15 ]; for ( int counter = 0; counter < array.length; counter++ ) 51 array[ counter ] = 2 * counter; } // end method init // obtain user input and call method binarysearch 56 public void actionperformed( ActionEvent actionevent ) 57 { 58 // input also can be obtained with enterfield.gettext() 59 String searchkey = actionevent.getactioncommand(); 60 Outline BinarySearch.ja va Lines Allocate 15ints for array and populate array with even ints Allocate 15ints for array and populate array with evenintsline 56 Invoked when user presses Enter Invoked when user presses Enter 61 // initialize display string for new search 62 display = "Portions of array searched\n"; // perform binary search 65 int element = binarysearch( array, Integer.parseInt( searchkey ) ); output.settext( display ); // display search result 70 if ( element!= -1 ) 71 resultfield.settext( "Found value in element " + element ); 72 else 73 resultfield.settext( "Value not found" ); } // end method actionperformed // method to perform binary search of an array 78 public int binarysearch( int array2[], int key ) 79 { 80 int low = 0; // low element index 81 int high = array2.length - 1; // high element index 82 int middle; // middle element index // loop until low index is greater than high index 85 while ( low <= high ) { 86 middle = ( low + high ) / 2; // determine middle index // display subset of array elements used in this 89 // iteration of binary search loop 90 buildoutput( array2, low, middle, high ); Outline BinarySearch.ja va Invoke method binarysearch, Line using 65 array and search key as arguments Invoke method binarysearch, using array and search key as arguments

147 91 92 // if key matches middle element, return middle location 93 if ( key == array[ middle ] ) 94 return middle; // if key less than middle element, set new high element 97 else if ( key < array[ middle ] ) 98 high = middle - 1; // key greater than middle element, set new low element 101 else 102 low = middle + 1; } // end while return -1; // key not found } // end method binarysearch // build row of output showing subset of array elements 111 // currently being processed 112 void buildoutput( int array3[], int low, int middle, int high ) 113 { 114 // create 2-digit integer number format 115 DecimalFormat twodigits = new DecimalFormat( "00" ); 116 If search key matches middle array element, return element index Outline BinarySearch.ja va Lines If search key matches middle array If search key is greater than middle array element, If search repeat key is search less than on second middle arrayhalf element, repeat search on first array half element, return element index Lines If search key is less than middle array element, repeat search Method buildoutput displays on first array half array contents being searched Lines If search key is greater than middle array element, repeat search on second array half Lines Method build- Output displays array contents being searched 117 // loop through array elements 118 for ( int counter = 0; counter < array3.length; counter++ ) { // if counter outside current array subset, append 121 // padding spaces to String display 122 if ( counter < low counter > high ) 123 display += " "; // if middle element, append element to String display 126 // followed by asterisk (*) to indicate middle element 127 else if ( counter == middle ) 128 display += twodigits.format( array3[ counter ] ) + "* "; else // append element to String display 131 display += twodigits.format( array3[ counter ] ) + " "; } // end for display += "\n"; } // end method buildoutput } // end class BinarySearch Display an asterisk next to middle element Outline BinarySearch.ja va Line 128 Display an asterisk next to middle element

148 Outline BinarySearch.ja va 7.9 Multidimensional Arrays Multidimensional arrays Tables with rows and columns Two-dimensional array Declaring two-dimensional array b[2][2] int b[][] = { { 1, 2 }, { 3, 4 } }; 1 and 2 initialize b[0][0] and b[0][1] 3 and 4 initialize b[1][0] and b[1][1] int b[][] = { { 1, 2 }, { 3, 4, 5 } }; row 0 contains elements 1 and 2 row 1 contains elements 3, 4 and 5

149 7.9 Multidimensional Arrays (Cont.) Creating multidimensional arrays Can be allocated dynamically 3-by-4 array int b[][]; b = new int[ 3 ][ 4 ]; Rows can have different number of columns int b[][]; b = new int[ 2 ][ ]; // allocate rows b[ 0 ] = new int[ 5 ]; // allocate row 0 b[ 1 ] = new int[ 3 ]; // allocate row 1 Column 0 Column 1 Column 2 Column 3 Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ] Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ] Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ] Column index Row index Array name Fig Two-dimensional array with three rows and four columns.

150 1 // Fig. 7.14: InitArray.java 2 // Initializing two-dimensional arrays. 3 import java.awt.container; 4 import javax.swing.*; 5 6 public class InitArray extends JApplet { 7 JTextArea outputarea; 8 9 // set up GUI and initialize applet 10 public void init() 11 { 12 outputarea = new JTextArea(); 13 Container container = getcontentpane(); 14 container.add( outputarea ); int array1[][] = { { 1, 2, 3 }, { 4, 5, 6 } }; 17 int array2[][] = { { 1, 2 }, { 3 }, { 4, 5, 6 } }; outputarea.settext( "Values in array1 by row are\n" ); 20 buildoutput( array1 ); outputarea.append( "\nvalues in array2 by row are\n" ); 23 buildoutput( array2 ); } // end method init 26 Outline InitArray.java Declare array1 with six Line 16 initializersin two sublists Declare array1 with six initializers in two sublists Declare array2 with six initializersin three sublists Line 17 Declare array2 with six initializers in three sublists 27 // append rows and columns of an array to outputarea 28 public void buildoutput( int array[][] ) 29 { 30 // loop through array's rows 31 for ( int row = 0; row < array.length; row++ ) { // loop through columns of current row 34 for ( int column = 0; column < array[ row ].length; column++ ) 35 outputarea.append( array[ row ][ column ] + " " ); outputarea.append( "\n" ); 38 } } // end method buildoutput } // end class InitArray Outline array[row].length returns number of columns associated with rowinitarray.java subscript Use double-bracket notation to access two-dimensional array values Line 34 array[row].leng th returns number of columns associated with row subscript Line 35 Use double-bracket notation to access twodimensional array values

151 1 // Fig. 7.15: DoubleArray.java 2 // Two-dimensional array example. 3 import java.awt.*; 4 import javax.swing.*; 5 6 public class DoubleArray extends JApplet { 7 int grades[][] = { { 77, 68, 86, 73 }, 8 { 96, 87, 89, 81 }, 9 { 70, 90, 86, 81 } }; int students, exams; 12 String output; 13 JTextArea outputarea; // initialize fields 16 public void init() 17 { 18 students = grades.length; // number of students 19 exams = grades[ 0 ].length; // number of exams // create JTextArea and attach to applet 22 outputarea = new JTextArea(); 23 Container container = getcontentpane(); 24 container.add( outputarea ); 25 Each row represents a student; each column represents an exam grade Outline Declare grades as 3-by-4 array DoubleArray.jav a Lines 7-9 Declare grades as 3- by-4 array Lines 7-9 Each row represents a student; each column represents an exam grade 26 // build output string 27 output = "The array is:\n"; 28 buildstring(); // call methods minimum and maximum 31 output += "\n\nlowest grade: " + minimum() + 32 "\nhighest grade: " + maximum() + "\n"; // call method average to calculate each student's average 35 for ( int counter = 0; counter < students; counter++ ) 36 output += "\naverage for student " + counter + " is " + 37 average( grades[ counter ] ); // pass one row of array grades // change outputarea's display font 40 outputarea.setfont( new Font( "Monospaced", Font.PLAIN, 12 ) ); // place output string in outputarea 43 outputarea.settext( output ); } // end method init // find minimum grade 48 public int minimum() 49 { 50 // assume first element of grades array is smallest 51 int lowgrade = grades[ 0 ][ 0 ]; 52 Determine average for each student Outline DoubleArray.jav Determine a minimum and maximum for all student Lines Determine minimum and maximum for all student Lines Determine average for each student

152 53 // loop through rows of grades array 54 for ( int row = 0; row < students; row++ ) // loop through columns of current row 57 for ( int column = 0; column < exams; column++ ) // if grade is less than lowgrade, assign it to lowgrade 60 if ( grades[ row ][ column ] < lowgrade ) 61 lowgrade = grades[ row ][ column ]; return lowgrade; // return lowest grade } // end method minimum // find maximum grade 68 public int maximum() 69 { 70 // assume first element of grades array is largest 71 int highgrade = grades[ 0 ][ 0 ]; // loop through rows of grades array 74 for ( int row = 0; row < students; row++ ) // loop through columns of current row 77 for ( int column = 0; column < exams; column++ ) // if grade is greater than highgrade, assign it to highgrade 80 if ( grades[ row ][ column ] > highgrade ) 81 highgrade = grades[ row ][ column ]; Use a nested loop to search for lowest grade in series Use a nested loop to search for highest grade in series Outline DoubleArray.jav a Lines Use a nested loop to search for lowest grade in series Lines Use a nested loop to search for highest grade in series return highgrade; // return highest grade } // end method maximum // determine average grade for particular student (or set of grades) 88 public double average( int setofgrades[] ) 89 { 90 int total = 0; // initialize total // sum grades for one student 93 for ( int count = 0; count < setofgrades.length; count++ ) 94 total += setofgrades[ count ]; // return average of grades 97 return ( double ) total / setofgrades.length; } // end method average // build output string 102 public void buildstring() 103 { 104 output += " "; // used to align column heads // create column heads 107 for ( int counter = 0; counter < exams; counter++ ) 108 output += "[" + counter + "] "; Outline Method average takes DoubleArray.jav array of student test results as aparameter Line 88 Calculate sum of array elements Method average takes array of student test results as parameter Divide by number of elements to get average Lines Calculate sum of array elements Line 97 Divide by number of elements to get average

153 // create rows/columns of text representing array grades 111 for ( int row = 0; row < students; row++ ) { 112 output += "\ngrades[" + row + "] "; for ( int column = 0; column < exams; column++ ) 115 output += grades[ row ][ column ] + " "; 116 } } // end method buildstring } // end class DoubleArray Outline DoubleArray.jav a Summary Array is an indexed collection of data values Array elements: values of primitive data type or objects All array elements must have same data type Array is created with new operator Array can have multiple indices. Arrays are passed to methods by reference

154 Part 8: Collections Arrays Collections Lists Sets Maps 2003 Prentice Hall, Inc. All rights reserved Collections Overview Collection Data structure (object) that can hold references to other objects Collection Interfaces Interfaces declare operations for various collection types Belong to package java.util Collection Set List Map Collection implementations execute these operations Collections framework contains several implementations of Collection Interfaces

155 Class Arrays 22.3 Class Arrays Provides static methods for manipulating arrays Provides high-level methods Method binarysearch for searching sorted arrays Method equals for comparing arrays Method fill for placing values into arrays Method sort for sorting arrays 1 // Fig. 22.1: UsingArrays.java 2 // Using Java arrays. 3 import java.util.*; 4 5 public class UsingArrays { 6 private int intvalues[] = { 1, 2, 3, 4, 5, 6 }; 7 private double doublevalues[] = { 8.4, 9.3, 0.2, 7.9, 3.4 }; 8 private int filledint[], intvaluescopy[]; 9 10 // initialize arrays 11 public UsingArrays() 12 { 13 filledint = new int[ 10 ]; 14 intvaluescopy = new int[ intvalues.length ]; Arrays.fill( filledint, 7 ); // fill with 7s Arrays.sort( doublevalues ); // sort doublevalues ascending // copy array intvalues into array intvaluescopy 21 System.arraycopy( intvalues, 0, intvaluescopy, 22 0, intvalues.length ); 23 } 24 Outline UsingArrays.jav a Line 16 Line 18 Lines Use static method fill of class Arrays to populate array with 7s Use static method sort of class Arrays to sort array s elements in ascending order Use static method arraycopy of class System to copy array intvalues into array intvaluescopy

156 25 // output values in each array 26 public void printarrays() 27 { 28 System.out.print( "doublevalues: " ); for ( int count = 0; count < doublevalues.length; count++ ) 31 System.out.print( doublevalues[ count ] + " " ); System.out.print( "\nintvalues: " ); for ( int count = 0; count < intvalues.length; count++ ) 36 System.out.print( intvalues[ count ] + " " ); System.out.print( "\nfilledint: " ); for ( int count = 0; count < filledint.length; count++ ) 41 System.out.print( filledint[ count ] + " " ); System.out.print( "\nintvaluescopy: " ); for ( int count = 0; count < intvaluescopy.length; count++ ) 46 System.out.print( intvaluescopy[ count ] + " " ); System.out.println(); } // end method printarrays 51 Outline UsingArrays.jav a 52 // find value in array intvalues 53 public int searchforint( int value ) 54 { 55 return Arrays.binarySearch( intvalues, value ); 56 } // compare array contents 59 public void printequality() 60 { 61 boolean b = Arrays.equals( intvalues, intvaluescopy ); System.out.println( "intvalues " + ( b? "==" : "!=" ) + 64 " intvaluescopy" ); b = Arrays.equals( intvalues, filledint ); System.out.println( "intvalues " + ( b? "==" : "!=" ) + 69 " filledint" ); 70 } 71 Outline Use static method binarysearch UsingArrays.jav of class to perform binary a search on array Line 55 Lines 61 and 66 Use static method equals of class Arrays to determine whether values of the two arrays are equivalent

157 72 public static void main( String args[] ) 73 { 74 UsingArrays usingarrays = new UsingArrays(); usingarrays.printarrays(); 77 usingarrays.printequality(); int location = usingarrays.searchforint( 5 ); 80 System.out.println( ( location >= 0? "Found 5 at element " + 81 location : "5 not found" ) + " in intvalues" ); location = usingarrays.searchforint( 8763 ); 84 System.out.println( ( location >= 0? "Found 8763 at element " + 85 location : "8763 not found" ) + " in intvalues" ); 86 } } // end class UsingArrays Outline UsingArrays.jav a doublevalues: intvalues: filledint: intvaluescopy: intvalues == intvaluescopy intvalues!= filledint Found 5 at element 4 in intvalues 8763 not found in intvalues Viewing an Array as a List 1 // Fig. 22.2: UsingAsList.java 2 // Using method aslist. 3 import java.util.*; 4 5 public class UsingAsList { 6 private static final String values[] = { "red", "white", "blue" }; 7 private List list; 8 9 // initialize List and set value at location 1 10 public UsingAsList() 11 { 12 list = Arrays.asList( values ); // get List 13 list.set( 1, "green" ); // change a value 14 } // output List and array 17 public void printelements() 18 { 19 System.out.print( "List elements : " ); for ( int count = 0; count < list.size(); count++ ) 22 System.out.print( list.get( count ) + " " ); System.out.print( "\narray elements: " ); 25 Collections Framework enables the programmer to view elements of one collection type as elements of a different collection type. E.g. Arrays can be viewed as Lists Outline UsingAsList.jav a Line 12 Use static method aslist of class Arrays Line 13 to return List view of array values Line 21 Use method set of List object to change Line 22 the contents of element 1 to "green" List method size returns number of elements in List List method get returns individual element in List

158 26 for ( int count = 0; count < values.length; count++ ) 27 System.out.print( values[ count ] + " " ); System.out.println(); 30 } public static void main( String args[] ) 33 { 34 new UsingAsList().printElements(); 35 } } // end class UsingAsList Outline UsingAsList.jav a List elements : red green blue Array elements: red green blue Arrays.asList creates a fixed-sized List that operates faster than any provided List implementations A List created with Arrays.asList has fixed size. calling methods add or remove throws an UnsupportedOperationException 22.4 Interface Collection and Class Collections Interface Collection root interface in the Collections hierarchy Contains bulk operations Adding, clearing, comparing and retaining objects Interfaces Set and List extend interface Collection Class Collections Provides static methods that manipulate collections Collections can be manipulated polymorphically

159 22.5 Lists List Ordered Collection that can contain duplicate elements Sometimes called a sequence 1 st List element index is 0. Several classes implement interface List ArrayList: resizable-array implementation of a List LinkedList: linke-list implementation of a list Vector: simialar to ArrayList but worse performance 1 // Fig. 22.3: CollectionTest.java 2 // Using the Collection interface. 3 import java.awt.color; 4 import java.util.*; 5 6 public class CollectionTest { 7 private static final String colors[] = { "red", "white", "blue" }; 8 9 // create ArrayList, add objects to it and manipulate it 10 public CollectionTest() 11 { 12 List list = new ArrayList(); // add objects to list 15 list.add( Color.MAGENTA ); // add a color object for ( int count = 0; count < colors.length; count++ ) 18 list.add( colors[ count ] ); list.add( Color.CYAN ); // add a color object // output list contents 23 System.out.println( "\narraylist: " ); for ( int count = 0; count < list.size(); count++ ) 26 System.out.print( list.get( count ) + " " ); 27 Outline CollectionTest. java Lines Line 26 Use List method add to add objects to ArrayList List method get returns individual element in List

160 28 // remove all String objects 29 removestrings( list ); // output list contents 32 System.out.println( "\n\narraylist after calling removestrings: " ); for ( int count = 0; count < list.size(); count++ ) 35 System.out.print( list.get( count ) + " " ); } // end constructor CollectionTest // remove String objects from Collection 40 private void removestrings( Collection collection ) 41 { 42 Iterator iterator = collection.iterator(); // get iterator // loop while collection has items 45 while ( iterator.hasnext() ) if ( iterator.next() instanceof String ) 48 iterator.remove(); // remove String object 49 } 50 Method removestrings takes a Collection as an argument; Outline Line 31 passes List, which extends Collection, to this method CollectionTest. java Line 29 Line 42 Line 45 Obtain Collection Line 47iterator Iterator method Line 48 hasnext determines whether the Iterator contains more elements Iterator method next returns next Object in Iterator Use Iterator method remove to Iterator is more flexible than Enumeration. remove String from Iterator Iterator can remore elements from collection. Enumeration cannot remove elements from collections. 51 public static void main( String args[] ) 52 { 53 new CollectionTest(); 54 } } // end class CollectionTest Outline CollectionTest. java ArrayList: java.awt.color[r=255,g=0,b=255] red white blue java.awt.color [r=0,g=255,b=255] ArrayList after calling removestrings: java.awt.color[r=255,g=0,b=255] java.awt.color[r=0,g=255,b=255]

161 1 // Fig. 22.4: ListTest.java 2 // Using LinkLists. 3 import java.util.*; 4 5 public class ListTest { 6 private static final String colors[] = { "black", "yellow", 7 "green", "blue", "violet", "silver" }; 8 private static final String colors2[] = { "gold", "white", 9 "brown", "blue", "gray", "silver" }; // set up and manipulate LinkedList objects 12 public ListTest() 13 { Outline ListTest.java Lines Line 23 Line List link = new LinkedList(); 15 List link2 = new LinkedList(); Create two LinkedList objects // add elements to each list 18 for ( int count = 0; count < colors.length; count++ ) { 19 link.add( colors[ count ] ); 20 link2.add( colors2[ count ] ); 21 } link.addall( link2 ); // concatenate lists 24 link2 = null; // release resources 25 Use LinkedList method addall to append link2 elements to link Nullify link2, so it can be garbage collected Outline 26 printlist( link ); uppercasestrings( link ); 29 ListTest.java 30 printlist( link ); 31 Lines System.out.print( "\ndeleting elements 4 to 6..." ); 33 removeitems( link, 4, 7 ); printlist( link ); printreversedlist( link ); } // end constructor ListTest // output List contents 42 public void printlist( List list ) Use List method get to obtain object 43 { in LinkedList, then print its value 44 System.out.println( "\nlist: " ); for ( int count = 0; count < list.size(); count++ ) 47 System.out.print( list.get( count ) + " " ); System.out.println(); 50 }

162 51 52 // locate String objects and convert to uppercase 53 private void uppercasestrings( List list ) 54 { 55 ListIterator iterator = list.listiterator(); while ( iterator.hasnext() ) { 58 Object object = iterator.next(); // get item if ( object instanceof String ) // check for String 61 iterator.set( ( ( String ) object ).touppercase() ); 62 } 63 } // obtain sublist and use clear method to delete sublist items 66 private void removeitems( List list, int start, int end ) 67 { 68 list.sublist( start, end ).clear(); // remove items 69 } // print reversed list 72 private void printreversedlist( List list ) 73 { 74 ListIterator iterator = list.listiterator( list.size() ); 75 Outline Use ListIterator to traverse LinkedList elements and convert them to upper case (if elements are Strings) ListTest.java Lines Line 68 Use List methods sublist and clear to remove LinkedList elements

163 76 System.out.println( "\nreversed List:" ); // print list in reverse order 79 while( iterator.hasprevious() ) 80 System.out.print( iterator.previous() + " " ); 81 } public static void main( String args[] ) 84 { 85 new ListTest(); 86 } } // end class ListTest list: black yellow green blue violet silver gold white brown blue gray silver list: BLACK YELLOW GREEN BLUE VIOLET SILVER GOLD WHITE BROWN BLUE GRAY SILVER Deleting elements 4 to 6... list: BLACK YELLOW GREEN BLUE WHITE BROWN BLUE GRAY SILVER Reversed List: SILVER GRAY BLUE BROWN WHITE BLUE GREEN YELLOW BLACK Outline ListIterator method hasprevious determines ListTest.java whether the ListIterator contains more elements Line 79 ListIterator method previous Line 80 returns previous Object in ListIterator 1 // Fig. 22.5: UsingToArray.java 2 // Using method toarray. 3 import java.util.*; 4 5 public class UsingToArray { 6 7 // create LinkedList, add elements and convert to array 8 public UsingToArray() 9 { 10 String colors[] = { "black", "blue", "yellow" }; LinkedList links = new LinkedList( Arrays.asList( colors ) ); links.addlast( "red" ); // add as last item 15 links.add( "pink" ); // add to the end 16 links.add( 3, "green" ); // add at 3rd index 17 links.addfirst( "cyan" ); // add as first item // get LinkedList elements as an array 20 colors = ( String [] ) links.toarray( new String[ links.size() ] ); System.out.println( "colors: " ); 23 Outline UsingToArray.ja va Line 20 Use List method toarray to obtain array representation of LinkedList

164 24 for ( int count = 0; count < colors.length; count++ ) 25 System.out.println( colors[ count ] ); 26 } public static void main( String args[] ) 29 { 30 new UsingToArray(); 31 } } // end class UsingToArray Outline UsingToArray.ja va colors: cyan black blue yellow green red pink 22.6 Algorithms Collections Framework provides set of algorithms Implemented as static methods algorithms of class List sort binarysearch reverse shuffle fill copy algorithms of class Collections min max The collections-framework algorithms are polymorphic.

165 sort Algorithm sort Sorts List elements Order is determined by natural order of elements type Relatively fast: n log(n) separate parameter can be used to modify ordering of elements Outline 1 // Fig. 22.6: Sort1.java 2 // Using algorithm sort. 3 import java.util.*; 4 Sort1.java 5 public class Sort1 { 6 private static final String suits[] = Line 13 7 { "Hearts", "Diamonds", "Clubs", "Spades" }; 8 9 // display array elements Line public void printelements() 11 { 12 // create ArrayList 13 List list = new ArrayList( Arrays.asList( suits ) ); Create ArrayList // output list 16 System.out.println( "Unsorted array elements:\n" + list ); Collections.sort( list ); // sort ArrayListUse Collections method // output list sort to sort ArrayList 21 System.out.println( "Sorted array elements:\n" + list ); 22 } 23

166 24 public static void main( String args[] ) 25 { 26 new Sort1().printElements(); 27 } } // end class Sort1 Outline Sort1.java Unsorted array elements: [Hearts, Diamonds, Clubs, Spades] Sorted array elements: [Clubs, Diamonds, Hearts, Spades] Outline 1 // Fig. 22.7: Sort2.java 2 // Using a Comparator object with algorithm sort. 3 import java.util.*; 4 Sort2.java 5 public class Sort2 { 6 private static final String suits[] = Line 18 7 { "Hearts", "Diamonds", "Clubs", "Spades" }; 8 9 // output List elements Line public void printelements() Method reverseorder of class 11 { Collections returns a 12 List list = Arrays.asList( suits ); // create List Comparator object that represents // output List elements the collection s reverse order 15 System.out.println( "Unsorted array elements:\n" + list ); // sort in descending order using a comparator 18 Collections.sort( list, Collections.reverseOrder() ); // output List elements 21 System.out.println( "Sorted list elements:\n" + list ); 22 } 23 Method sort of class Collections can use a Comparator object to sort a List

167 24 public static void main( String args[] ) 25 { 26 new Sort2().printElements(); 27 } } // end class Sort2 Outline Sort2.java Unsorted array elements: [Hearts, Diamonds, Clubs, Spades] Sorted list elements: [Spades, Hearts, Diamonds, Clubs] 1 // Fig. 22.8: Sort3.java 2 // Creating a custom Comparator class. 3 import java.util.*; 4 5 public class Sort3 { 6 7 public void printelements() 8 { 9 List list = new ArrayList(); // create List list.add( new Time2( 6, 24, 34 ) ); 12 list.add( new Time2( 18, 14, 05 ) ); 13 list.add( new Time2( 8, 05, 00 ) ); 14 list.add( new Time2( 12, 07, 58 ) ); 15 list.add( new Time2( 6, 14, 22 ) ); // output List elements Sort in order using a custom comparator TimeComparator. 18 System.out.println( "Unsorted array elements:\n" + list ); // sort in order using a comparator 21 Collections.sort( list, new TimeComparator() ); // output List elements 24 System.out.println( "Sorted list elements:\n" + list ); 25 } 26 Outline Sort3.java Line 21

168 Outline 27 public static void main( String args[] ) Custom comparator 28 { 29 new Sort2().printElements(); TimeComparator implements 30 } Comparator interface. Sort3.java 31 Implement method compare to 32 private class TimeComparator implements Comparator { determine the order of two objects. 33 int hourcompare, minutecompare, secondcompare; 34 Time2 time1, time2; 35 Line 32 Line public int compare(object object1, Object object2) 37 { 38 // cast the objects 39 time1 = (Time2)object1; 40 time2 = (Time2)object2; hourcompare = new Integer( time1.gethour() ).compareto( 43 new Integer( time2.gethour() ) ); // test the hour first 46 if ( hourcompare!= 0 ) 47 return hourcompare; minutecompare = new Integer( time1.getminute() ).compareto( 50 new Integer( time2.getminute() ) ); // then test the minute 53 if ( minutecompare!= 0 ) 54 return minutecompare; secondcompare = new Integer( time1.getsecond() ).compareto( 57 new Integer( time2.getsecond() ) ); return secondcompare; // return result of comparing seconds 60 } } // end class TimeComparator } // end class Sort3 Outline Sort3.java Unsorted array elements: [06:24:34, 18:14:05, 08:05:00, 12:07:58, 06:14:22] Sorted list elements: [06:14:22, 06:24:34, 08:05:00, 12:07:58, 18:14:05]

169 shuffle Algorithm shuffle Randomly orders List elements 1 // Fig. 22.9: Cards.java 2 // Using algorithm shuffle. 3 import java.util.*; 4 5 // class to represent a Card in a deck of cards 6 class Card { 7 private String face; 8 private String suit; 9 10 // initialize a Card 11 public Card( String initialface, String initialsuit ) 12 { 13 face = initialface; 14 suit = initialsuit; 15 } // return face of Card 18 public String getface() 19 { 20 return face; 21 } // return suit of Card 24 public String getsuit() 25 { 26 return suit; 27 } Outline Cards.java

170 28 29 // return String representation of Card 30 public String tostring() 31 { 32 StringBuffer buffer = new StringBuffer( face + " of " + suit ); 33 buffer.setlength( 20 ); return buffer.tostring(); 36 } } // end class Card // class Cards declaration 41 public class Cards { 42 private static final String suits[] = 43 { "Hearts", "Clubs", "Diamonds", "Spades" }; 44 private static final String faces[] = { "Ace", "Deuce", "Three", 45 "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", 46 "Jack", "Queen", "King" }; 47 private List list; // set up deck of Cards and shuffle 50 public Cards() 51 { 52 Card deck[] = new Card[ 52 ]; 53 Outline Cards.java 54 for ( int count = 0; count < deck.length; count++ ) 55 deck[ count ] = new Card( faces[ count % 13 ], 56 suits[ count / 13 ] ); list = Arrays.asList( deck ); // get List 59 Collections.shuffle( list ); // shuffle deck 60 } // output deck 63 public void printcards() 64 { 65 int half = list.size() / 2-1; for ( int i = 0, j = half + 1; i <= half; i++, j++ ) Use method shuffle of class Collections to shuffle List 68 System.out.println( list.get( i ).tostring() + list.get( j ).tostring()); 69 } public static void main( String args[] ) 72 { 73 new Cards().printCards(); 74 } } // end class Cards Outline Cards.java Line 59

171 King of Diamonds Four of Diamonds King of Hearts Three of Spades Four of Hearts Five of Diamonds Queen of Diamonds Seven of Diamonds Nine of Hearts Ten of Spades Three of Hearts Six of Hearts Six of Diamonds Ace of Clubs Eight of Clubs Jack of Clubs Seven of Clubs Five of Clubs Nine of Spades King of Spades Ten of Hearts Queen of Clubs Three of Diamonds Four of Clubs Eight of Spades Jack of Hearts Jack of Spades Six of Clubs Nine of Diamonds Four of Spades Seven of Spades Eight of Hearts Five of Hearts Seven of Hearts Three of Clubs Deuce of Hearts Ace of Spades Eight of Diamonds Deuce of Clubs Ten of Diamonds Queen of Hearts Ten of Clubs Queen of Spades Six of Spades Nine of Clubs Ace of Diamonds Ace of Hearts Deuce of Spades King of Clubs Jack of Diamonds Five of Spades Deuce of Diamonds Outline Cards.java Algorithms reverse, fill, copy, max and min Class Collections provides algorithms: reverse Reverses the order of List elements fill Populates List elements with values copy Creates copy of a List max Returns largest element in List min Returns smallest element in List

172 1 // Fig : Algorithms1.java 2 // Using algorithms reverse, fill, copy, min and max. 3 import java.util.*; 4 5 public class Algorithms1 { 6 private String letters[] = { "P", "C", "M" }, letterscopy[]; 7 private List list, copylist; 8 9 // create a List and manipulate it with methods from Collections 10 public Algorithms1() 11 { 12 list = Arrays.asList( letters ); // get List 13 letterscopy = new String[ 3 ]; 14 copylist = Arrays.asList( letterscopy ); System.out.println( "Initial list: " ); 17 output( list ); Collections.reverse( list ); // reverse order 20 System.out.println( "\nafter calling reverse: " ); 21 output( list ); Collections.copy( copylist, list ); // copy List 24 System.out.println( "\nafter copying: " ); 25 output( copylist ); 26 Outline Algorithms1.jav a Line 19 Line 23 Use method reverse of class Collections to obtain List in reverse order Use method copy of class Collections to obtain copy of List 27 Collections.fill( list, "R" ); Use method // fill fill list of with class RsCollections 28 System.out.println( "\nafter calling fill: " ); to populate List with the letter "R" 29 output( list ); } // end constructor // output List information 34 private void output( List listref ) 35 { 36 System.out.print( "The list is: " ); for ( int k = 0; k < listref.size(); k++ ) 39 System.out.print( listref.get( k ) + " " ); System.out.print( "\nmax: " + Collections.max( listref ) ); 42 System.out.println( " Min: " + Collections.min( listref ) ); 43 } public static void main( String args[] ) 46 { 47 new Algorithms1(); 48 } } // end class Algorithms1 Outline Algorithms1.jav a Line 27 Line 41 Line 42 Obtain maximum value in List Obtain minimum value in List

173 Initial list: The list is: P C M Max: P Min: C After calling reverse: The list is: M C P Max: P Min: C Outline Algorithms1.jav a After copying: The list is: M C P Max: P Min: C After calling fill: The list is: R R R Max: R Min: R Algorithm binarysearch binarysearch static method of class Collections Locates Object in List (i.e. LinkeList, Vector, ArrayList) Returns index of Object in List if Object exists Returns negative value if Object does not exist If multiple list elements match with search key, no guarantee which one will be returned prerequisite: list s element must be sorted in ascending order.

174 1 // Fig : BinarySearchTest.java 2 // Using algorithm binarysearch. 3 import java.util.*; 4 5 public class BinarySearchTest { 6 private static final String colors[] = { "red", "white", 7 "blue", "black", "yellow", "purple", "tan", "pink" }; 8 private List list; // List reference 9 10 // create, sort and output list 11 public BinarySearchTest() 12 { 13 list = new ArrayList( Arrays.asList( colors ) ); 14 Collections.sort( list ); // sort the ArrayList 15 System.out.println( "Sorted ArrayList: " + list ); 16 } // search list for various values 19 private void printsearchresults() 20 { 21 printsearchresultshelper( colors[ 3 ] ); // first item 22 printsearchresultshelper( colors[ 0 ] ); // middle item 23 printsearchresultshelper( colors[ 7 ] ); // last item 24 printsearchresultshelper( "aardvark" ); // below lowest 25 printsearchresultshelper( "goat" ); // does not exist 26 printsearchresultshelper( "zebra" ); // does not exist 27 } 28 Outline BinarySearchTes t.java Line 14 Sort List in ascending order 29 // helper method to perform searches 30 private void printsearchresultshelper( String key ) 31 { 32 int result = 0; System.out.println( "\nsearching for: " + key ); 35 result = Collections.binarySearch( list, key ); 36 System.out.println( ( result >= 0? "Found at index " + result : 37 "Not Found (" + result + ")" ) ); 38 } public static void main( String args[] ) 41 { 42 new BinarySearchTest().printSearchResults(); 43 } } // end class BinarySearchTest Sorted ArrayList: black blue pink purple red tan white yellow Searching for: black Found at index 0 Searching for: red Found at index 4 Searching for: pink Found at index 2 Searching for: aardvark Not Found (-1) Searching for: goat Not Found (-3) Searching for: zebra Not Found (-9) Outline BinarySearchTes t.java Line 35 Use method binarysearch of class Collections to search List for specified key

175 Set 22.7 Sets Collection that contains unique elements Collections framework contains several Set implementations: HashSet Stores elements in hash table TreeSet Stores elements in tree 1 // Fig : SetTest.java 2 // Using a HashSet to remove duplicates. 3 import java.util.*; 4 5 public class SetTest { 6 private static final String colors[] = { "red", "white", "blue", 7 "green", "gray", "orange", "tan", "white", "cyan", 8 "peach", "gray", "orange" }; 9 10 // create and output ArrayList 11 public SetTest() 12 { 13 List list = new ArrayList( Arrays.asList( colors ) ); 14 System.out.println( "ArrayList: " + list ); 15 printnonduplicates( list ); 16 } // create set from array to eliminate duplicates 19 private void printnonduplicates( Collection collection ) 20 { 21 // create a HashSet and obtain its iterator 22 Set set = new HashSet( collection ); 23 Iterator iterator = set.iterator(); System.out.println( "\nnonduplicates are: " ); 26 Outline SetTest.java Line 22 Create HashSet from Collection object

176 27 while ( iterator.hasnext() ) 28 System.out.print( iterator.next() + " " ); System.out.println(); 31 } public static void main( String args[] ) 34 { 35 new SetTest(); 36 } } // end class SetTest Use Iterator to traverse HashSet and print nonduplicates Outline SetTest.java Lines ArrayList: [red, white, blue, green, gray, orange, tan, white, cyan, peach, gray, orange] Nonduplicates are: red cyan white tan gray green orange blue peach 1 // Fig : SortedSetTest.java 2 // Using TreeSet and SortedSet. 3 import java.util.*; 4 5 public class SortedSetTest { 6 private static final String names[] = { "yellow", "green", 7 "black", "tan", "grey", "white", "orange", "red", "green" }; 8 9 // create a sorted set with TreeSet, then manipulate it 10 public SortedSetTest() 11 { 12 SortedSet tree = new TreeSet( Arrays.asList( names ) ); System.out.println( "set: " ); 15 printset( tree ); // get headset based upon "orange" 18 System.out.print( "\nheadset (\"orange\"): " ); 19 printset( tree.headset( "orange" ) ); // get tailset based upon "orange" 22 System.out.print( "tailset (\"orange\"): " ); 23 printset( tree.tailset( "orange" ) ); // get first and last elements 26 System.out.println( "first: " + tree.first() ); 27 System.out.println( "last : " + tree.last() ); 28 } 29 Outline SortedSetTest.j ava Line 12 Line 19 Create TreeSet from Line names 23 array Lines Use TreeSet method headset to get TreeSet subset less than "orange" Use TreeSet method tailset to get TreeSet subset greater than "orange" Methods first and last obtain smallest and largest TreeSet elements, respectively

177 30 // output set 31 private void printset( SortedSet set ) 32 { 33 Iterator iterator = set.iterator(); while ( iterator.hasnext() ) 36 System.out.print( iterator.next() + " " ); System.out.println(); 39 } public static void main( String args[] ) 42 { 43 new SortedSetTest(); 44 } } // end class SortedSetTest Outline SortedSetTest.j Use Iterator to ava traverse SortedSet and print values Lines set: black green grey orange red tan white yellow headset ("orange"): black green grey tailset ("orange"): orange red tan white yellow first: black last : yellow Map 22.8 Maps Associates keys to values Cannot contain duplicate keys Called one-to-one mapping Sets contain only values whereas Maps contain keys and values Several classes implement interface Map: HashMap stores elements in hash tables TreeMaps stores elements in trees

178 1 // Fig : WordTypeCount.java 2 // Program counts the number of occurrences of each word in a string 3 import java.awt.*; 4 import java.awt.event.*; 5 import java.util.*; 6 import javax.swing.*; 7 8 public class WordTypeCount extends JFrame { 9 private JTextArea inputfield; 10 private JLabel prompt; 11 private JTextArea display; 12 private JButton gobutton; private Map map; public WordTypeCount() 17 { 18 super( "Word Type Count" ); 19 inputfield = new JTextArea( 3, 20 ); map = new HashMap(); Create HashMap gobutton = new JButton( "Go" ); 24 gobutton.addactionlistener( 25 Outline MapTest.java Line new ActionListener() { // inner class public void actionperformed( ActionEvent event ) 29 { 30 createmap(); 31 display.settext( createoutput() ); 32 } } // end inner class ); // end call to addactionlistener prompt = new JLabel( "Enter a string:" ); 39 display = new JTextArea( 15, 20 ); 40 display.seteditable( false ); JScrollPane displayscrollpane = new JScrollPane( display ); // add components to GUI 45 Container container = getcontentpane(); 46 container.setlayout( new FlowLayout() ); 47 container.add( prompt ); 48 container.add( inputfield ); 49 container.add( gobutton ); 50 container.add( displayscrollpane ); 51 Outline MapTest.java

179 52 setsize( 400, 400 ); 53 show(); } // end constructor // create map from user input 58 private void createmap() 59 { 60 String input = inputfield.gettext(); 61 StringTokenizer tokenizer = new StringTokenizer( input ); while ( tokenizer.hasmoretokens() ) { 64 String word = tokenizer.nexttoken().tolowercase(); // get word // if the map contains the word 67 if ( map.containskey( word ) ) { Integer count = (Integer) map.get( word ); // get value // increment value 72 map.put( word, new Integer( count.intvalue() + 1 ) ); 73 } 74 else // otherwise add word with a value of 1 to map 75 map.put( word, new Integer( 1 ) ); } // end while } // end method createmap Outline MapTest.java Line 69 Lines 72 and 75 Use method get to retrieve a Character from HashMap Use method put to store a Character with an Integer key in HashMap // create string containing map values 82 private String createoutput() { 83 StringBuffer output = new StringBuffer( "" ); 84 Iterator keys = map.keyset().iterator(); // iterate through the keys 87 while ( keys.hasnext() ) { 88 Object currentkey = keys.next(); // output the key-value pairs 91 output.append( currentkey + "\t" + 92 map.get( currentkey ) + "\n" ); 93 } output.append( "size: " + map.size() + "\n" ); 96 output.append( "isempty: " + map.isempty() + "\n" ); return output.tostring(); } // end method createoutput 101 Outline MapTest.java

180 102 public static void main( String args[] ) 103 { 104 WordTypeCount application = new WordTypeCount(); 105 application.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); 106 } } // end class WordTypeCount Outline MapTest.java Summary Java collections framework prepackaged data structures and algorithms for manipulating these data structures A collection is an object that can hold references to objects. Collection interfaces declare operations for each type of collection. Important Constructs: Class Arrays Class Collections Collection List Collection Set Collection Map

181 1 Part 8 Methods scope of declarations method overriding method overloading recursions 2003 Prentice Hall, Inc. All rights reserved. 3 Modules 6.1 Introduction Small pieces of a problem e.g., divide and conquer Facilitate design, implementation, operation and maintenance of large programs

182 4 6.2 Program Modules in Java Modules in Java Methods Classes Java API provides several modules Programmers can also create modules e.g., programmer-defined methods Methods Invoked by a method call Returns a result to calling method (caller) Similar to a boss (caller) asking a worker (called method) to complete a task 5 boss worker1 worker2 worker3 worker4 worker5 Fig. 6.1 Hierarchical boss-method/worker-method relationship.

183 Good Programming Practice 6 Familiarize yourself with the rich collection of classes and methods provided by the Java API java.sun.com/j2se/ /docs/api/index.html and with the rich set of collections of classes available in various class libraries. Avoid reinventing the wheel Reduce program development time and programming errors By rewriting existing Java API classes one rarely can improve the performance Software Engineering Observation 7 Promote software reusability: each method should perform a single, well-defined task; name of the method should express that task effectively. Small methods are easier to test and debug and promote software reusability.

184 6.3 Math-Class Methods 8 Class java.lang.math Provides common mathematical calculations Calculate the square root of 900.0: Math.sqrt( ) Method sqrt belongs to class Math Dot (.) allows access to method sqrt The argument is located inside parentheses Class Math must not be explicitly imported. Package java.lang is implicitly imported by the compiler. 9 Method Description Example abs( x ) absolute value of x (this method also has float, int and long versions) abs( 23.7 ) is 23.7 abs( 0.0 ) is 0.0 abs( ) is 23.7 ceil( x ) rounds x to the smallest integer not less than x ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0 cos( x ) trigonometric cosine of x (x is in radians) cos( 0.0 ) is 1.0 exp( x ) exponential method ex exp( 1.0 ) is exp( 2.0 ) is floor( x ) rounds x to the largest integer not greater than x floor( 9.2 ) is 9.0 floor( -9.8 ) is log( x ) natural logarithm of x (base e) log( Math.E ) is 1.0 log( Math.E * Math.E ) is 2.0 max( x, y ) larger value of x and y (this method also has float, int and long versions) max( 2.3, 12.7 ) is 12.7 max( -2.3, ) is -2.3 min( x, y ) smaller value of x and y (this method also has float, int and long versions) min( 2.3, 12.7 ) is 2.3 min( -2.3, ) is pow( x, y ) x raised to the power y (xy) pow( 2.0, 7.0 ) is pow( 9.0, 0.5 ) is 3.0 sin( x ) trigonometric sine of x (x is in radians) sin( 0.0 ) is 0.0 sqrt( x ) square root of x sqrt( ) is 30.0 sqrt( 9.0 ) is 3.0 tan( x ) trigonometric tangent of x (x is in radians) tan( 0.0 ) is 0.0 Fig. 6.2 Math-class methods.

185 6.4 Methods Declarations 10 Methods Allow programmers to modularize programs Makes program development more manageable Software reusability Avoid repeating code Local variables Declared in method declaration Parameters Communicates information between methods via method calls 1 // Fig. 6.3: SquareIntegers.java 2 // Creating and using a programmer-defined method. 3 import java.awt.container; 4 5 import javax.swing.*; 6 7 public class SquareIntegers extends JApplet { 8 Declare result to store square of number 9 // set up GUI and calculate squares of integers from 1 to 10 Method init invokes method square (next slide) 10 public void init() 11 { 12 // JTextArea to display results 13 JTextArea outputarea = new JTextArea(); // get applet's content pane (GUI component display area) 16 Container container = getcontentpane(); // attach outputarea to container 19 container.add( outputarea ); int result; // store result of call to method square 22 String output = ""; // String containing results // loop 10 times 25 for ( int counter = 1; counter <= 10; counter++ ) { 26 result = square( counter ); // method call // append result to String output 29 output += "The square of " + counter + " is " + result + "\n"; } // end for Outline 12 SquareIntegers. java Line 21 Declare result to store square of number Line 26 Method init invokes method square Method square returns int that result Line 26 stores Method square returns int that result stores

186 32 33 outputarea.settext( output ); // place results in JTextArea } // end method init // square method declaration 38 public int square( int y ) 39 { 40 return y * y; // return square of y } // end method square } // end class SquareIntegers y is the parameter of method square Method square returns the square of y Outline 13 SquareIntegers. java Line 38 y is the parameter of method square Line 40 Method square returns the square of y 6.4 Method Declarations (cont.) General format of method declaration: 14 return-value-type method-name( parameter1, parameter2,, parametern ) { declarations and statements } Method can also return values: return expression; Common Programming errors: e.g. float x, y instead of float x, float y data types of actual and formal parameters must match Method header and calls must match in the number,type and order of parameters and arguments

187 Several Ways to Call a Method 15 method name by itself, e.g. square(counter) Methods in a class declaration can call other methods in the same class declaration. reference to a method of an object g.drawline(15,10,210,10) class name qualifying a method name (static method) Integer.parseInt(firstNumber) 1 // Fig. 6.4: MaximumTest.java 2 // Finding the maximum of three floating-point numbers. 3 import java.awt.container; 4 5 import javax.swing.*; 6 7 public class MaximumTest extends JApplet { 8 9 // initialize applet by obtaining user input and creating GUI 10 public void init() 11 { 12 // obtain user input 13 String s1 = JOptionPane.showInputDialog( 14 "Enter first floating-point value" ); 15 String s2 = JOptionPane.showInputDialog( User inputs three Strings Convert Strings to doubles 16 "Enter second floating-point value" ); 17 String s3 = JOptionPane.showInputDialog( 18 "Enter third floating-point value" ); // convert user input to double values 21 double number1 = Double.parseDouble( s1 ); 22 double number2 = Double.parseDouble( s2 ); 23 double number3 = Double.parseDouble( s3 ); double max = maximum( number1, number2, number3 ); // method call // create JTextArea to display results 28 JTextArea outputarea = new JTextArea(); // display numbers and maximum value 31 outputarea.settext( "number1: " + number1 + "\nnumber2: " + 32 number2 + "\nnumber3: " + number3 + "\nmaximum is: " + max ); 33 Outline Maximum.java Lines User inputs three Strings Lines Convert Strings to doubles 16 Line 25 Method init passes doubles as arguments to method Method maximum init passes doubles as arguments to method maximum

188 34 // get applet's GUI component display area 35 Container container = getcontentpane(); // attach outputarea to Container c 38 container.add( outputarea ); } // end method init // maximum method uses Math class method max to help 43 // determine maximum value 44 public double maximum( double x, double y, double z ) 45 { 46 return Math.max( x, Math.max( y, z ) ); } // end method maximum } // end class Maximum Method maximum returns value from method max of class Math Outline Maximum.java Line 46 Method maximum returns value from method max of class Math Argument Promotion 18 Coercion of arguments Forcing arguments to appropriate type to pass to method e.g., System.out.println( Math.sqrt( 4 ) ); Evaluates Math.sqrt( 4 ) Then evaluates System.out.println() Promotion rules Specify how to convert types without data loss

189 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 byte short, int, long, float or double boolean None (boolean values are not considered to be numbers in Java) Fig. 6.5 Allowed promotions for primitive types. 19 Valid promotions from lower table entries to higher level table entries. Type conversion to lower table entries requires explicit cast operation. result = square ((int) doublevalue); 6.6 Java API Packages 20 Packages Classes grouped into categories of related classes Promotes software reuse import statements specify classes used in Java programs e.g., import javax.swing.japplet;

190 21 Package java.applet Description The Java Applet Package contains the Applet class and several interfaces that enable applet/browser interaction and the playing of audio clips. In Java 2, class javax.swing.japplet is used to define an applet that uses the Swing GUI components. java.awt java.awt.event The Java Abstract Window Toolkit Package contains the classes and interfaces required to create and manipulate GUIs in Java 1.0 and 1.1. In Java 2, the Swing GUI components of the javax.swing packages are often used instead. The Java Abstract Window Toolkit Event Package contains classes and interfaces that enable event handling for GUI components in both the java.awt and javax.swing packages. java.io The Java Input/Output Package contains classes that enable programs to input and output data (see Chapter 17, Files and Streams). java.lang The Java Language Package contains classes and interfaces (discussed throughout this text) that are required by many Java programs. This package is imported by the compiler into all programs. java.net java.text The Java Networking Package contains classes that enable programs to communicate via networks (see Chapter 18, Networking). The Java Text Package contains classes and interfaces that enable a Java program to manipulate numbers, dates, characters and strings. The package provides many of Java s internationalization capabilities that enable a program to be customized to a specific locale (e.g., an applet may display strings in different languages, based on the user s country). java.util The Java Utilities Package contains utility classes and interfaces, such as date and time manipulations, randomnumber processing capabilities with class Random, storing and processing large amounts of data and breaking strings into smaller pieces called tokens with class StringTokenizer (see Chapter 20; Data Structures, Chapter 21, Java Utilities Package and Bit Manipulation; and Chapter 22, Collections). javax.swing The Java Swing GUI Components Package contains classes and interfaces for Java s Swing GUI components that provide support for portable GUIs. javax.swing.event Fig. 6.6 Java API packages (a subset). The Java Swing Event Package contains classes and interfaces that enable event handling for GUI components in package javax.swing. 6.7 Random-Number Generation 22 Java random-number generators Math.random() 1 + ( int ) ( Math.random() * 6 ) Produces integers from 1-6 Use a seed for different random-number sequences

191 1 // Fig. 6.7: RandomIntegers.java 2 // Shifted, scaled random integers. 3 import javax.swing.joptionpane; 4 5 public class RandomIntegers { 6 7 public static void main( String args[] ) 8 { 9 int value; 10 String output = ""; // loop 20 times 13 for ( int counter = 1; counter <= 20; counter++ ) { // pick random integer between 1 and 6 16 value = 1 + ( int ) ( Math.random() * 6 ); output += value + " "; // append value to output // if counter divisible by 5, append newline to String output 21 if ( counter % 5 == 0 ) 22 output += "\n"; } // end for 25 Produce integers in range 1-6 Outline 23 RandomIntegers. java Line 16 Produce integers in range 1-6 Math.random returns doubles. We cast the double as an int Line 16 Math.random returns doubles. We cast the double as an int 26 JOptionPane.showMessageDialog( null, output, 27 "20 Random Numbers from 1 to 6", 28 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class RandomIntegers Outline 24 RandomIntegers. java

192 1 // Fig. 6.8: RollDie.java 2 // Roll a six-sided die 6000 times. 3 import javax.swing.*; 4 5 public class RollDie { 6 7 public static void main( String args[] ) 8 { 9 int frequency1 = 0, frequency2 = 0, frequency3 = 0, 10 frequency4 = 0, frequency5 = 0, frequency6 = 0, face; // summarize results 13 for ( int roll = 1; roll <= 6000; roll++ ) { 14 face = 1 + ( int ) ( Math.random() * 6 ); // determine roll value and increment appropriate counter 17 switch ( face ) { case 1: 20 ++frequency1; 21 break; case 2: 24 ++frequency2; 25 break; case 3: 28 ++frequency3; 29 break; 30 Outline RollDie.java Line 14 Produce integers in range 1-6Produce integers in range 1-6 Increment appropriate frequency counter, depending on randomly generated number 25 Lines Increment appropriate frequency counter, depending on randomly generated number 31 case 4: 32 ++frequency4; 33 break; case 5: 36 ++frequency5; 37 break; case 6: 40 ++frequency6; 41 break; } // end switch } // end for JTextArea outputarea = new JTextArea(); outputarea.settext( "Face\tFrequency" + "\n1\t" + frequency "\n2\t" + frequency2 + "\n3\t" + frequency "\n4\t" + frequency4 + "\n5\t" + frequency "\n6\t" + frequency6 ); JOptionPane.showMessageDialog( null, outputarea, 55 "Rolling a Die 6000 Times", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class RollDie Outline RollDie.java 26

193 27 36 Scope 6.9 Scope of Declarations (1) Portion of the program that can reference an entity by its name Basic scope rules Scope of a parameter declaration Scope of a local-variable declaration Scope of a label in a labeled break or continue statement Scope of a local-variable declaration that appears in the initialization section of a for statement s header Scope of a method or field of a class

194 Scope of Declarations (2) Scope of a parameter declaration Body of the method in which the declaration appears. Scope of a constructor parameter declaration is the body of that constructor. Scope of a local variable declaration From the point at which the declaration appears in the block to the end of that block. Scope of a label in labeled break or continue statement The statement enclosed by the labeled statement (e.g. body of labeled statement) Scope of Declarations (3) Scope of a local variable declaration in for statement body of the for statement Scope of a method or field of a class entire body of the class. This enables methods of a class to use simple names to call other methods declared in this class or inherited by that class and to access fields declared in the class.

195 39 Declarations and Scopes in Blocks Any block may contain variable or reference declarations. nested blocks: identifier in inner block with same as name as identifier in outer block of the same method -> syntax error local variable or parameter with the same name as a field -> field is hidden until block terminates. shadowing Avoid using the same names for fields and local variables. 1 // Fig. 6.10: Scoping.java 2 // A scoping example. 3 import java.awt.container; 4 5 import javax.swing.*; 6 7 public class Scoping extends JApplet { 8 JTextArea outputarea; 9 10 // field that is accessible to all methods of this class 11 int x = 1; // create applet's GUI 14 public void init() 15 { 16 outputarea = new JTextArea(); 17 Container container = getcontentpane(); 18 container.add( outputarea ); } // end method init // method start called after init completes; start calls 23 // methods uselocal and usefield 24 public void start() 25 { Field x has class scope Local variable x has block scope Method start uses local variable x 26 int x = 5; // local variable in method start that shadows field x outputarea.append( "local x in start is " + x ); 29 Outline Scoping.java Line 11 field x Line 26 Local variable x Line 28 Method start uses local variable x 40

196 30 uselocal(); // uselocal has local x 31 usefield(); // useinstance uses Scoping's field x 32 uselocal(); // uselocal reinitializes local x 33 usefield(); // Scoping's field x retains its value outputarea.append( "\n\nlocal x in start is " + x ); } // end method start // uselocal creates and initializes local variable x during each call Re-create variable x and initialize it to public void uselocal() 41 { 42 int x = 25; // initialized each time uselocal is called outputarea.append( "\n\nlocal x in uselocal is " + x + 45 " after entering uselocal" ); 46 ++x; 47 outputarea.append( "\nlocal x in uselocal is " + x + 48 " before exiting uselocal" ); } // end method uselocal 51 Outline Scoping.java Line 42 Recreate variable x and initialize it to 25 Lines Method uselocal uses local variable x Method uselocal uses local variable x // usefield modifies Scoping's field x during each call 53 public void usefield() 54 { 55 outputarea.append( "\n\nfield x is " + x + 56 " on entering usefield" ); 57 x *= 10; 58 outputarea.append( "\nfield x is " + x + 59 " on exiting usefield" ); } // end method useinstance } // end class Scoping Outline Scoping.java Lines Method usefield Method usefield uses field x uses field x 42

197 6.16 Methods of Class JApplet 43 Java API defines several JApplet methods Defining methods of Fig in a JApplet is called overriding those methods. New method declaration overrides the inherited one. Must use appropriate method header, otherwise default versions New method declaration replaces default one Method public void init() When the method is called and its purpose This method is called once by the applet container when an applet is loaded for execution. It performs initialization of an applet. Typical actions performed here are initializing fields, creating GUI components, loading sounds to play, loading images to display (see Chapter 19, Multimedia) and creating threads (see Chapter 16, Multithreading). 44 public void start() This method is called after the init method completes execution. In addition, if the browser user visits another Web site and later returns to the HTML page on which the applet resides, method start is called again. The method performs any tasks that must be completed when the applet is loaded for the first time and that must be performed every time the HTML page on which the applet resides is revisited. Typical actions performed here include starting an animation (see Chapter 19) and starting other threads of execution (see Chapter 16). public void paint( Graphics g ) This drawing method is called after the init method completes execution and the start method has started. It is also called every time the applet needs to be repainted. For example, if the user covers the applet with another open window on the screen and later uncovers the applet, the paint method is called. Typical actions performed here involve drawing with the Graphics object g that is passed to the paint method by the applet container. public void stop() public void destroy() This method is called when the applet should stop executing normally, when the user of the browser leaves the HTML page on which the applet resides. The method performs any tasks that are required to suspend the applet s execution. Typical actions performed here are to stop execution of animations and threads. This method is called when the applet is being removed from memory normally, when the user of the browser exits the browsing session (i.e., closes all browser windows). The method performs any tasks that are required to destroy resources allocated to the applet. Fig JApplet methods that the applet container calls during an applet s execution.

198 6.15 Method Overloading 45 Method overloading Several methods of the same name declared in the same class. Different parameter set for each method Number of parameters Parameter types Overloaded methods are distinguished by their signature Method name and number and types of parameters Overloaded methods are commonly used to perform similar tasks but on different types Java compiler must decide which method to take. Overloaded methods cannot be distinguished by return types if they have the same signature -> syntax error! 1 // Fig. 6.12: MethodOverload.java 2 // Using overloaded methods 3 import java.awt.container; 4 5 import javax.swing.*; 6 7 public class MethodOverload extends JApplet { 8 9 // create GUI and call each square method 10 public void init() 11 { 12 JTextArea outputarea = new JTextArea(); 13 Container container = getcontentpane(); 14 container.add( outputarea ); outputarea.settext( "The square of integer 7 is " + square( 7 ) + 17 "\nthe square of double 7.5 is " + square( 7.5 ) ); } // end method init Method square receives an int as an argument // square method with int argument 22 public int square( int intvalue ) 23 { 24 System.out.println( "Called square with int argument: " + 25 intvalue ); return intvalue * intvalue; } // end method square with int argument 30 Outline 46 MethodOverload. java Lines Method square receives an int as an argument

199 31 // square method with double argument 32 public double square( double doublevalue ) 33 { 34 System.out.println( "Called square with double argument: " + 35 doublevalue ); return doublevalue * doublevalue; } // end method square with double argument } // end class MethodOverload Overloaded method square receives a double as an argument Outline 47 MethodOverload. java Lines Overloaded method square receives a double as an argument Called square with int argument: 7 Called square with double argument: // Fig. 6.13: MethodOverload.java 2 // Overloaded methods with identical signatures. 3 import javax.swing.japplet; 4 5 public class MethodOverload extends JApplet { 6 7 // declaration of method square with int argument 8 public int square( int x ) 9 { 10 return x * x; 11 } // second declaration of method square 14 // with int argument causes syntax error 15 public double square( int y ) 16 { 17 return y * y; 18 } } // end class MethodOverload Outline 48 MethodOverload. java Lines 8 and 15 Compiler cannot distinguish between Compiler cannot methods with identical names and parameter sets distinguish between methods with identical names and parameter sets MethodOverload.java:15: square(int) is already defined in MethodOverload public double square( int y ) ^ 1 error Compiler cannot differ overloaded methods by different return type Fig Compiler error messages generated from overloaded methods with identical parameter lists and different return types.

200 6.12 Recursion 49 Recursive method Calls itself (directly or indirectly) through another method Method knows how to solve only a base case Method divides problem Base case (simplest case) Simpler problem Method divides simpler problem until solvable Recursive call = Recursive step return statement to pass back result to caller of previous recursion. sequence of smaller and smaller problems must converge to the base case sequence of calls returns until original method call returns final result to caller. 50 n! = n*(n-1)*(n-2)* *2*1 5! 5! Final value = 120 5! = 5 * 24 = 120 is returned 5 * 4! 5 * 4! 4! = 4 * 6 = 24 is returned 4 * 3! 4 * 3! 2! = 2 * 1 = 2 is returned 3! = 3 * 2 = 6 is returned 3 * 2! 3 * 2! 2 * 1! 1 2 * 1! 1 1 returned (a) Sequence of recursive calls. (b) Values returned from each recursive call. Fig Recursive evaluation of 5!.

201 1 // Fig. 6.15: FactorialTest.java 2 // Recursive factorial method. 3 import java.awt.*; 4 5 import javax.swing.*; 6 7 public class FactorialTest extends JApplet { 8 JTextArea outputarea; 9 10 // create GUI and calculate factorials of public void init() 12 { 13 outputarea = new JTextArea(); Container container = getcontentpane(); 16 container.add( outputarea ); // calculate the factorials of 0 through for ( long counter = 0; counter <= 10; counter++ ) 20 outputarea.append( counter + "! = " + 21 factorial( counter ) + "\n" ); } // end method init 24 Invoke method factorial Outline 51 FactorialTest.j ava Line 21 Invoke method factorial 25 // recursive declaration of method factorial 26 public long factorial( long number ) 27 { 28 // base case 29 if ( number <= 1 ) 30 return 1; // recursive step 33 else 34 return number * factorial( number - 1 ); } // end method factorial } // end class FactorialTest Test for base case (method factorial can solve base case) Outline 52 FactorialTest.j ava Lines Else return simpler Test problem for base that case method factorial (method might solve factorial in next recursive can call solve base case) Line 34 Else return simpler problem that method factorial might solve in next recursive call

202 53 Recursions: Common Programming Error omitting the base case incorrect based case or recursion step that never converges to base case public int nextrecursion( int number ) if ( number == 3 ) return 1; else // recursive step return number * nextrecursion( number/2 ); input parameter out of range (e.g. negative instead of positive value) cover with correct typing Commonly recursion errors yield infinite recursion eventually exhausting memory Example Using Recursion: The Fibonacci Series 54 Fibonacci series Each number in the series is sum of two previous numbers e.g., 0, 1, 1, 2, 3, 5, 8, 13, 21 fibonacci(0) = 0 fibonacci(1) = 1 fibonacci(n) = fibonacci(n - 1) + fibonacci( n 2 ) fibonacci(0) and fibonacci(1) are base cases Golden ratio (golden mean)

203 1 // Fig. 6.16: FibonacciTest.java 2 // Recursive fibonacci method. 3 import java.awt.*; 4 import java.awt.event.*; 5 6 import javax.swing.*; 7 8 public class FibonacciTest extends JApplet implements ActionListener { 9 JLabel numberlabel, resultlabel; 10 JTextField numberfield, resultfield; // set up applet s GUI 13 public void init() 14 { 15 // obtain content pane and set its layout to FlowLayout 16 Container container = getcontentpane(); 17 container.setlayout( new FlowLayout() ); // create numberlabel and attach it to content pane 20 numberlabel = new JLabel( "Enter an integer and press Enter" ); 21 container.add( numberlabel ); // create numberfield and attach it to content pane 24 numberfield = new JTextField( 10 ); 25 container.add( numberfield ); // register this applet as numberfield s ActionListener 28 numberfield.addactionlistener( this ); 29 Outline 55 FibonacciTest.j ava 30 // create resultlabel and attach it to content pane 31 resultlabel = new JLabel( "Fibonacci value is" ); 32 container.add( resultlabel ); // create numberfield, make it uneditable 35 // and attach it to content pane 36 resultfield = new JTextField( 15 ); 37 resultfield.seteditable( false ); 38 container.add( resultfield ); } // end method init // obtain user input and call method fibonacci 43 public void actionperformed( ActionEvent event ) 44 { 45 long number, fibonaccivalue; // obtain user s input and convert to long 48 number = Long.parseLong( numberfield.gettext() ); showstatus( "Calculating..." ); // calculate fibonacci value for number user input 53 fibonaccivalue = fibonacci( number ); // indicate processing complete and display result 56 showstatus( "Done." ); 57 resultfield.settext( Long.toString( fibonaccivalue ) ); } // end method actionperformed 60 Outline 56 FibonacciTest.j ava Line 43 Method actionperformed is invoked when user presses Enter Method actionperformed Line 45 is invoked when user We presses use long, Enter because Fibonacci We use long, because numbers become large Fibonacci numbers quickly become large quickly Lines Pass user input to method fibonacci Pass user input to method fibonacci

204 61 // recursive declaration of method fibonacci 62 public long fibonacci( long n ) 63 { 64 // base case 65 if ( n == 0 n == 1 ) 66 return n; // recursive step 69 else 70 return fibonacci( n - 1 ) + fibonacci( n - 2 ); } // end method fibonacci } // end class FibonacciTest Test for base case (method fibonacci can solve base case) Outline 57 FibonacciTest.j ava Else return simpler problem Lines that method fibonaccitest might for solve base case in next recursive (method call fibonacci can solve base case) Lines Else return simpler problem that method fibonacci might solve in next recursive call Outline 58 FibonacciTest.j ava

205 Outline 59 FibonacciTest.j ava 60 fibonacci( 3 ) return fibonacci( 2 ) + fibonacci( 1 ) return fibonacci( 1 ) + fibonacci( 0 ) return 1 return 1 return 0 Fig Set of recursive calls for fibonacci (3).

206 61 Iteration 6.14 Recursion vs. Iteration Uses repetition structures (for, while or do while) Repetition through explicitly use of repetition structure Terminates when loop-continuation condition fails Controls repetition by using a counter Recursion Uses selection structures (if, if else or switch) Repetition through repeated method calls Terminates when base case is satisfied Controls repetition by dividing problem into simpler one Recursion vs. Iteration (cont.) Recursion More overhead than iteration More memory intensive than iteration Can also be solved iteratively Often can be implemented with only a few lines of code

207 Summary 63 modules in Java: classes and methods software reuse: methods for modularizing programs scope of declarations method overriding New method declaration overrides the inherited one. method overloading Several methods of the same name declared in the same class. recursions versus iteration

208 Part 10 Object Oriented Programming Traditionelle Softwareentwicklung Wasserfallmodell Dominierte lange die Softwareentwicklung Weite Verbreitung in vielen Varianten Requirement Analysis Design Implementation Test Maintenance Hauptprobleme: Starre Unterteilung von Softwareprojekten Sprunghafte Phasenübergänge Spätes Erkennen von Designfehlern (late design breakage) Gefahr, Anforderungen nicht zu erfüllen

209 Traditionelle Softwareentwicklung Strukturierte Analyse und Design (SA/SD) Basis sind Analysetechniken, die zwischen 1965 u entwickelt wurden. Im Mittelpunkt steht die Modellierung von Prozessen durch Funktionen. sehr weit verbreitet (klassisches SE) Schwerpunkt: Implementierung und Test schwierige Wartung Aufwand Requirement Analysis Design Implementation Test Kosten der Fehlerkorrektur x 1, 5-6 x 1 x Definition Implementation After release

210 Objektorientierte Softwareentwicklung Ende der 80er Jahre erfolgt ein Paradigmenwechsel im Software Engineering: Objektorientierung. Objektorientierte Analyse und Design (OOA/OOD) Basierend auf OO-Technologie (ab ca. 1985) Zentral sind Objektmodelle (Vereinigung von Daten- und Prozessmodellen) Schwerpunkt: Analyse und Design leichtere Wartung Aufwand Requirement Analysis Design Implementation Test OOA/OOD versus SA/SD Library Information System Object-Oriented A/D Structured A/D System Catalog Librarian Book Library Record Loans Add Resources Report Fines OOA/OOD Zerlegung anhand von Konzepten (Objekten) SA/SD Zerlegung anhand von Prozessen (Funktionen)

211 Introduction: Procedural Programming Procedural programming language C, Pascal, Fortran, operations-oriented operations to perform a task grouped into functions functions form a program data to support functions data and operations (procedures, functions) are separated How to realize a functionality? Functions are units of programming Introduction: Object-Oriented Programming Object-oriented programming language Java, Smalltalk, C++ Object-oriented Data and operations (methods) define a unit (class) Classes to encapsulate data (attributes) and methods (behavior) Encapsulation for hiding implementation What (functionality) should be realized? Classes are units of programming members fields (variables) methods for manipulating fields functions, or methods, are encapsulated in classes

212 Key Object Oriented Concepts (1) Classes and Objects A class describes the characteristics (variables) and behavior (methods) of its objects. A class declaration defines the variables and methods of an object. A class declaration defines a new reference type. class Person { // class declaration String name; // variable (field) private String svnr; // - "... public Person(String name, String svnr) { // constructor this.name = name; this.svnr = svnr; } public int getalter() (...) // method } Key Object Oriented Concepts (2) State of an object defines by the contents of its variables Behavior of an object defined through the object s methods. Object interaction Objects interact with each other through exchanging messages (method invocation).

213 Key Object Oriented Concepts (3) Classes and Objects Objects are instances of a class. Objects are created through the invocation of a constructor (new Operator). // create instance (object) of class Person Person hugo = new Person ("Hugo", " "); Acess to variables and methods of an object is achieved through the "." Operator String name = hugo.name; int a = hugo.getage(); // access variable // call method Classes and Objects: UML Diagrams

214 Key Object Oriented Concepts (4) Encapsulation (Information hiding) The internal structure of an object should not be accessible or visible to the outside world. Program that is using objects of a specific class should be independent of the implementation of this class. Know what an object can do, not how it does it. Java access modifiers: public, private, protected Information hiding increases the level of independence. Independence of modules is important for large systems and maintenance. class Person {... private String svnr; // not accessible outside public int getsvnr() {...} // access method } Java Language Constructs - Classes Class declaration Variables Constructor public class Person { private String name; private String svnr; public Person(String name, String svnr) { this.svnr = svnr; this.name = name; } Methods } public String getsvnr() { return svnr; } publis String getname() { return name; }

215 Implementing a Time Abstract Data Type with a Class Java simplifies creation of abstract data types hide implementation details internal implementation can be changed without changing interfaces (method signature) We introduce classes Time1 and TimeTest Time1.java declares class Time1 TimeTest.java declares class TimeTest public classes must be declared in separate files Class Time1 will not execute by itself Does not have method main TimeTest, which has method main, creates (instantiates) and uses Time1 object 1 // Fig. 8.1: Time1.java 2 // Time1 class declaration maintains the time in 24-hour format. 3 import java.text.decimalformat; 4 5 public class Time1 extends Object { 6 private int hour; // private int minute; // private int second; // // Time1 constructor initializes each instance variable to zero; 11 // ensures that each Time1 object starts in a consistent state 12 public Time1() 13 { 14 settime( 0, 0, 0 ); 15 } // set a new time value using universal time; perform 18 // validity checks on the data; set invalid values to zero 19 public void settime( int h, int m, int s ) 20 { 21 hour = ( ( h >= 0 && h < 24 )? h : 0 ); 22 minute = ( ( m >= 0 && m < 60 )? m : 0 ); 23 second = ( ( s >= 0 && s < 60 )? s : 0 ); 24 } 25 Time1 (subclass) extends superclass java.lang.object (Chapter 9 discusses inheritance) Time1.java Line 5 private variables (and Time1 methods) (subclass) are accessible only to methods extends in this superclass java.lang.objec t Lines 6-8 private variables Time1 constructor creates Lines Time1 object then invokes Time1 constructor method settime then invokes method settime Line 19 public methods Method settime sets private variables public according methods to arguments (and Lines variables) are accessible wherever Method program settime has Time1 reference sets private variables according to arguments

216 26 // convert to String in universal-time format 27 public String touniversalstring() 28 { 29 DecimalFormat twodigits = new DecimalFormat( "00" ); return twodigits.format( hour ) + ":" + 32 twodigits.format( minute ) + ":" + twodigits.format( second ); 33 } // convert to String in standard-time format 36 public String tostandardstring() 37 { 38 DecimalFormat twodigits = new DecimalFormat( "00" ); return ( (hour == 12 hour == 0)? 12 : hour % 12 ) + ":" + 41 twodigits.format( minute ) + ":" + twodigits.format( second ) + 42 ( hour < 12? " AM" : " PM" ); 43 } } // end class Time1 Time1.java 8.2 Implementing a Time Abstract Data Type with a Class (cont.) Every Java class must extend another class Time1 extends java.lang.object If class does not explicitly extend another class class implicitly extends Object Class constructor Same name as class Initializes instance variables of a class object Called when program instantiates an object of that class Can take arguments, but cannot return values Class can have several constructors, through overloading Class Time1 constructor(lines 12-15)

217 1 // Fig. 8.2: TimeTest1.java 2 // Class TimeTest1 to exercise class Time1. 3 import javax.swing.joptionpane; 4 5 public class TimeTest1 { 6 7 public static void main( String args[] ) 8 { 9 Time1 time = new Time1(); // calls Time1 constructor 10 Declare and create instance of class Time1 by calling Time1 constructor 11 // append String version of time to String output 12 String output = "The initial universal time is: " + 13 time.touniversalstring() + "\nthe initial standard time is: " + 14 time.tostandardstring(); // change time and append updated time to output 17 time.settime( 13, 27, 6 ); 18 output += "\n\nuniversal time after settime is: " + 19 time.touniversalstring() + 20 "\nstandard time after settime is: " + time.tostandardstring(); // set time with invalid values; append updated time to output 23 time.settime( 99, 99, 99 ); 24 output += "\n\nafter attempting invalid settings: " + 25 "\nuniversal time: " + time.touniversalstring() + 26 "\nstandard time: " + time.tostandardstring(); 27 TimeTest1.java Line 9 Declare and create TimeTest1 interacts with Time1 instance of class by calling Time1 public methods Time1 by calling Time1 constructor Lines TimeTest1 interacts with Time1 by calling Time1 public methods 28 JOptionPane.showMessageDialog( null, output, 29 "Testing Class Time1", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class TimeTest1 TimeTest1.java

218 Main concepts to be covered fields constructors methods parameters object interaction garbage collection packages Basic class structure public class TicketMachine { Inner part of the class omitted. } The outer wrapper of TicketMachine public class ClassName { Fields Constructors Methods } The contents of a class

219 Fields Fields store values for an object. They are also known as instance variables. Fields define the state of an object. public class TicketMachine { private int price; private int balance; private int total; } Constructor and methods omitted. access modifier type variable name private int price; Class scope Class Scope Class variables and methods Members are accessible to all class methods Members can be referenced by name objectreferencename.objectmembername Shadowed (hidden) class variables this.variablename

220 8.4 Controlling Access to Members Member access modifiers Control access to class s variables and methods public Variables and methods accessible to clients of the class private Variables and methods not accessible to clients of the class Precede every field and method declaration with access modifier. Rule of thumb: fields as private methods as public private methods: utility methods can be called only by other methods of the same class public fields is uncommon and dangerous programming! 1 // Fig. 8.3: TimeTest2.java 2 // Errors resulting from attempts to access private members of Time1. 3 public class TimeTest2 { 4 5 public static void main( String args[] ) 6 { 7 Time1 time = new Time1(); 8 9 time.hour = 7; // error: hour is a private instance variable 10 time.minute = 15; // error: minute is a private instance variable 11 time.second = 30; // error: second is a private instance variable 12 } } // end class TimeTest2 Compiler error TimeTest2 cannot directly access Time1 s private data TimeTest2.java Lines 9-11 Compiler error TimeTest2 cannot directly access Time1 s private data TimeTest2.java:9: hour has private access in Time1 time.hour = 7; // error: hour is a private instance variable ^ TimeTest2.java:10: minute has private access in Time1 time.minute = 15; // error: minute is a private instance variable ^ TimeTest2.java:11: second has private access in Time1 time.second = 30; // error: second is a private instance variable ^ 3 errors

221 Referring to the Current Object s Members with this Keyword this (this reference) Allows an object to refer to itself syntax error: non-constructor method tries to invoke constructor via this reference. Constructor can call other methods warning: instance variables may not be consistent yet 1 // Fig. 8.4: ThisTest.java 2 // Using the this reference to refer to instance variables and methods. 3 import javax.swing.*; 4 import java.text.decimalformat; 5 6 public class ThisTest { 7 8 public static void main( String args[] ) 9 { 10 SimpleTime time = new SimpleTime( 12, 30, 19 ); JOptionPane.showMessageDialog( null, time.buildstring(), 13 "Demonstrating the \"this\" Reference", 14 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); 17 } } // end class ThisTest // class SimpleTime demonstrates the "this" reference 22 class SimpleTime { 23 private int hour; 24 private int minute; 25 private int second; 26 ThisTest.java

222 27 // constructor uses parameter names identical to instance variable 28 // names; "this" reference required to distinguish between names 29 public SimpleTime( int hour, int minute, int second ) 30 { 31 this.hour = hour; // set "this" object's hour 32 this.minute = minute; // set "this" object's minute 33 this.second = second; // set "this" object's second 34 } // use explicit and implicit "this" to call tostandardstring 37 public String buildstring() 38 { 39 return "this.tostandardstring(): " + this.tostandardstring() + 40 "\ntostandardstring(): " + tostandardstring(); 41 } // return String representation of SimpleTime 44 public String tostandardstring() 45 { 46 DecimalFormat twodigits = new DecimalFormat( "00" ); // "this" is not required here, because method does not 49 // have local variables with same names as instance variables 50 return twodigits.format( this.hour ) + ":" + 51 twodigits.format( this.minute ) + ":" + 52 twodigits.format( this.second ); 53 } } // end class SimpleTime ThisTest.java this used to distinguish between arguments and Lines ThisTest variables this used to distinguish between argumens and variables Lines use explicit and Use explicit and implicit this to call to call tostandardstring tostandarsstring Initializing Class Objects: Constructors Class constructor Same name as class Initializes instance variables of a class object Call class constructor to instantiate object of that class new ClassName( argument1, argument2,, arugmentn ); new indicates that new object is created ClassName indicates type of object created arguments specifies constructor argument values constructors never return values and cannot specify a return type other methods with same name as class can return values but they are not constructors and will not be called when object is created. constructors are normally declared public

223 Using Overloaded Constructors Overloaded constructors Methods (in same class) may have same name Must have different parameter lists 1 // Fig. 8.5: Time2.java 2 // Time2 class declaration with overloaded constructors. 3 import java.text.decimalformat; 4 5 public class Time2 { 6 private int hour; // private int minute; // private int second; // // Time2 constructor initializes each instance variable to zero; 11 // ensures that Time object starts in a consistent state 12 public Time2() 13 { Overloaded constructor 14 this( 0, 0, 0 ); // invoke Time2 constructor has one with int three arguments 15 } // Time2 constructor: hour supplied, minute and second defaulted to 0 18 public Time2( int h ) 19 { 20 this( h, 0, 0 ); // invoke Time2 constructor has with two int three arguments 21 } // Time2 constructor: hour and minute supplied, second defaulted to 0 24 public Time2( int h, int m ) 25 { 26 this( h, m, 0 ); // invoke Time2 constructor with three arguments 27 } 28 No-argument (default) constructor Use this to invoke the Time2 constructor declared at lines Second overloaded constructor Time2.java Lines No-argument (default) constructor Line 14 Use this to invoke the Time2 constructor declared at lines Lines Overloaded constructor has one int argument Lines Second overloaded constructor has two int arguments

224 29 // Time2 constructor: hour, minute and second supplied 30 public Time2( int h, int m, int s ) 31 { 32 settime( h, m, s ); // invoke settime to validate time 33 } // Time2 constructor: another Time2 object supplied 36 public Time2( Time2 time ) 37 { 38 // invoke Time2 constructor with three arguments 39 this( time.hour, time.minute, time.second ); 40 } has Time2 argument // set a new time value using universal time; perform 43 // validity checks on data; set invalid values to zero 44 public void settime( int h, int m, int s ) 45 { 46 hour = ( ( h >= 0 && h < 24 )? h : 0 ); 47 minute = ( ( m >= 0 && m < 60 )? m : 0 ); 48 second = ( ( s >= 0 && s < 60 )? s : 0 ); 49 } // convert to String in universal-time format 52 public String touniversalstring() 53 { 54 DecimalFormat twodigits = new DecimalFormat( "00" ); return twodigits.format( hour ) + ":" + 57 twodigits.format( minute ) + ":" + twodigits.format( second ); 58 } Third overloaded constructor has three int arguments Time2.java Fourth overloaded constructor Lines Third overloaded constructor has three int arguments Lines Fourth overloaded constructor has Time2 argument // convert to String in standard-time format 61 public String tostandardstring() 62 { 63 DecimalFormat twodigits = new DecimalFormat( "00" ); return ( (hour == 12 hour == 0)? 12 : hour % 12 ) + ":" + 66 twodigits.format( minute ) + ":" + twodigits.format( second ) + 67 ( hour < 12? " AM" : " PM" ); 68 } } // end class Time2 Time2.java

225 1 // Fig. 8.6: TimeTest3.java 2 // Overloaded constructors used to initialize Time2 objects. 3 import javax.swing.*; 4 TimeTest3.java 5 public class TimeTest3 { 6 7 public static void main( String args[] ) Instantiate each Time2 reference Lines 9-14 using a different constructor Instantiate each 8 { Time2 reference 9 Time2 t1 = new Time2(); // 00:00:00 using a different 10 Time2 t2 = new Time2( 2 ); // 02:00:00 11 Time2 t3 = new Time2( 21, 34 ); // 21:34:00 constructor 12 Time2 t4 = new Time2( 12, 25, 42 ); // 12:25:42 13 Time2 t5 = new Time2( 27, 74, 99 ); // 00:00:00 14 Time2 t6 = new Time2( t4 ); // 12:25: String output = "Constructed with: " + 17 "\nt1: all arguments defaulted" + 18 "\n " + t1.touniversalstring() + 19 "\n " + t1.tostandardstring(); output += "\nt2: hour specified; minute and second defaulted" + 22 "\n " + t2.touniversalstring() + 23 "\n " + t2.tostandardstring(); output += "\nt3: hour and minute specified; second defaulted" + 26 "\n " + t3.touniversalstring() + 27 "\n " + t3.tostandardstring(); output += "\nt4: hour, minute and second specified" + 30 "\n " + t4.touniversalstring() + 31 "\n " + t4.tostandardstring(); output += "\nt5: all invalid values specified" + 34 "\n " + t5.touniversalstring() + 35 "\n " + t5.tostandardstring(); output += "\nt6: Time2 object t4 specified" + 38 "\n " + t6.touniversalstring() + 39 "\n " + t6.tostandardstring(); JOptionPane.showMessageDialog( null, output, 42 "Overloaded Constructors", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class TimeTest3 TimeTest3.java

226 Using Set and Get Methods Accessor method ( get method) public method Allow clients to read private data Mutator method ( set method) public method Allow clients to modify private data Accessor methods Methods implement the behavior of objects. Accessors provide information about an object. Methods have a structure consisting of a header and a body. The header defines the method s signature. public int getprice() The body encloses the method s statements.

227 Accessor methods access modifier return type method name public int getprice() { return price; } start and end of method body (block) parameter list (empty) return statement Mutator methods Have a similar method structure: header and body. Used to mutate (i.e., change) an object s state. Achieved through changing the value of one or more fields. Typically contain assignment statements. Typically receive parameters.

228 Mutator methods access modifier return type (void) method name parameter public void insertmoney(int amount) { balance += amount; assignment statement } field being changed Local variables Fields are one sort of variable. They store values through the life of an object. They are accessible throughout the class. Methods can include shorter-lived variables. They exist only as long as the method is being executed. They are only accessible from within the method. Local variables cannot have modifier

229 Local variables No access modifier A local variable public int refundbalance() { int amounttorefund; amounttorefund = balance; balance = 0; return amounttorefund; } Avoid method-parameter names or local variable names that conflict with field names. 1 // Fig. 8.7: Time3.java 2 // Time3 class declaration with set and get methods. 3 import java.text.decimalformat; 4 5 public class Time3 { 6 private int hour; // private int minute; // private int second; // private variables cannot be accessed directly by objects in different classes 10 // Time3 constructor initializes each instance variable to zero; 11 // ensures that Time object starts in a consistent state 12 public Time3() 13 { 14 this( 0, 0, 0 ); // invoke Time3 constructor with three arguments 15 } // Time3 constructor: hour supplied, minute and second defaulted to 0 18 public Time3( int h ) 19 { 20 this( h, 0, 0 ); // invoke Time3 constructor with three arguments 21 } // Time3 constructor: hour and minute supplied, second defaulted to 0 24 public Time3( int h, int m ) 25 { 26 this( h, m, 0 ); // invoke Time3 constructor with three arguments 27 } 28 Time3.java Lines 6-8 private variables cannot be accessed directly by objects in different classes

230 29 // Time3 constructor: hour, minute and second supplied 30 public Time3( int h, int m, int s ) 31 { 32 settime( h, m, s ); 33 } // Time3 constructor: another Time3 object supplied 36 public Time3( Time3 time ) 37 { 38 // invoke Time3 constructor with three arguments 39 this( time.gethour(), time.getminute(), time.getsecond() ); 40 } // Set Methods 43 // set a new time value using universal time; perform 44 // validity checks on data; set invalid values to zero 45 public void settime( int h, int m, int s ) 46 { 47 sethour( h ); // set the hour 48 setminute( m ); // set the minute 49 setsecond( s ); // set the second 50 } // validate and set hour 53 public void sethour( int h ) 54 { 55 hour = ( ( h >= 0 && h < 24 )? h : 0 ); 56 } 57 Time3.java Lines Set methods allows objects to manipulate private variables Set methods allows objects to manipulate private variables 58 // validate and set minute 59 public void setminute( int m ) 60 { 61 minute = ( ( m >= 0 && m < 60 )? m : 0 ); 62 } // validate and set second 65 public void setsecond( int s ) 66 { 67 second = ( ( s >= 0 && s < 60 )? s : 0 ); 68 } // Get Methods 71 // get hour value 72 public int gethour() 73 { 74 return hour; 75 } // get minute value 78 public int getminute() 79 { 80 return minute; 81 } 82 Get methods allow objects to read private variables Time3.java Lines Get methods allow objects to read private variables

231 83 // get second value 84 public int getsecond() 85 { 86 return second; 87 } // convert to String in universal-time format 90 public String touniversalstring() 91 { 92 DecimalFormat twodigits = new DecimalFormat( "00" ); return twodigits.format( gethour() ) + ":" + 95 twodigits.format( getminute() ) + ":" + 96 twodigits.format( getsecond() ); 97 } // convert to String in standard-time format 100 public String tostandardstring() 101 { 102 DecimalFormat twodigits = new DecimalFormat( "00" ); return ( ( gethour() == 12 gethour() == 0 )? : gethour() % 12 ) + ":" + twodigits.format( getminute() ) ":" + twodigits.format( getsecond() ) ( gethour() < 12? " AM" : " PM" ); 108 } } // end class Time3 Time3.java Object Interaction Creating cooperating objects Composition Class contains references to objects of other classes These references are members

232 A digital clock Abstraction and modularization Abstraction is the ability to ignore details of parts to focus attention on a higher level of a problem. Modularization is the process of dividing a whole into well-defined parts, which can be built and examined separately, and which interact in welldefined ways.

233 Modularizing the clock display One four-digit display? Or two two-digit displays? Implementation - NumberDisplay public class NumberDisplay { private int limit; private int value; } Constructor and methods omitted.

234 Implementation -ClockDisplay public class ClockDisplay { private NumberDisplay hours; private NumberDisplay minutes; } Constructor and methods omitted. Object diagram

235 Class diagram Primitive types vs. object types SomeObject obj; object type int i; 32 primitive type

236 Primitive types vs. object types SomeObject a; SomeObject b; int a; 32 b = a; int b; 32 Source code: NumberDisplay public NumberDisplay(int rolloverlimit) { limit = rolloverlimit; value = 0; } public void increment() { value = (value + 1) % limit; }

237 Source code: NumberDisplay public String getdisplayvalue() { if(value < 10) return "0" + value; else return "" + value; } Objects creating objects public class ClockDisplay { private NumberDisplay hours; private NumberDisplay minutes; private String displaystring; } public ClockDisplay() { hours = new NumberDisplay(24); minutes = new NumberDisplay(60); updatedisplay(); }

238 Method calling public void timetick() { minutes.increment(); if(minutes.getvalue() == 0) { // it just rolled over! hours.increment(); } updatedisplay(); } Internal method /** * Update the internal string that * represents the display. */ private void updatedisplay() { displaystring = hours.getdisplayvalue() + ":" + minutes.getdisplayvalue(); }

239 ClockDisplay object diagram Objects creating objects in class NumberDisplay: public NumberDisplay(int rolloverlimit); in class ClockDisplay: formal parameter hours = new NumberDisplay(24); actual parameter

240 Method calls internal method calls updatedisplay(); private void updatedisplay() external method calls minutes.increment(); 1 // Fig. 8.9: Date.java 2 // Date class declaration. Class Date encapsulates 3 4 public class Date { data that describes date 5 private int month; // private int day; // 1-31 based on month 7 private int year; // any year 8 9 // constructor: call checkmonth to confirm proper value for month; 10 // call checkday to confirm proper value for day 11 public Date( int themonth, int theday, int theyear ) 12 { 13 month = checkmonth( themonth ); // validate month 14 year = theyear; // could validate year 15 day = checkday( theday ); // validate day System.out.println( "Date object constructor for date " + 18 todatestring() ); } // end Date constructor // utility method to confirm proper month value 23 private int checkmonth( int testmonth ) 24 { 25 if ( testmonth > 0 && testmonth <= 12 ) // validate month 26 return testmonth; Date.java Date constructor instantiates Date object based on specified arguments Line 4 Class Date encapsulates data that describes date Lines Date constructor instantiates Date object based on specified arguments

241 27 28 else { // month is invalid 29 System.out.println( "Invalid month (" + testmonth + 30 ") set to 1." ); 31 return 1; // maintain object in consistent state 32 } } // end method checkmonth // utility method to confirm proper day value based on month and year 37 private int checkday( int testday ) 38 { 39 int dayspermonth[] = 40 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // check if day in range for month 43 if ( testday > 0 && testday <= dayspermonth[ month ] ) 44 return testday; // check for leap year 47 if ( month == 2 && testday == 29 && ( year % 400 == 0 48 ( year % 4 == 0 && year % 100!= 0 ) ) ) 49 return testday; System.out.println( "Invalid day (" + testday + ") set to 1." ); return 1; // maintain object in consistent state } // end method checkday Date.java // return a String of the form month/day/year 58 public String todatestring() 59 { 60 return month + "/" + day + "/" + year; 61 } } // end class Date Date.java

242 1 // Fig. 8.10: Employee.java 2 // Employee class declaration. 3 4 public class Employee { 5 private String firstname; 6 private String lastname; Employee is composed of two 7 private Date birthdate; references to Date objects 8 private Date hiredate; 9 10 // constructor to initialize name, birth date and hire date 11 public Employee( String first, String last, Date dateofbirth, 12 Date dateofhire ) 13 { 14 firstname = first; 15 lastname = last; 16 birthdate = dateofbirth; 17 hiredate = dateofhire; 18 } // convert Employee to String format 21 public String toemployeestring() 22 { 23 return lastname + ", " + firstname + 24 " Hired: " + hiredate.todatestring() + 25 " Birthday: " + birthdate.todatestring(); 26 } } // end class Employee Employee.java Lines 7-8 Employee is composed of two references to Date objects 1 // Fig. 8.11: EmployeeTest.java 2 // Demonstrating an object with a member object. 3 import javax.swing.joptionpane; 4 5 public class EmployeeTest { 6 7 public static void main( String args[] ) 8 { 9 Date birth = new Date( 7, 24, 1949 ); 10 Date hire = new Date( 3, 12, 1988 ); 11 Employee employee = new Employee( "Bob", "Jones", birth, hire ); JOptionPane.showMessageDialog( null, employee.toemployeestring(), 14 "Testing Class Employee", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); 17 } } // end class EmployeeTest EmployeeTest.ja va Date object constructor for date 7/24/1949 Date object constructor for date 3/12/1988

243 8.10 Garbage Collection Garbage collection Java runtime system returns memory of objects which are no longer needed (objects without references to it). Java performs this automatically object marked for garbage collection if no references to object no guarantee that the garbage collector will be called garbage collector runs with lower priority in parallel with a given program Finalizer method Returns resources (e.g. files or network connections) to system executed before garbage collector reclaims object Java provides method finalize Defined in java.lang.object Receives no parameters cannot be overloaded Returns void 8.11 Static Class Members static keyword static class variable Class-wide information All class objects share same data Access to a class s public static members Qualify the member name with the class name and a dot (.) e.g., Math.random() static class methods and variables exist and can be used, even if no objects have been instantiated. static methods cannot access non-static class members. static methods have no this reference.

244 1 // Fig. 8.12: Employee.java 2 // Employee class declaration. 3 public class Employee { 4 private String firstname; 5 private String lastname; 6 private static int count = 0; // number of objects in memory 7 8 // initialize employee, add 1 to static count and 9 // output String indicating that constructor was called 10 public Employee( String first, String last ) 11 { 12 firstname = first; 13 lastname = last; count; // increment static count of employees 16 System.out.println( "Employee constructor: " + 17 firstname + " " + lastname ); Employee objects share one instance of count 18 } Called when Employee is // subtract 1 from static count when garbage marked collector for garbage collection 21 // calls finalize to clean up object and output String 22 // indicating that finalize was called 23 protected void finalize() 24 { 25 --count; // decrement static count of employees 26 System.out.println( "Employee finalizer: " + 27 firstname + " " + lastname + "; count = " + count ); 28 } 29 Employee.java Line 6 Employee objects share one instance of count Lines Called when Employee is marked for garbage collection 30 // get first name 31 public String getfirstname() 32 { 33 return firstname; 34 } // get last name 37 public String getlastname() 38 { 39 return lastname; static method accesses 40 } 41 static variable count 42 // static method to get static count value 43 public static int getcount() 44 { 45 return count; 46 } } // end class Employee Employee.java Lines static method accesses static variable count

245 1 // Fig. 8.13: EmployeeTest.java 2 // Test Employee class with static class variable, 3 // static class method, and dynamic memory. 4 import javax.swing.*; 5 6 public class EmployeeTest { 7 EmployeeTest can invoke Employee static method, even though Employee has not been instantiated 8 public static void main( String args[] ) 9 { 10 // prove that count is 0 before creating Employees 11 String output = "Employees before instantiation: " + 12 Employee.getCount(); // create two Employees; count should be 2 15 Employee e1 = new Employee( "Susan", "Baker" ); 16 Employee e2 = new Employee( "Bob", "Jones" ); // prove that count is 2 after creating two Employees 19 output += "\n\nemployees after instantiation: " + 20 "\nvia e1.getcount(): " + e1.getcount() + 21 "\nvia e2.getcount(): " + e2.getcount() + 22 "\nvia Employee.getCount(): " + Employee.getCount(); // get names of Employees 25 output += "\n\nemployee 1: " + e1.getfirstname() + 26 " " + e1.getlastname() + "\nemployee 2: " + 27 e2.getfirstname() + " " + e2.getlastname(); 28 EmployeeTest.ja va Line 12 EmployeeTest can invoke Employee static method, even though Employee has not been instantiated 29 // decrement reference count for each Employee object; in this 30 // example, there is only one reference to each Employee, so these 31 // statements mark each Employee object for garbage collection Calls Java s automatic garbagecollection mechanism 32 e1 = null; 33 e2 = null; System.gc(); // suggest call to garbage collector // show Employee count after calling garbage collector; count 38 // displayed may be 0, 1 or 2 based on whether garbage collector 39 // executes immediately and number of Employee objects collected 40 output += "\n\nemployees after System.gc(): " + 41 Employee.getCount(); JOptionPane.showMessageDialog( null, output, 44 "Static Members", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); 47 } } // end class EmployeeTest EmployeeTest.ja va Line 35 Calls Java s automatic garbage-collection mechanism Employee constructor: Susan Baker Employee constructor: Bob Jones Employee finalizer: Susan Baker; count = 1 Employee finalizer: Bob Jones; count = 0

246 8.12 Final Instance Variables final keyword Indicates that variable is not modifiable Any attempt to modify final variable results in error private final int INCREMENT = 5; Declares variable INCREMENT as a constant and initializes the variable declaration and initialization can be separated private final int INCREMENT;... INCREMENT = 5; // must be in a constructor syntax error if final instance variables without initialization final instance variables is tried to be modified after initialization 1 // Fig. 8.14: IncrementTest.java 2 // Initializing a final variable. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class IncrementTest extends JApplet implements ActionListener { 8 private Increment incrementobject; 9 private JButton button; // set up GUI 12 public void init() 13 { 14 incrementobject = new Increment( 5 ); Container container = getcontentpane(); button = new JButton( "Click to increment" ); 19 button.addactionlistener( this ); 20 container.add( button ); 21 } // add INCREMENT to total when user clicks button 24 public void actionperformed( ActionEvent actionevent ) 25 { 26 incrementobject.increment(); 27 showstatus( incrementobject.toincrementstring() ); 28 } } // end class IncrementTest 31 IncrementTest.j ava

247 32 // class containing constant variable 33 class Increment { 34 private int count = 0; // number of increments 35 private int total = 0; // total of all increments 36 private final int INCREMENT; // constant variable // initialize constant INCREMENT 39 public Increment( int incrementvalue ) 40 { 41 INCREMENT = incrementvalue; // intialize constant variable (once) 42 } // add INCREMENT to total and add 1 to count 45 public void increment() final variable INCREMENT must be initialized before using it 46 { 47 total += INCREMENT; 48 ++count; 49 } // return String representation of an Increment object's data 52 public String toincrementstring() 53 { 54 return "After increment " + count + ": total = " + total; 55 } } // end class Increment final keyword declares Increment.java INCREMENT as constant Line 36 final keyword declares INCREMENT as constant Line 41 final variable INCREMENT must be initialized before using it IncrementTest.java:40: variable INCREMENT might not have been initialized { ^ 1 error If statement 41 is outcommented

248 8.13 Creating Packages We can import packages into programs Group of related classes and interfaces Help manage complexity of application components Facilitate software reuse Provide convention for unique class names Popular package-naming convention Reverse Internet domain name e.g., com.deitel Steps for creating a reusable class declare public class choose a package name add package name to the source code of class compile the class (placed in appropriate directory structure) import reusable class into a program for reuse 1 // Fig. 8.16: Time1.java 2 // Time1 class declaration maintains the time in 24-hour format. 3 package com.deitel.jhtp5.ch08; 4 5 import java.text.decimalformat; 6 7 public class Time1 extends Object { 8 private int hour; // private int minute; // private int second; // // Time1 constructor initializes each instance variable to zero; 13 // ensures that each Time1 object starts in a consistent state 14 public Time1() 15 { 16 settime( 0, 0, 0 ); 17 } // set a new time value using universal time; perform Class Time1 is placed in this package Class Time1 is in directory com/deitel/jhtp5/ch08 import class DecimalFormat from package java.text 20 // validity checks on the data; set invalid values to zero 21 public void settime( int h, int m, int s ) 22 { 23 hour = ( ( h >= 0 && h < 24 )? h : 0 ); 24 minute = ( ( m >= 0 && m < 60 )? m : 0 ); 25 second = ( ( s >= 0 && s < 60 )? s : 0 ); 26 } 27 Time1.java Line 3 Class Time1 is placed in this package Line 3 Class Time1 is in directory com/deitel/jhtp 5/ch08 Line 5 import class DecimalFormat from package java.text class Time1 will be placed in directory ch08 in com/deitel/jhtp5 compiling with javac d generates appropriate directory structure if it does not exist.

249 28 // convert to String in universal-time format 29 public String touniversalstring() 30 { 31 DecimalFormat twodigits = new DecimalFormat( "00" ); return twodigits.format( hour ) + ":" + 34 twodigits.format( minute ) + ":" + twodigits.format( second ); 35 } // convert to String in standard-time format 38 public String tostandardstring() 39 { 40 DecimalFormat twodigits = new DecimalFormat( "00" ); return ( (hour == 12 hour == 0)? 12 : hour % 12 ) + ":" + 43 twodigits.format( minute ) + ":" + twodigits.format( second ) + 44 ( hour < 12? " AM" : " PM" ); 45 } } // end class Time1 DecimalFormat Time1.java from package java.text Line 31 DecimalFormat from package java.text 1 // Fig. 8.17: TimeTest1.java 2 // Class TimeTest1 to exercise class Time1. import class JOptionPane from package javax.swing 3 4 // Java packages 5 import javax.swing.joptionpane; 6 7 // Deitel packages 8 import com.deitel.jhtp5.ch08.time1; // import Time1 class 9 10 public class TimeTest1 { public static void main( String args[] ) 13 { 14 Time1 time = new Time1(); // calls Time1 constructor // append String version of time to String output 17 String output = "The initial universal time is: " + 18 time.touniversalstring() + "\nthe initial standard time is: " + 19 time.tostandardstring(); // change time and append updated time to output 22 time.settime( 13, 27, 6 ); 23 output += "\n\nuniversal time after settime is: " + 24 time.touniversalstring() + 25 "\nstandard time after settime is: " + time.tostandardstring(); 26 import class Time1 from package com.deitel.jhtp4.ch08 TimeTest1 can declare Time1 object TimeTest1.java Line 5 import class JOptionPane from package javax.swing Line 8 import class Time1 from package com.deitel.jhtp 4.ch08 Line 14 TimeTest1 can declare Time1 object

250 27 // set time with invalid values; append updated time to output 28 time.settime( 99, 99, 99 ); 29 output += "\n\nafter attempting invalid settings: " + 30 "\nuniversal time: " + time.touniversalstring() + 31 "\nstandard time: " + time.tostandardstring(); JOptionPane.showMessageDialog( null, output, 34 "Testing Class Time1", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class TimeTest1 TimeTest1.java Package access 8.14 Package Access Variable or method without access modifier (public, protected or private) default access modifier: package access Program with one class declaration no effect Program that uses multiple classes from the same package classes can access each other s package access methods and fields through proper object references

251 1 // Fig. 8.18: PackageDataTest.java 2 // Classes in the same package (i.e., the same directory) can 3 // use package access data of other classes in the same package. 4 import javax.swing.joptionpane; Instantiate reference PackageDataTest to 5 PackageData object.java 6 public class PackageDataTest { 7 Line 10 8 public static void main( String args[] ) Instantiate reference to 9 { PackageData 10 PackageData packagedata = new PackageData(); 11 object 12 // append String representation of packagedata to output 13 String output = "After instantiation:\n" + Lines packagedata.topackagedatastring(); PackageDataTest PackageDataTest can 15 access PackageData can access 16 // change package access data in packagedata object data, because each class PackageData data, 17 packagedata.number = 77; shares same package because each class 18 packagedata.string = "Goodbye"; shares same 19 package 20 // append String representation of packagedata to output 21 output += "\nafter changing values:\n" + 22 packagedata.topackagedatastring(); JOptionPane.showMessageDialog( null, output, "Package Access", 25 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); 28 } } // end class PackageDataTest // class with package access instance variables 33 class PackageData { 34 int number; // package-access instance variable 35 String string; // package-access instance variable // constructor 38 public PackageData() 39 { 40 number = 0; 41 string = "Hello"; 42 } // return PackageData object String representation 45 public String topackagedatastring() 46 { 47 return "number: " + number + " string: " + string; 48 } } // end class PackageData No access modifier, so class has package-access variables PackageDataTest.java Line 33 No access modifier, so class has packageaccess variables

252 Review Class bodies contain fields, constructors and methods. Fields store values that determine an object s state. Constructors initialize objects. Methods implement the behavior of objects. Review Fields, parameters and local variables are all variables. Fields persist for the lifetime of an object. Parameters are used to receive values into a constructor or method. Local variables are used for short-lived temporary storage. Classes can be grouped to packages for software reuse

253 1 Part 11 Object Oriented Programming: Inheritance 2003 Prentice Hall, Inc. All rights reserved. Main concepts to be covered 2 Superclasses and Subclasses protected Members Relationship between Superclasses and Subclasses Case Study: Three-Level Inheritance Hierarchy Constructors and Finalizers in Subclasses Software Engineering with Inheritance

254 Introduction: Inheritance 3 Software reusability Create new class from existing class Absorb existing class s data and behaviors (methods) Enhance with new capabilities Subclass extends superclass Subclass More specialized group of objects Behaviors inherited from superclass Can customize Additional behaviors Central object oriented concepts (1) 4 Inheritance Derive subclasses from existing classes ( Class hierarchy). The subclass inherits the variables and methods of a superclass. A subclass may define new variables and methods. Methods of a superclass can be overwritten in a subclass. class Person { String name; private String svnr; public int getalter {...} } class Student extends Person { String matrnr; } // superclass // subclass

255 5 Central object oriented concepts (2) Class Object Class Object implicitly is a superclass of any other class. Class Object provides methods which can be used by any other class. Example: The Java Collection API (java.util) uses class Object to support data structures (Vector, Stack, LinkedList, Hashtable,...) for management of objects derived from arbitrary classes. 6 Class Hierarchy Direct superclass Inherited explicitly (one level up hierarchy) Indirect superclass Inherited two or more levels up hierarchy Single inheritance Inherits from one superclass Multiple inheritance Inherits from multiple superclasses Java does not support multiple inheritance ClassN ClassN-1... Class2 ClassN-1 Class1

256 7 The DoME example "Database of Multimedia Entertainment" stores details about CDs and videos CD: title, artist, # tracks, playing time, got-it, comment Video: title, director, playing time, got-it, comment allows (later) to search for information or print lists 8 DoME objects

257 DoME classes 9 DoME object model 10

258 Class diagram 11 CD source code [ ] incomplete (comments!) public class CD { private String title; private String artist; private String comment; CD(String thetitle, String theartist) { title = thetitle; artist = theartist; comment = " "; } void setcomment(string newcomment) {... } String getcomment() {... } 12 } void print() {... }...

259 Video source code public class Video { private String title; private String director; private String comment; Video(String thetitle, String thedirect) { title = thetitle; director = thedirect; comment = " "; } 13 [ ] incomplete (comments!) void setcomment(string newcomment) {... } String getcomment() {... } } void print() {... } class Database { private ArrayList cds; private ArrayList videos;... Database source code public void list() { for(iterator iter = cds.iterator(); iter.hasnext(); ) { CD cd = (CD)iter.next(); cd.print(); System.out.println(); // empty line between items } } } for(iterator iter = videos.iterator(); iter.hasnext(); ) { Video video = (Video)iter.next(); video.print(); System.out.println(); // empty line between items }

260 15 code duplication Critique of DoME CD and Video classes very similar (large part are identical) makes maintenance difficult/more work introduces danger of bugs through incorrect maintenance code duplication also in Database class 16 Using inheritance

261 17 Using inheritance define one superclass : Item define subclasses for Video and CD the superclass defines common attributes the subclasses inherit the superclass members the subclasses add own members 18 Inheritance hierarchies

262 Inheritance in Java 19 public class Item {... } no change here change here public class CD extends Item {... } public class Video extends Item {... } Superclass 20 public class Item { private String title; private int playingtime; private boolean gotit; private String comment; } // constructors and methods omitted.

263 Subclasses 21 public class CD extends Item { private String artist; private int numberoftracks; } // constructors and methods omitted. public class Video extends Item { private String director; } // constructors and methods omitted. 22 public class Item { private String title; private int playingtime; private boolean gotit; private String comment; Inheritance and constructors /** * Initialise the fields of the item. */ public Item(String thetitle, int time) { title = thetitle; playingtime = time; gotit = false; comment = ""; } } // methods omitted

264 23 public class CD extends Item { private String artist; private int numberoftracks; Inheritance and constructors /** * Constructor for objects of class CD */ public CD(String thetitle, String theartist, int tracks, int time) { super(thetitle, time); artist = theartist; numberoftracks = tracks; } } // methods omitted 24 Superclass constructor call Subclass constructors must always contain a 'super' call. If none is written, the compiler inserts one (without parameters) works only, if the superclass has a constructor without parameters Must be the first statement in the subclass constructor.

265 Adding more item types 25 Deeper hierarchies 26 Inheritance is transitive

266 27 Review (so far) Inheritance (so far) helps with: Avoiding code duplication Code reuse Easier maintenance Extendibility 28 public class Database { private ArrayList items; } /** * Construct an empty Database. */ public Database() { items = new ArrayList(); } /** * Add an item to the database. */ public void additem(item theitem) { items.add(theitem); }... New Database source code avoids code duplication in client!

267 New Database source code 29 /** * Print a list of all currently stored CDs and * videos to the text terminal. */ public void list() { for(iterator iter = items.iterator(); iter.hasnext(); ) { Item item = (Item)iter.next(); item.print(); System.out.println(); // empty line between items } } Subtyping 30 First, we had: public void addcd(cd thecd) public void addvideo(video thevideo) Now, we have: public void additem(item theitem) We call this method with: Video myvideo = new Video(...); database.additem(myvideo);

268 31 Subclasses and subtyping Classes define types. Subclasses define subtypes. Objects of subclasses can be used where objects of supertypes are required. (This is called substitution.) 32 Subtyping and assignment subclass objects may be assigned to superclass variables Vehicle v1 = new Vehicle(); Vehicle v2 = new Car(); Vehicle v3 = new Bicycle();

269 Subtyping and parameter passing 33 public class Database { } public void additem(item theitem) {... } Video video = new Video(...); CD cd = new CD(...); database.additem(video); database.additem(cd); subclass objects may be passed to superclass parameters Object diagram 34

270 Class diagram 35 Abstraction 36 Focus on commonalities among objects in system is-a vs. has-a is-a Inheritance Upperclass represents an abstraction (more generic concept) of a lower class subclass object treated as superclass object Example: Car is a vehicle Vehicle properties/behaviors also car properties/behaviors has-a Composition Object contains one or more objects of other classes as members Example: Car has a steering wheel

271 42 protected Members protected access Intermediate level of protection between public and private protected members of a superclass are accessible to superclass members subclass members Class members in the same package Subclass access superclass member Keyword super and a dot (.) Protected does not allow access to a class s methods to clients other than subclasses. declare superclass instance variables private superclass implementation can change without affecting subclasses private members are not inherited by subclasses public members are inherited by subclasses Relationship between Superclasses and Subclasses 43 Superclass and subclass relationship Example: Point/circle inheritance hierarchy Point x-y coordinate pair Circle x-y coordinate pair Radius Constructors are not inherited Direct superclass s constructor is called implicitly (with no arguments) or explicitly (possibly with several arguments).

272 1 // Fig. 9.4: Point.java 2 // Point class declaration represents Maintain an x-y x-coordinate and y- pair. 3 coordinates as private 4 public class Point { instance variables. 5 private int x; // x part of coordinate pair 6 private int y; // y part of coordinate pair 7 8 // no-argument constructor 9 public Point() 10 { Implicit call to Object constructor 11 // implicit call to Object constructor occurs here 12 } // constructor 15 public Point( int xvalue, int yvalue ) 16 { 17 // implicit call to Object constructor occurs here 18 x = xvalue; // no need for validation 19 y = yvalue; // no need for validation 20 } // set x in coordinate pair 23 public void setx( int xvalue ) 24 { 25 x = xvalue; // no need for validation 26 } 27 Point.java Outline 44 Lines 5-6 Maintain x- and y- coordinates as private instance variables. Line 11 Implicit call to Object constructor 28 // return x from coordinate pair 29 public int getx() 30 { 31 return x; 32 } // set y in coordinate pair 35 public void sety( int yvalue ) 36 { 37 y = yvalue; // no need for validation 38 } // return y from coordinate pair 41 public int gety() 42 { 43 return y; 44 } Override method tostring 45 of class Object 46 // return String representation of Point object 47 public String tostring() 48 { 49 return "[" + x + ", " + y + "]"; 50 } } // end class Point Point.java Outline Lines Override method tostring of class Object. 45

273 1 // Fig. 9.5: PointTest.java 2 // Testing class Point. 3 import javax.swing.joptionpane; 4 5 public class PointTest { 6 7 public static void main( String[] args ) 8 { 9 Point point = new Point( 72, 115 ); // create Point object // get point coordinates 12 String output = "X coordinate is " + point.getx() + Change the value of point s x- 13 "\ny coordinate is " + point.gety(); and y- coordinates point.setx( 10 ); // set x-coordinate 16 point.sety( 20 ); // set y-coordinate // get String representation of new point value 19 output += "\n\nthe new location of point is " + point; JOptionPane.showMessageDialog( null, output ); // display output System.exit( 0 ); } // end main } // end class PointTest Outline PointTest.java Instantiate Point object Line 9 Instantiate Point object 46 Lines Change the value of point s x- and y- Implicitly coordinates call point s tostring method Line 19 Implicitly call point s tostring method 1 // Fig. 9.6: Circle.java 2 // Circle class contains x-y coordinate pair and radius. 3 4 public class Circle { Maintain x-y coordinates and 5 private int x; // x-coordinate radiusof as Circle's privatecenter 6 private int y; // y-coordinate instance of variables. Circle's center 7 private double radius; // Circle's radius 8 9 // no-argument constructor 10 public Circle() 11 { 12 // implicit call to Object constructor occurs here 13 } // constructor 16 public Circle( int xvalue, int yvalue, double radiusvalue ) 17 { 18 // implicit call to Object constructor occurs here 19 x = xvalue; // no need for validation 20 y = yvalue; // no need for validation 21 setradius( radiusvalue ); 22 } // set x in coordinate pair 25 public void setx( int xvalue ) 26 { 27 x = xvalue; // no need for validation 28 } 29 Note code similar to Point code. Outline Circle.java 47 Lines 5-7 Maintain x- and y- coordinates and radius as private instance variables. Lines Note code similar to Point code.

274 30 // return x from coordinate pair 31 public int getx() 32 { 33 return x; 34 } // set y in coordinate pair 37 public void sety( int yvalue ) 38 { 39 y = yvalue; // no need for validation 40 } // return y from coordinate pair 43 public int gety() 44 { 45 return y; 46 } // set radius 49 public void setradius( double radiusvalue ) 50 { 51 radius = ( radiusvalue < 0.0? 0.0 : radiusvalue ); 52 } // return radius 55 public double getradius() 56 { 57 return radius; 58 } 59 Outline Note code similar to Point Circle.java code. Lines Note code similar to Point code. Ensure non-negative value for radius. Line 51 Ensure non-negative value for radius // calculate and return diameter 61 public double getdiameter() 62 { 63 return 2 * radius; 64 } // calculate and return circumference 67 public double getcircumference() 68 { 69 return Math.PI * getdiameter(); 70 } // calculate and return area 73 public double getarea() 74 { 75 return Math.PI * radius * radius; 76 } // return String representation of Circle object 79 public String tostring() 80 { 81 return "Center = [" + x + ", " + y + "]; Radius = " + radius; 82 } } // end class Circle Outline Circle.java 49

275 1 // Fig. 9.7: CircleTest.java 2 // Testing class Circle. 3 import java.text.decimalformat; 4 import javax.swing.joptionpane; 5 6 public class CircleTest { 7 8 public static void main( String[] args ) 9 { 10 Circle circle = new Circle( 37, 43, 2.5 ); // create Circle object // get Circle's initial x-y coordinates and radius 13 String output = "X coordinate is " + circle.getx() + 14 "\ny coordinate is " + circle.gety() + 15 "\nradius is " + circle.getradius(); circle.setx( 35 ); // set new x-coordinate 18 circle.sety( 20 ); // set new y-coordinate 19 circle.setradius( 4.25 ); // set new radius 20 Explicitly call circle s 21 // get String representation of new tostring circle Use value set methods to modify 22 output += "\n\nthe new location and radius of circle are\n" + 23 circle.tostring(); // format floating-point values with 2 digits of precision 26 DecimalFormat twodigits = new DecimalFormat( "0.00" ); 27 Create Circle object. private instance variable. Outline 50 CircleTest.java Line 10 Create Circle object Lines Use set methods to modify private instance variable Line 23 Explicitly call circle s tostring method // get Circle's diameter Outline 29 output += "\ndiameter is " + 30 twodigits.format( circle.getdiameter() ); 31 CircleTest.java 32 // get Circle's circumference Use get methods to 33 output += "\ncircumference is " + obtain Lines circle s diameter, 34 twodigits.format( circle.getcircumference() ); 35 circumference and area. Use get methods to 36 // get Circle's area obtain circle s 37 output += "\narea is " + twodigits.format( circle.getarea() ); 38 diameter, 39 JOptionPane.showMessageDialog( null, output ); // display output circumference and 40 area. 41 System.exit( 0 ); } // end main } // end class CircleTest

276 1 // Fig. 9.8: Circle2.java 2 // Circle2 class inherits from Point. 3 4 public class Circle2 extends Point { 5 private double radius; // Circle2's radius 6 7 // no-argument constructor 8 public Circle2() 9 { 10 // implicit call to Point constructor occurs here 11 } 12 Class Circle2 extends class Point. Maintain private instance variable radius. 13 // constructor 14 public Circle2( int xvalue, int yvalue, double radiusvalue ) 15 { 16 // implicit call to Point constructor occurs here 17 x = xvalue; // not allowed: x private errors. in Point 18 y = yvalue; // not allowed: y private in Point 19 setradius( radiusvalue ); 20 } // set radius 23 public void setradius( double radiusvalue ) 24 { 25 radius = ( radiusvalue < 0.0? 0.0 : radiusvalue ); 26 } 27 Attempting to access superclass Point s private instance variables x and y results in syntax Outline Circle2.java 52 Line 4 Class Circle2 extends class Point. Line 5 Maintain private instance variable radius. Lines Attempting to access superclass Point s private instance variables x and y results in syntax errors. 34 // calculate and return diameter 35 public double getdiameter() 36 { 37 return 2 * radius; 38 } // calculate and return circumference 41 public double getcircumference() 42 { 43 return Math.PI * getdiameter(); 44 } // calculate and return area 47 public double getarea() 48 { 49 return Math.PI * radius * radius; 50 } // return String representation of Circle object 53 public String tostring() 54 { Attempting to access superclass Point s private instance variables x and y results in syntax errors. 55 // use of x and y not allowed: x and y private in Point 56 return "Center = [" + x + ", " + y + "]; Radius = " + radius; 57 } } // end class Circle2 Outline Circle2.java Line 56 Attempting to access superclass Point s private instance variables x and y results in syntax errors. 53

277 Outline 54 Circle2.java:17: x has private access in Point x = xvalue; // not allowed: x private in Point ^ Circle2.java:18: y has private access in Point y = yvalue; // not allowed: y private in Point ^ Circle2.java:56: x has private access in Point return "Center = [" + x + ", " + y + "]; Radius = " + radius; ^ Circle2.java:56: y has private access in Point return "Center = [" + x + ", " + y + "]; Radius = " + radius; ^ 4 errors Circle2.java output Attempting to access superclass Point s private instance variables x and y results in syntax errors. Attempting to access superclass Point s private instance variables x and y results in syntax errors. 1 // Fig. 9.9: Point2.java 2 // Point2 class declaration represents an x-y coordinate pair. Maintain x- and y- 3 4 public class Point2 { coordinates as protected 5 protected int x; // x part of coordinate instance pair variables, accessible 6 protected int y; // y part of coordinate to subclasses. pair 7 8 // no-argument constructor 9 public Point2() 10 { 11 // implicit call to Object constructor occurs here 12 } // constructor 15 public Point2( int xvalue, int yvalue ) 16 { 17 // implicit call to Object constructor occurs here 18 x = xvalue; // no need for validation 19 y = yvalue; // no need for validation 20 } // set x in coordinate pair 23 public void setx( int xvalue ) 24 { 25 x = xvalue; // no need for validation 26 } 27 Outline Point2.java 55 Lines 5-6 Maintain x- and y- coordinates as protected instance variables, accessible to subclasses.

278 28 // return x from coordinate pair 29 public int getx() 30 { 31 return x; 32 } // set y in coordinate pair 35 public void sety( int yvalue ) 36 { 37 y = yvalue; // no need for validation 38 } // return y from coordinate pair 41 public int gety() 42 { 43 return y; 44 } // return String representation of Point2 object 47 public String tostring() 48 { 49 return "[" + x + ", " + y + "]"; 50 } } // end class Point2 Outline Point2.java 56 1 // Fig. 9.10: Circle3.java 2 // Circle3 class inherits from Point2 and has Class access Circle3 to Point2 inherits from 3 // protected members x and y. Maintain class Point2. private instance 4 5 public class Circle3 extends Point2 { variables radius. 6 private double radius; // Circle3's radius 7 8 // no-argument constructor 9 public Circle3() 10 { 11 // implicit call to Point2 constructor occurs here 12 } // constructor Implicitly calls superclass s default constructor. 15 public Circle3( int xvalue, int Modify yvalue, inherited double radiusvalue instance ) 16 { variables x and y, declared 17 // implicit call to Point2 constructor occurs here protected in superclass 18 x = xvalue; // no need for validation Point2. 19 y = yvalue; // no need for validation 20 setradius( radiusvalue ); 21 } // set radius 24 public void setradius( double radiusvalue ) 25 { 26 radius = ( radiusvalue < 0.0? 0.0 : radiusvalue ); 27 } 28 Outline Circle3.java Line 5 Class Circle3 inherits from class Point2. Line 6 Maintain private instance variables radius. Lines 11 and 17 Implicitly call superclass s default constructor. Lines Modify inherited instance variables x and y, declared protected in superclass Point2. 57

279 29 // return radius 30 public double getradius() 31 { 32 return radius; 33 } // calculate and return diameter 36 public double getdiameter() 37 { 38 return 2 * radius; 39 } // calculate and return circumference 42 public double getcircumference() 43 { 44 return Math.PI * getdiameter(); 45 } // calculate and return area 48 public double getarea() 49 { 50 return Math.PI * radius * radius; 51 } // return String representation of Circle3 object 54 public String tostring() 55 { Access inherited instance variables x and y, declared protected in superclass Point2. 56 return "Center = [" + x + ", " + y + "]; Radius = " + radius; 57 } } // end class Circle3 Outline Circle3.java Line 56 Access inherited instance variables x and y, declared protected in superclass Point // Fig. 9.11: CircleTest3.java 2 // Testing class Circle3. 3 import java.text.decimalformat; 4 import javax.swing.joptionpane; 5 6 public class CircleTest3 { 7 8 public static void main( String[] args ) 9 { 10 // instantiate Circle object 11 Circle3 circle = new Circle3( 37, 43, 2.5 ); // get Circle3's initial x-y coordinates and radius 14 String output = "X coordinate is " + circle.getx() + 15 "\ny coordinate is " + circle.gety() + 16 "\nradius is " + circle.getradius(); circle.setx( 35 ); // set new x-coordinate 19 circle.sety( 20 ); // set new y-coordinate 20 circle.setradius( 4.25 ); // set new radius // get String representation of new circle value Outline 59 Circletest3.java Line 11 Create Circle3 object. Lines Use inherited get methods to access inherited protected instance Use inherited variables get methods x and y. to Use variables x and y. access Circle3 inherited get method protected to access Line 16 instance private variables instance Use Circle3 x and y. variables. get method to access private instance variables. Lines Use inherited set methods to modify inherited protected data x and y. Line 20 Use Circle3 set method to modify private data radius. Create Circle3 object. Use inherited set methods to modify inherited Use Circle3 protected set method data to x and y. 23 output += "\n\nthe new location and radius of circle are\n" + 24 circle.tostring(); modify private data 25 radius.

280 26 // format floating-point values with 2 digits of precision 27 DecimalFormat twodigits = new DecimalFormat( "0.00" ); // get Circle's diameter 30 output += "\ndiameter is " + 31 twodigits.format( circle.getdiameter() ); // get Circle's circumference 34 output += "\ncircumference is " + 35 twodigits.format( circle.getcircumference() ); // get Circle's area 38 output += "\narea is " + twodigits.format( circle.getarea() ); JOptionPane.showMessageDialog( null, output ); // display output System.exit( 0 ); } // end method main } // end class CircleTest3 Outline 60 Circletest3.jav a Relationship between Superclasses and Subclasses (Cont.) 61 Using protected instance variables Advantages subclasses can modify values directly Slight increase in performance Avoid set/get function call overhead Disadvantages No validity checking subclass can assign illegal value Implementation dependent subclass methods more likely dependent on superclass implementation superclass implementation changes may result in subclass modifications Fragile (brittle) software

281 Relationship between Superclasses and Subclasses (Cont.) 62 Override a method with a more restricted access modifier syntax error A public method of the superclass cannot become a protected or private method in the subclass. Declare superclass instance variables private (as opposed to protected), thus superclass implementation can change without affecting subclass implementation. instead of protected instance variables: non-private methods for accessing private variables 1 // Fig. 9.12: Point3.java 2 // Point class declaration represents an x-y coordinate pair. Better software-engineering 3 4 public class Point3 { practice: private over 5 private int x; // x part of coordinate protected pair when possible. 6 private int y; // y part of coordinate pair 7 8 // no-argument constructor 9 public Point3() 10 { 11 // implicit call to Object constructor occurs here 12 } // constructor 15 public Point3( int xvalue, int yvalue ) 16 { 17 // implicit call to Object constructor occurs here 18 x = xvalue; // no need for validation 19 y = yvalue; // no need for validation 20 } // set x in coordinate pair 23 public void setx( int xvalue ) 24 { 25 x = xvalue; // no need for validation 26 } 27 Outline Point3.java Lines 5-6 Better softwareengineering practice: private over protected when possible. 63

282 28 // return x from coordinate pair 29 public int getx() Outline 30 { 31 return x; 32 } Point3.java // set y in coordinate pair Line public void sety( int yvalue ) Invoke public 36 { methods to access 37 y = yvalue; // no need for validation private instance 38 } 39 variables. 40 // return y from coordinate pair 41 public int gety() 42 { 43 return y; 44 } 45 Invoke public methods to access 46 // return String representation of Point3 object private instance variables. 47 public String tostring() 48 { 49 return "[" + getx() + ", " + gety() + "]"; 50 } } // end class Point // Fig. 9.13: Circle4.java Class Circle4 inherits from 2 // Circle4 class inherits from Point3 and accesses Point3's 3 // private x and y via Point3's public methods. class Point public class Circle4 extends Point3 { Maintain private instance variable radius. 6 7 private double radius; // Circle4's radius 8 9 // no-argument constructor 10 public Circle4() 11 { 12 // implicit call to Point3 constructor occurs here 13 } // constructor 16 public Circle4( int xvalue, int yvalue, double radiusvalue ) 17 { 18 super( xvalue, yvalue ); // call Point3 constructor explicitly 19 setradius( radiusvalue ); 20 } // set radius 23 public void setradius( double radiusvalue ) 24 { 25 radius = ( radiusvalue < 0.0? 0.0 : radiusvalue ); 26 } 27 Outline Circle4.java Line 5 Class Circle4 inherits from class Point3. Line 7 Maintain private instance variable radius. 65

283 28 // return radius 29 public double getradius() 30 { 31 return radius; 32 } // calculate and return diameter 35 public double getdiameter() 36 { 37 return 2 * getradius(); 38 } // calculate and return circumference 41 public double getcircumference() 42 { 43 return Math.PI * getdiameter(); 44 } // calculate and return area 47 public double getarea() 48 { Invoke method getradius rather than directly accessing instance variable radius. 49 return Math.PI * getradius() * getradius(); 50 } Redefine class Point3 s method tostring. // return String representation of Circle4 object 53 public String tostring() 54 { 55 return "Center = " + super.tostring() + "; Radius = " + getradius(); 56 } } // end class Circle4 Outline Circle4.java 66 Line 37, 49 and 55 Invoke method getradius rather than directly accessing instance variable radius. Lines Redefine class Point3 s method tostring. 1 // Fig. 9.14: CircleTest4.java 2 // Testing class Circle4. 3 import java.text.decimalformat; 4 import javax.swing.joptionpane; 5 6 public class CircleTest4 { 7 8 public static void main( String[] args ) Create Circle4 object. 9 { 10 // instantiate Circle object 11 Circle4 circle = new Circle4( 37, 43, 2.5 ); // get Circle4's initial x-y coordinates and radius 14 String output = "X coordinate is " + circle.getx() + 15 "\ny coordinate is " + circle.gety() + 16 "\nradius is " + circle.getradius(); variable radius circle.setx( 35 ); // set new x-coordinate 19 circle.sety( 20 ); // set new y-coordinate Use inherited seta methods to 20 circle.setradius( 4.25 ); // set new radius 21 modify inherited private 22 // get String representation of new circle Use instance value Circle4 variables set method x and y. to 23 output += "\n\nthe new location and radius modify of circle private are\n" instance + variable radius. 24 circle.tostring(); 25 Outline 67 Circletest4.java Line 11 Create Circle4 object. Lines 14 and 15 Use inherited get methods to access inherited private instance variables x and y. Line 16 Use Circle4 get method to access private instance variable radius. Lines Use inherited seta methods to modify inherited private instance variables x and y. Line 20 Use Circle4 set method to modify private instance variable radius. Use inherited get methods to access inherited private instance Use Circle4 variables get x method and y. to access private instance

284 26 // format floating-point values with 2 digits of precision 27 DecimalFormat twodigits = new DecimalFormat( "0.00" ); // get Circle's diameter 30 output += "\ndiameter is " + 31 twodigits.format( circle.getdiameter() ); // get Circle's circumference 34 output += "\ncircumference is " + 35 twodigits.format( circle.getcircumference() ); // get Circle's area 38 output += "\narea is " + twodigits.format( circle.getarea() ); JOptionPane.showMessageDialog( null, output ); // display output System.exit( 0 ); } // end main } // end class CircleTest4 Outline 68 Circletest4.jav a Case Study: Three-Level Inheritance Hierarchy 69 Three level point/circle/cylinder hierarchy Point x-y coordinate pair Circle x-y coordinate pair Radius Cylinder x-y coordinate pair Radius Height

285 1 // Fig. 9.15: Cylinder.java 2 // Cylinder class inherits from Circle public class Cylinder extends Circle4 { 5 private double height; // Cylinder's height 6 7 // no-argument constructor 8 public Cylinder() 9 { 10 // implicit call to Circle4 constructor occurs here 11 } // constructor Maintain private instance variable height. Class Cylinder extends class Circle4. 14 public Cylinder( int xvalue, int yvalue, double radiusvalue, 15 double heightvalue ) 16 { 17 super( xvalue, yvalue, radiusvalue ); // call Circle4 constructor 18 setheight( heightvalue ); 19 } // set Cylinder's height 22 public void setheight( double heightvalue ) 23 { 24 height = ( heightvalue < 0.0? 0.0 : heightvalue ); 25 } 26 Outline Cylinder.java Line 4 Class Cylinder extends class Circle4. Line 5 Maintain private instance variable height // get Cylinder's height 28 public double getheight() 29 { 30 return height; 31 } Redefine superclass 32 Circle4 s method 33 // override Circle4 method getarea to calculate Invoke Cylinder superclass getarea to return area 34 public double getarea() Circle4 s getarea Cylinder surface area. 35 { method using keyword super. 36 return 2 * super.getarea() + getcircumference() * getheight(); 37 } // calculate Cylinder volume 40 public double getvolume() 41 { 42 return super.getarea() * getheight(); 43 } Redefine class Circle4 s 44 method tostring. 45 // return String representation of Cylinder Invoke objectsuperclass 46 public String tostring() Circle4 s tostring 47 { method using keyword super. 48 return super.tostring() + "; Height = " + getheight(); 49 } } // end class Cylinder Outline Cylinder.java 71 Line 34 and 42 Redefine superclass Circle4 s method getarea to return Cylinder surface area. Line 36 Invoke superclass Circle4 s getarea method using keyword super. Lines Redefine class Circle4 s method tostring. Line 48 Invoke superclass Circle4 s tostring method using keyword super.

286 1 // Fig. 9.16: CylinderTest.java 2 // Testing class Cylinder. 3 import java.text.decimalformat; 4 import javax.swing.joptionpane; 5 6 public class CylinderTest { 7 8 public static void main( String[] args ) 9 { 10 // create Cylinder object 11 Cylinder cylinder = new Cylinder( 12, 23, 2.5, 5.7 ); // get Cylinder's initial x-y coordinates, Invoke radius directly and height inherited 14 String output = "X coordinate is " + cylinder.getx() Circle4 get + method. 15 "\ny coordinate is " + cylinder.gety() + "\nradius is " + 16 cylinder.getradius() + "\nheight is " + cylinder.getheight(); cylinder.setx( 35 ); // set new x-coordinate Invoke indirectly inherited 19 cylinder.sety( 20 ); // set new y-coordinate 20 cylinder.setradius( 4.25 ); // set new Point3 radius set methods. 21 cylinder.setheight( ); // set new Invoke height directly inherited 22 Circle4 set method. Invoke Cylinder set 23 // get String representation of new cylinder value 24 output += method. 25 "\n\nthe new location, radius and height of cylinder are\n" + 26 cylinder.tostring(); 27 Invoke overridden tostring method. Outline 72 CylinderTest.java Lines 14 and 15 Invoke indirectly inherited Point3 get methods. Line 16 Invoke directly inherited Circle4 get method. Line 16 Invoke Cylinder get method. Lines Invoke indirectly inherited Point3 set methods. Line 20 Invoke directly inherited Circle4 set method. Line 21 Invoke Cylinder set method. Line 26 Invoke overridden tostring method. method. Invoke indirectly inherited Point3 get methods. Invoke Cylinder get method. 28 // format floating-point values with 2 digits of precision 29 DecimalFormat twodigits = new DecimalFormat( "0.00" ); // get Cylinder's diameter 32 output += "\n\ndiameter is " + 33 twodigits.format( cylinder.getdiameter() ); // get Cylinder's circumference 36 output += "\ncircumference is " + 37 twodigits.format( cylinder.getcircumference() ); // get Cylinder's area 40 output += "\narea is " + twodigits.format( cylinder.getarea() ); // get Cylinder's volume 43 output += "\nvolume is " + twodigits.format( cylinder.getvolume() ); JOptionPane.showMessageDialog( null, output ); // display output System.exit( 0 ); } // end main } // end class CylinderTest Outline 73 CylinderTest.ja va Line 40 Invoke overridden getarea method. Invoke overridden getarea method.

287 74 Constructors and Finalizers in Subclasses Instantiating subclass object Chain of constructor calls subclass constructor invokes superclass constructor Implicitly or explicitly subclass constructor immediately calls the superclass constructor (explicitly, via super or implicitly) Base of inheritance hierarchy Last constructor called in chain is Object s constructor Original subclass constructor s body finishes executing last Example: Point3/Circle4/Cylinder hierarchy Point3 constructor called second last (last is Object constructor) Point3 constructor s body finishes execution second (first is Object constructor s body) Circle4 and Cylinder constructor s body finishes execution third and fourth, respectively 9.6 Constructors and Destructors in Derived Classes 75 Garbage collecting subclass object Chain of finalize method calls Reverse order of constructor chain Finalizer of subclass called first Finalizer of next superclass up hierarchy next Continue up hierarchy until final superreached After final superclass (Object) finalizer, object removed from memory

288 1 // Fig. 9.17: Point.java 2 // Point class declaration represents an x-y coordinate pair. 3 4 public class Point { 5 private int x; // x part of coordinate pair 6 private int y; // y part of coordinate pair 7 8 // no-argument constructor 9 public Point() 10 { 11 // implicit call to Object constructor occurs here 12 System.out.println( "Point no-argument constructor: " + this ); 13 } // constructor 16 public Point( int xvalue, int yvalue ) 17 { 18 // implicit call to Object constructor occurs here 19 x = xvalue; // no need for validation 20 y = yvalue; // no need for validation System.out.println( "Point constructor: " + this ); 23 } // finalizer 26 protected void finalize() 27 { 28 System.out.println( "Point finalizer: " + this ); 29 } 30 Outline Point.java Lines 12, 22 and 28 Constructor and finalizer output messages to demonstrate method call order. Constructor and finalizer output messages to demonstrate method call order // set x in coordinate pair 32 public void setx( int xvalue ) 33 { 34 x = xvalue; // no need for validation 35 } // return x from coordinate pair 38 public int getx() 39 { 40 return x; 41 } // set y in coordinate pair 44 public void sety( int yvalue ) 45 { 46 y = yvalue; // no need for validation 47 } // return y from coordinate pair 50 public int gety() 51 { 52 return y; 53 } // return String representation of Point4 object 56 public String tostring() 57 { 58 return "[" + getx() + ", " + gety() + "]"; 59 } } // end class Point Outline Point.java 77

289 1 // Fig. 9.18: Circle.java 2 // Circle5 class declaration. 3 4 public class Circle extends Point { 5 6 private double radius; // Circle's radius 7 8 // no-argument constructor 9 public Circle() 10 { 11 // implicit call to Point constructor occurs here 12 System.out.println( "Circle no-argument constructor: " + this ); 13 } // constructor 16 public Circle( int xvalue, int yvalue, double radiusvalue ) 17 { 18 super( xvalue, yvalue ); // call Point constructor 19 setradius( radiusvalue ); System.out.println( "Circle constructor: " + this ); 22 } // finalizer 25 protected void finalize() 26 { 27 System.out.println( "Circle finalizer: " + this ); super.finalize(); // call superclass finalize method 30 } 31 Outline Circle.java Lines 12, 21 and 29 Constructor and finalizer output messages to demonstrate method Constructor and finalizer call order. output messages to demonstrate method call order // set radius 33 public void setradius( double radiusvalue ) 34 { 35 radius = ( radiusvalue < 0.0? 0.0 : radiusvalue ); 36 } // return radius 39 public double getradius() 40 { 41 return radius; 42 } // calculate and return diameter 45 public double getdiameter() 46 { 47 return 2 * getradius(); 48 } // calculate and return circumference 51 public double getcircumference() 52 { 53 return Math.PI * getdiameter(); 54 } Outline Circle.java 79

290 55 56 // calculate and return area 57 public double getarea() 58 { 59 return Math.PI * getradius() * getradius(); 60 } // return String representation of Circle5 object 63 public String tostring() 64 { 65 return "Center = " + super.tostring() + "; Radius = " + getradius(); 66 } } // end class Circle Outline Circle.java 80 1 // Fig. 9.19: ConstructorFinalizerTest.java 2 // Display order in which superclass and subclass 3 // constructors and finalizers are called. 4 5 public class ConstructorFinalizerTest { 6 Outline 81 ConstructorFina lizertest.java 7 public static void main( String args[] ) Line 12 8 { Point object goes in and out Point object goes in 9 Point point; of scope immediately. and out of scope 10 Circle circle1, circle2; 11 immediately. Instantiate two Circle 12 point = new Point( 11, 22 ); objects to demonstrate Lines 15 order 13 and System.out.println(); of subclass and superclass Instantiate two 15 circle1 = new Circle( 72, 29, 4.5 ); constructor/finalizer Circle method objects to 16 calls. demonstrate order of 17 System.out.println(); subclass and 18 circle2 = new Circle( 5, 7, ); superclass point = null; // mark for garbage collection constructor/finalizer 21 circle1 = null; // mark for garbage collection method calls. 22 circle2 = null; // mark for garbage collection System.out.println(); 25

291 26 System.gc(); // call the garbage collector } // end main } // end class ConstructorFinalizerTest Point constructor: [11, 22] Point constructor: Center = [72, 29]; Radius = 0.0 Circle constructor: Center = [72, 29]; Radius = 4.5 Outline 82 ConstructorFina lizertest.java Subclass Circle constructor body executes after superclass Point4 s constructor finishes execution. Point constructor: Center = [5, 7]; Radius = 0.0 Circle constructor: Center = [5, 7]; Radius = Point finalizer: [11, 22] Circle finalizer: Center = [72, 29]; Radius = 4.5 Point finalizer: Center = [72, 29]; Radius = 4.5 Circle finalizer: Center = [5, 7]; Radius = Point finalizer: Center = [5, 7]; Radius = Finalizer for Circle object called in reverse order of constructors. 84 Summary Inheritance allows the definition of classes as extensions of other classes. Inheritance avoids code duplication allows code reuse simplifies the code simplifies maintenance and extending

292 Part 12 Object Oriented Programming: Polymorphism polymorphism abstract versus concrete classes interfaces inner classes foils from: Prentice Hall, Inc. and S. Benkner (University of Vienna) Polymorphism: Motivation Shape Shape shape; Cube cube = new Cube(...); Circle circle = new Circle(); shape = cube;... shape.getname()... TwoDimensionalShape ThreeDimensionalShape shape = circle;... shape.getname()... Circle Square Triangle Sphere Cube Tetrahedron Assumption: all classes have method getname(); superclass variable can be assigned reference to subclass object. superclass variable can invoke getname method of subclass objects execution time environment polymorphically chooses correct subclass version of the method based on the type of the reference stored in the superclass variable.

293 Introduction: Polymorphism (1) A variable may reference objects of different classes. Objects of a subclass A can be assigned to objects of a superclass (assignment compatible) or to objects of class A. A superclass object is not a subclass object. Person p; Student s;... p = s; s = p; // p may refer to objects of class Person or // Student. // legal; every student is a Person // illegal; not every person is a student Introduction: Polymorphism (2) An object of a derived class B has the types of all superclasses of B. e.g.: s has type Student and type Person Student s = new Student(); boolean test1 = s instanceof Student; boolean test2 = s instanceof Person; // yields true // yields true

294 Assignment Compatibility Variables with type B can be assigned to variables of type B or type A where A is a superclass of B. class Person {... } class Student extends Person {... } class Kurs {... void register(person p) {... } }... Person p = new Person(); Student s = new Student(); s = p; p = s; Kurs kurs = new Kurs(); kurs.register(s); // Error! (incompatible) // compatible // compatible Inheritance and Cast Operator (1) If a variable a of type A references an object of a subclass B, then a can be assigned to b of type B by using an explicit type cast (downcasting). class A {... } class B extends A {... } A a; B b = new B (); a = b; b = (B) a; // cast type of a to B

295 Inheritance and Cast Operator (2) Vehicle f; Car a; a = new Car(); f = a; a = (Car) f; // Car is a subclass of Vehicle // f now becomes a car // correct because f is a car Vehicle f; Car a; Bike b; // Bike is a subclass of Vehicle a = new Car(); f = a; // f now becomes a car b = (Bike) a; // error detected during compilation // no subclass-superclass relation between a and b b = (Bike) f; // error detected during runtime // f is not a bike at this point 1 // Fig. 10.1: HierarchyRelationshipTest1.java 2 // Assigning superclass and subclass references to superclass- and 3 // subclass-type variables. 4 import javax.swing.joptionpane; 5 6 public class HierarchyRelationshipTest1 { 7 8 public static void main( String[] args ) 9 { HierarchyRelation shiptest1.java Line 11 Assign superclass reference to superclasstype variable 10 // assign superclass reference to superclass-type variable Assign superclass reference 11 Point3 point = new Point3( 30, 50 ); to superclass-type variable // assign subclass reference to subclass-type variable Line 14 Assign subclass reference 14 Circle4 circle = new Circle4( 120, 89, 2.7 ); Assign subclass to reference subclass-type variable 15 to subclass-type variable 16 // invoke tostring on superclass object using superclass variable 17 String output = "Call Point3's tostring with superclass" + 18 " reference to superclass object: \n" + point.tostring(); // invoke tostring on subclass object using subclass variable 21 output += "\n\ncall Circle4's tostring with subclass" + 22 " reference to subclass object: \n" + circle.tostring(); 23 Invoke Line tostring 17 on superclass Invoke object tostring using on superclass superclass variable object using superclass variable Invoke tostring on subclass Line object 22 using subclass Invoke variable tostring on subclass object using subclass variable

296 Assign subclass reference to 24 // invoke tostring on subclass object using superclass variable 25 Point3 pointref = circle; superclass-type variable 26 output += "\n\ncall Circle4's tostring with superclass" + 27 " reference to subclass object: \n" + pointref.tostring(); JOptionPane.showMessageDialog( null, output ); // display output System.exit( 0 ); } // end main } // end class HierarchyRelationshipTest1 Invoke tostring on subclass HierarchyRelati object using superclass onshiptest1.jav variable a Line 25 Assign subclass reference to superclass-type variable. Line 27 Invoke tostring on subclass object using superclass variable. Using Superclass References with Subclass-Type Variables Previous example Assigned subclass reference to superclass-type variable Circle is a Point Assign superclass reference to subclass-type variable Compiler error No is a relationship Point is not a Circle Circle has data/methods that Point does not setradius (declared in Circle) not declared in Point Cast superclass references to subclass references Called downcasting Invoke subclass functionality Point Circle

297 1 // Fig. 10.2: HierarchyRelationshipTest2.java 2 // Attempt to assign a superclass reference to a subclass-type variable. 3 4 public class HierarchyRelationshipTest2 { 5 6 public static void main( String[] args ) 7 { 8 Point3 point = new Point3( 30, 50 ); 9 Circle4 circle; // subclass-type variable // assign superclass reference to subclass-type variable 12 circle = point; // Error: a Point3 is not a Circle4 13 } } // end class HierarchyRelationshipTest2 Assigning superclass reference to subclass-type variable causes compiler error HierarchyRelati onshiptest2.jav a Line 12 Assigning superclass reference to subclasstype variable causes compiler error. HierarchyRelationshipTest2.java:12: incompatible types found : Point3 required: Circle4 circle = point; // Error: a Point3 is not a Circle4 ^ 1 error Subclass Method Calls via Superclass-Type variables Call a subclass method with superclass reference Compiler error Subclass methods are not superclass methods Works if superclass contains definition of the same method as in subclass

298 1 // Fig. 10.3: HierarchyRelationshipTest3.java 2 // Attempting to invoke subclass-only member methods through 3 // a superclass reference. 4 5 public class HierarchyRelationshipTest3 { 6 7 public static void main( String[] args ) 8 { 9 Point3 point; 10 Circle4 circle = new Circle4( 120, 89, 2.7 ); point = circle; // aim superclass reference at subclass object // invoke superclass (Point3) methods on subclass 15 // (Circle4) object through superclass reference 16 int x = point.getx(); // invoke getx of class Point3 17 int y = point.gety(); // invoke gety of class Point3 18 point.setx( 10 ); // invoke setx of class Point3 19 point.sety( 20 ); // invoke sety of class Point3 20 point.tostring(); // invoke tostring of class Circle4 21 HierarchyRelati onshiptest3.jav a 22 // attempt to invoke subclass-only (Circle4) methods on 23 // subclass object through superclass (Point3) reference 24 double radius = point.getradius(); 25 point.setradius( ); 26 double diameter = point.getdiameter(); 27 double circumference = point.getcircumference(); 28 double area = point.getarea(); } // end main } // end class HierarchyRelationshipTest3 Attempt to invoke subclassonly (Circle4) methods on subclass object through superclass (Point3) reference. HierarchyRelati onshiptest3.jav a Lines Attempt to invoke subclass-only (Circle4) methods on subclass object through superclass (Point3) reference. A variable can be used to invoke only methods that are members of that variable s type. This can be checked by the compiler at compilation time.

299 HierarchyRelationshipTest3.java:24: cannot resolve symbol symbol : method getradius () location: class Point3 double radius = point.getradius(); ^ HierarchyRelationshipTest3.java:25: cannot resolve symbol symbol : method setradius (double) location: class Point3 point.setradius( ); ^ HierarchyRelationshipTest3.java:26: cannot resolve symbol symbol : method getdiameter () location: class Point3 double diameter = point.getdiameter(); ^ HierarchyRelationshipTest3.java:27: cannot resolve symbol symbol : method getcircumference () location: class Point3 double circumference = point.getcircumference(); ^ HierarchyRelationshipTest3.java:28: cannot resolve symbol symbol : method getarea () location: class Point3 double area = point.getarea(); ^ 5 errors HierarchyRelati onshiptest3.jav a Abstract Classes Abstract classes are used for the representation of abstract concepts (vehicle, planet, etc.) in Java. are used for closely related classes (vehicle, car, truck, etc.) are superclasses (called abstract superclasses) in inheritance hierarchies cannot be instantiated Incomplete (only partially implemented) subclasses fill in "missing pieces Concrete classes Can be instantiated Implement every method they declare Provide specifics public abstract class Vehicle {... }

300 Abstract Methods declared with the keyword abstract defines only the interface (types and names of parameters and return value) no implementation (body) abstract class Food { // abstract class abstract double nutrition (double amount);// abstract method } Abstract Classes and Methods (1) Every class with at least one abstract method must be declared to be abstract (abstract class... ) Abstract classes may contain besides abstract methods arbitrary fields, non-abstract methods and constructors. abstract class Shape { static int nrofshapes; Point origin; Shape() {nrofshapes++;} abstract double area(); } // abstract Class // class variable // instance variable // constructor // abstract method

301 Abstract Classes and Methods (2) A subclass B of an abstract class A can be instantiated if B implements all abstract methods of A. abstract class Shape { // abstract class static int nrofshapes; // class variable Point origin; // instance variable Shape() {nrofshapes++; } // constructor abstract double area(); // abstract method } class Circle extends Shape { // subclass of Shape double r; double area() { return r*r*3,14;} }... Circle c = new Circle (); Shape s = c; System.out.println(s.area()); Abstract Classes and Methods (3) If a subclass B does not implement all abstract methods of an abstract class A, then B is an abstract class as well. abstract class Shape // abstract class static int nrofshapes; // class variable Point origin; // instance variable Shape() {nrofshapes++; } // constructor abstract double area(); // abstract method } // abstract subclass of Shape abstract class ColoredShape extends Shape { Color c; void setcolor(color newcol) { c = newcol; } }

302 Case Study: Inheriting Interface and Implementation Make abstract superclass Shape Abstract method getname Default implementation does not make sense Methods may be overridden getarea, getvolume Default implementations return 0.0 If not overridden, uses superclass default implementation Subclasses Point, Circle, Cylinder 10.5 Case Study: Inheriting Interface and Implementation Shape Point Circle Cylinder Fig Shape hierarchy class diagram.

303 Case Study: Inheriting Interface and Implementation getarea getvolume getname print Shape abstract default Object implement. Point "Point" [x,y] Circle pr "Circle" center=[x,y]; radius=r Cylinder 2pr 2 +2prh pr 2 h "Cylinder" center=[x,y]; radius=r; height=h Polimorphic interface for the Shape hierarchy classes. 1 // Fig. 10.6: Shape.java 2 // Shape abstract-superclass declaration. 3 4 public abstract class Shape extends Object { 5 6 // return area of shape; 0.0 by default 7 public double getarea() Keyword abstract 8 { declares class Shape as 9 return 0.0; 10 } abstract class // return volume of shape; 0.0 by default 13 public double getvolume() 14 { 15 return 0.0; 16 } // abstract method, overridden by subclasses 19 public abstract String getname(); } // end abstract class Shape Shape.java Line 4 Keyword abstract declares class Shape as abstract class Line 19 Keyword abstract declares method getname as abstract method Keyword abstract declares method getname as abstract method

304 1 // Fig. 10.7: Point.java 2 // Point class declaration inherits from Shape. 3 4 public class Point extends Shape { 5 private int x; // x part of coordinate pair 6 private int y; // y part of coordinate pair 7 8 // no-argument constructor; x and y default to 0 9 public Point() 10 { 11 // implicit call to Object constructor occurs here 12 } // constructor 15 public Point( int xvalue, int yvalue ) 16 { 17 // implicit call to Object constructor occurs here 18 x = xvalue; // no need for validation 19 y = yvalue; // no need for validation 20 } // set x in coordinate pair 23 public void setx( int xvalue ) 24 { 25 x = xvalue; // no need for validation 26 } 27 Point.java 28 // return x from coordinate pair 29 public int getx() 30 { 31 return x; 32 } // set y in coordinate pair 35 public void sety( int yvalue ) 36 { 37 y = yvalue; // no need for validation 38 } // return y from coordinate pair 41 public int gety() 42 { 43 return y; 44 } 45 Override abstract method getname. 46 // override abstract method getname to return "Point" 47 public String getname() 48 { 49 return "Point"; 50 } // override tostring to return String representation of Point 53 public String tostring() 54 { 55 return "[" + getx() + ", " + gety() + "]"; 56 } } // end class Point Point.java Lines Override abstract method getname.

305 1 // Fig. 10.8: Circle.java 2 // Circle class inherits from Point. 3 4 public class Circle extends Point { 5 private double radius; // Circle's radius 6 7 // no-argument constructor; radius defaults to public Circle() 9 { 10 // implicit call to Point constructor occurs here 11 } // constructor 14 public Circle( int x, int y, double radiusvalue ) 15 { 16 super( x, y ); // call Point constructor 17 setradius( radiusvalue ); 18 } // set radius 21 public void setradius( double radiusvalue ) 22 { 23 radius = ( radiusvalue < 0.0? 0.0 : radiusvalue ); 24 } 25 Circle.java 26 // return radius 27 public double getradius() 28 { 29 return radius; 30 } // calculate and return diameter 33 public double getdiameter() 34 { 35 return 2 * getradius(); 36 } // calculate and return circumference 39 public double getcircumference() 40 { 41 return Math.PI * getdiameter(); 42 } 43 Override method getarea to return circle area 44 // override method getarea to return Circle area 45 public double getarea() 46 { 47 return Math.PI * getradius() * getradius(); 48 } 49 Circle.java Lines Override method getarea to return circle area.

306 50 // override abstract method getname to return "Circle" 51 public String getname() 52 { 53 return "Circle"; 54 } 55 Override abstract method getname 56 // override tostring to return String representation of Circle 57 public String tostring() 58 { 59 return "Center = " + super.tostring() + "; Radius = " + getradius(); 60 } } // end class Circle Circle.java Lines Override abstract method getname. 1 // Fig. 10.9: Cylinder.java 2 // Cylinder class inherits from Circle. 3 4 public class Cylinder extends Circle { 5 private double height; // Cylinder's height 6 7 // no-argument constructor; height defaults to public Cylinder() 9 { 10 // implicit call to Circle constructor occurs here 11 } // constructor 14 public Cylinder( int x, int y, double radius, double heightvalue ) 15 { 16 super( x, y, radius ); // call Circle constructor 17 setheight( heightvalue ); 18 } // set Cylinder's height 21 public void setheight( double heightvalue ) 22 { 23 height = ( heightvalue < 0.0? 0.0 : heightvalue ); 24 } 25 Cylinder.java

307 26 // get Cylinder's height 27 public double getheight() 28 { 29 return height; 30 } public String getname() 46 { 47 return "Cylinder"; 48 } Override method getarea to return cylinder area 32 // override method getarea to return Cylinder Override area method 33 public double getarea() getvolume to 34 { return cylinder 35 return 2 * super.getarea() + getcircumference() * getheight(); volume 36 } // override method getvolume to return Cylinder volume 39 public double getvolume() 40 { 41 return super.getarea() * getheight(); 42 } // override abstract method getname to return "Cylinder" Override abstract method getname Cylinder.java Lines Override method getarea to return cylinder area Lines Override method getvolume to return cylinder volume Lines Override abstract method getname // override tostring to return String representation of Cylinder 51 public String tostring() 52 { 53 return super.tostring() + "; Height = " + getheight(); 54 } } // end class Cylinder Cylinder.java

308 1 // Fig : AbstractInheritanceTest.java 2 // Driver for shape, point, circle, cylinder hierarchy. 3 import java.text.decimalformat; 4 import javax.swing.joptionpane; 5 6 public class AbstractInheritanceTest { 7 8 public static void main( String args[] ) 9 { 10 // set floating-point number format 11 DecimalFormat twodigits = new DecimalFormat( "0.00" ); // create Point, Circle and Cylinder objects 14 Point point = new Point( 7, 11 ); 15 Circle circle = new Circle( 22, 8, 3.5 ); 16 Cylinder cylinder = new Cylinder( 20, 30, 3.3, ); // obtain name and string representation of each object 19 String output = point.getname() + ": " + point + "\n" + 20 circle.getname() + ": " + circle + "\n" + 21 cylinder.getname() + ": " + cylinder + "\n"; Shape arrayofshapes[] = new Shape[ 3 ]; // create Shape array 24 AbstractInherit ancetest.java 25 // aim arrayofshapes[ 0 ] at subclass Point object 26 arrayofshapes[ 0 ] = point; // aim arrayofshapes[ 1 ] at subclass Circle object 29 arrayofshapes[ 1 ] = circle; // aim arrayofshapes[ 2 ] at subclass Cylinder object 32 arrayofshapes[ 2 ] = cylinder; // loop through arrayofshapes to get name, string 35 // representation, area and volume of every Shape in array 36 for ( int i = 0; i < arrayofshapes.length; i++ ) { 37 output += "\n\n" + arrayofshapes[ i ].getname() + ": " + 38 arrayofshapes[ i ].tostring() + "\narea = " + 39 twodigits.format( arrayofshapes[ i ].getarea() ) + 40 "\nvolume = " + 41 twodigits.format( arrayofshapes[ i ].getvolume() ); 42 } JOptionPane.showMessageDialog( null, output ); // display output System.exit( 0 ); } // end main } // end class AbstractInheritanceTest Create an array of AbstractInherit generic Shape Loop through objects ancetest.java arrayofshapes to get name, string representation, Lines area and volume of Create every an array of shape in array generic Shape objects Lines Loop through arrayofshapes to get name, string representation, area and volume of every shape in array late binding or dynamic binding: All method calls to getname, tostring, getarea and getvolume are resolved at execution time, based on the type of the object to which element arrayofshapes[i] currently refers.

309 final methods final Methods and Classes in superclasses cannot be overridden in subclasses private methods are implicitly final static methods are implicitly final only non-static methods can be overridden in subclasses. final classes Cannot be superclasses Methods in final classes are implicitly final e.g., class String final classes typically for security reasons

310 Case Study: Payroll System Using Polymorphism Create a payroll program Use abstract methods and polymorphism Problem statement 4 types of employees, paid weekly Salaried (fixed salary, no matter the hours) Hourly (overtime [>40 hours] pays time and a half) Commission (paid percentage of sales) Base-plus-commission (base salary + percentage of sales) Boss wants to raise pay by 10% Case Study: Payroll System Using Polymorphism Superclass Employee Abstract method earnings (returns pay) abstract because need to know employee type Cannot calculate for generic employee Other classes extend Employee Employee SalariedEmployee CommissionEmployee HourlyEmployee BasePlusCommissionEmployee

311 1 // Fig : Employee.java 2 // Employee abstract superclass. 3 Declares class Employee 4 public abstract class Employee { as abstract class. 5 private String firstname; 6 private String lastname; 7 private String socialsecuritynumber; 8 9 // constructor 10 public Employee( String first, String last, String ssn ) 11 { 12 firstname = first; 13 lastname = last; 14 socialsecuritynumber = ssn; 15 } // set first name 18 public void setfirstname( String first ) 19 { 20 firstname = first; 21 } 22 Employee.java Line 4 Declares class Employee as abstract class. 23 // return first name 24 public String getfirstname() 25 { 26 return firstname; 27 } // set last name 30 public void setlastname( String last ) 31 { 32 lastname = last; 33 } // return last name 36 public String getlastname() 37 { 38 return lastname; 39 } // set social security number 42 public void setsocialsecuritynumber( String number ) 43 { 44 socialsecuritynumber = number; // should validate 45 } 46 Employee.java

312 47 // return social security number 48 public String getsocialsecuritynumber() 49 { 50 return socialsecuritynumber; 51 } // return String representation of Employee object 54 public String tostring() 55 { 56 return getfirstname() + " " + getlastname() + 57 "\nsocial security number: " + getsocialsecuritynumber(); 58 } // abstract method overridden by subclasses 61 public abstract double earnings(); } // end abstract class Employee Abstract method overridden by subclasses Employee.java Line 61 Abstract method overridden by subclasses. 1 // Fig : SalariedEmployee.java 2 // SalariedEmployee class extends Employee. 3 4 public class SalariedEmployee extends Employee { 5 private double weeklysalary; 6 7 // constructor Use superclass constructor for 8 public SalariedEmployee( String first, String last, basic fields. 9 String socialsecuritynumber, double salary ) 10 { 11 super( first, last, socialsecuritynumber ); 12 setweeklysalary( salary ); 13 } // set salaried employee's salary 16 public void setweeklysalary( double salary ) 17 { 18 weeklysalary = salary < 0.0? 0.0 : salary; 19 } // return salaried employee's salary 22 public double getweeklysalary() 23 { 24 return weeklysalary; 25 } 26 SalariedEmploye e.java Line 11 Use superclass constructor for basic fields.

313 27 // calculate salaried employee's pay; 28 // override abstract method earnings in Employee 29 public double earnings() 30 { 31 return getweeklysalary(); 32 } Must implement abstract 33 method earnings. 34 // return String representation of SalariedEmployee object 35 public String tostring() 36 { 37 return "\nsalaried employee: " + super.tostring(); 38 } } // end class SalariedEmployee SalariedEmploye e.java Lines Must implement abstract method earnings. 1 // Fig : HourlyEmployee.java 2 // HourlyEmployee class extends Employee. 3 4 public class HourlyEmployee extends Employee { 5 private double wage; // wage per hour 6 private double hours; // hours worked for week 7 8 // constructor 9 public HourlyEmployee( String first, String last, 10 String socialsecuritynumber, double hourlywage, double hoursworked ) 11 { 12 super( first, last, socialsecuritynumber ); 13 setwage( hourlywage ); 14 sethours( hoursworked ); 15 } // set hourly employee's wage 18 public void setwage( double wageamount ) 19 { 20 wage = wageamount < 0.0? 0.0 : wageamount; 21 } // return wage 24 public double getwage() 25 { 26 return wage; 27 } 28 HourlyEmployee. java

314 29 // set hourly employee's hours worked 30 public void sethours( double hoursworked ) 31 { 32 hours = ( hoursworked >= 0.0 && hoursworked <= )? 33 hoursworked : 0.0; 34 } // return hours worked 37 public double gethours() 38 { 39 return hours; 40 } // calculate hourly employee's pay; 43 // override abstract method earnings in Employee 44 public double earnings() Must implement abstract 45 { method earnings. 46 if ( hours <= 40 ) // no overtime 47 return wage * hours; 48 else 49 return 40 * wage + ( hours - 40 ) * wage * 1.5; 50 } // return String representation of HourlyEmployee object 53 public String tostring() 54 { 55 return "\nhourly employee: " + super.tostring(); 56 } } // end class HourlyEmployee HourlyEmployee. java Lines Must implement abstract method earnings. 1 // Fig : CommissionEmployee.java 2 // CommissionEmployee class extends Employee. 3 4 public class CommissionEmployee extends Employee { 5 private double grosssales; // gross weekly sales 6 private double commissionrate; // commission percentage 7 8 // constructor 9 public CommissionEmployee( String first, String last, 10 String socialsecuritynumber, 11 double grossweeklysales, double percent ) 12 { 13 super( first, last, socialsecuritynumber ); 14 setgrosssales( grossweeklysales ); 15 setcommissionrate( percent ); 16 } // set commission employee's rate 19 public void setcommissionrate( double rate ) 20 { 21 commissionrate = ( rate > 0.0 && rate < 1.0 )? rate : 0.0; 22 } // return commission employee's rate 25 public double getcommissionrate() 26 { 27 return commissionrate; 28 } CommissionEmplo yee.java

315 29 30 // set commission employee's weekly base salary 31 public void setgrosssales( double sales ) 32 { 33 grosssales = sales < 0.0? 0.0 : sales; 34 } // return commission employee's gross sales amount 37 public double getgrosssales() 38 { 39 return grosssales; 40 } // calculate commission employee's Must pay; implement abstract 43 // override abstract method earnings method in Employee earnings. 44 public double earnings() 45 { 46 return getcommissionrate() * getgrosssales(); 47 } // return String representation of CommissionEmployee object 50 public String tostring() 51 { 52 return "\ncommission employee: " + super.tostring(); 53 } } // end class CommissionEmployee CommissionEmplo yee.java Lines Must implement abstract method earnings. 1 // Fig : BasePlusCommissionEmployee.java 2 // BasePlusCommissionEmployee class extends CommissionEmployee. 3 4 public class BasePlusCommissionEmployee extends CommissionEmployee { 5 private double basesalary; // base salary per week 6 7 // constructor 8 public BasePlusCommissionEmployee( String first, String last, 9 String socialsecuritynumber, double grosssalesamount, 10 double rate, double basesalaryamount ) 11 { 12 super( first, last, socialsecuritynumber, grosssalesamount, rate ); 13 setbasesalary( basesalaryamount ); 14 } // set base-salaried commission employee's base salary 17 public void setbasesalary( double salary ) 18 { 19 basesalary = salary < 0.0? 0.0 : salary; 20 } // return base-salaried commission employee's base salary 23 public double getbasesalary() 24 { 25 return basesalary; 26 } 27 BasePlusCommiss ionemployee.jav a

316 28 // calculate base-salaried commission employee's earnings; 29 // override method earnings in CommissionEmployee 30 public double earnings() Override method earnings 31 { 32 return getbasesalary() + super.earnings(); in CommissionEmployee 33 } // return String representation of BasePlusCommissionEmployee 36 public String tostring() 37 { 38 return "\nbase-salaried commission employee: " + 39 super.getfirstname() + " " + super.getlastname() + 40 "\nsocial security number: " + super.getsocialsecuritynumber(); 41 } } // end class BasePlusCommissionEmployee BasePlusCommiss ionemployee.jav a Lines Override method earnings in CommissionEmplo yee 1 // Fig : PayrollSystemTest.java 2 // Employee hierarchy test program. 3 import java.text.decimalformat; 4 import javax.swing.joptionpane; 5 6 public class PayrollSystemTest { 7 8 public static void main( String[] args ) 9 { 10 DecimalFormat twodigits = new DecimalFormat( "0.00" ); // create Employee array 13 Employee employees[] = new Employee[ 4 ]; // initialize array with Employees 16 employees[ 0 ] = new SalariedEmployee( "John", "Smith", 17 " ", ); 18 employees[ 1 ] = new CommissionEmployee( "Sue", "Jones", 19 " ", 10000,.06 ); 20 employees[ 2 ] = new BasePlusCommissionEmployee( "Bob", "Lewis", 21 " ", 5000,.04, 300 ); 22 employees[ 3 ] = new HourlyEmployee( "Karen", "Price", 23 " ", 16.75, 40 ); String output = ""; 26 PayrollSystemTe st.java

317 27 // generically process each element in array employees 28 for ( int i = 0; i < employees.length; i++ ) { 29 output += employees[ i ].tostring(); // determine whether element is a BasePlusCommissionEmployee PayrollSystemTe st.java 32 if ( employees[ i ] instanceof BasePlusCommissionEmployee ) { Determine whether element is a 33 BasePlusCommissionEmpl Line // downcast Employee reference to Determine whether 35 // BasePlusCommissionEmployee reference oyee element is a 36 BasePlusCommissionEmployee currentemployee = 37 ( BasePlusCommissionEmployee ) employees[ i ]; BasePlusCommiss 38 Downcast Employee reference to ionemployee 39 double oldbasesalary = currentemployee.getbasesalary(); BasePlusCommissionEmployee output += "\nold base salary: reference $" + oldbasesalary; currentemployee.setbasesalary( 1.10 * oldbasesalary ); Line 37 Downcast Employee reference to 43 output += "\nnew base salary with 10% increase is: $" + BasePlusCommiss 44 currentemployee.getbasesalary(); ionemployee 45 reference 46 } // end if output += "\nearned $" + employees[ i ].earnings() + "\n"; } // end for // get type name of each object in employees array 53 for ( int j = 0; j < employees.length; j++ ) 54 output += "\nemployee " + j + " is a " + 55 employees[ j ].getclass().getname(); JOptionPane.showMessageDialog( null, output ); // display output 58 System.exit( 0 ); } // end main } // end class PayrollSystemTest Get type name of each PayrollSystemTe object in employeesst.java array Lines Get type name of each object in employees array

318 Downcast Operation Type of object must have an is-a relationship with type specified in the cast operator otherwise ClassCastException occurs Object can be cast only to its own type or to the type of one of its superclasses. Interfaces (1) are used to decouple method interfaces from their implementation. Interfaces are used for functionality not dependent on the class consist only of (implicit) abstract methods (= without implementation) and constants (implicit final static). no fields and no contructors public interface Sammlerstueck { public double sammlerwert();... }

319 Interfaces (2) A class may implement one or several interfaces. If a class implements an interface, then all of the interface s methods must be implemented otherwise the class must be declared abstract. public class BriefMarke implements Sammlerstueck {... public double sammlerwert() { //Implementierung... } } public class OldTimer extends Auto implements Sammlerstueck {... public double sammlerwert() { //Implementierung... } } Interfaces and Inheritance (1) an example

320 Interfaces and Inheritance (2) can be extended similar as classes. in contrast to classes, an interface may extend one or several other interfaces. interface A { void a(); } interface B { void b(); } interface C extends A, B { } // C inherits a() and b() Interfaces: Assignment Compatibility An object of a class A that implements an interface, can be assigned to a variable of the type of that interface. An interface cannot be instantiated. BriefMarke blauemauritius = new Briefmarke(); OldTimer chevy57 = new OldTimer(); Sammlerstueck[] sammlung;... sammlung[i] = blaue Mauritius;... Sammlung[j] = chevy57;... for (i=0; i<sammlung.length; i++) gesamtwert += sammlung[i].sammlerwert();

321 Interfaces and Inheritance The implementation of an interface is an attribute which is inherited by subclasses. If a class A implements an interface I, then the clause implements I at a subclass of A is optional. Based on a class declaration one cannot always determine, whether a specific interface is implemented by that class. Interfaces: Advantages Interface of a class is separated from implementation -> Software development can be handled more flexible. A variable of a type of a certain interface can be assigned objects of classes that implement this interface. Different implementation variations can be dynamically selected or modified.

322 Interfaces: Importance Interfaces play an important role in the Java API, e.g.: Eventhandling: EventListener, ActionListener, KeyListener, MouseListener, MouseMotionListener,... Collections: Collection, Iterator, Enumeration,... Objektserialisierung: Serializable Multithreading: Runnable Case Study: Creating and Using Interfaces 1 // Fig : Shape.java 2 // Shape interface declaration. Classes that implement Shape 3 4 public interface Shape { must implement these methods 5 public double getarea(); // calculate area 6 public double getvolume(); // calculate volume 7 public String getname(); // return shape name 8 9 } // end interface Shape Shape.java Lines 5-7 Classes that implement Shape must implement these methods

323 1 // Fig : Point.java 2 // Point class declaration implements interface Shape. 3 4 public class Point extends Object implements Shape { 5 private int x; // x part of coordinate pair 6 private int y; // y part of coordinate pair 7 8 // no-argument constructor; x and y default to 0 9 public Point() 10 { 11 // implicit call to Object constructor occurs here 12 } // constructor 15 public Point( int xvalue, int yvalue ) 16 { 17 // implicit call to Object constructor occurs here 18 x = xvalue; // no need for validation 19 y = yvalue; // no need for validation 20 } // set x in coordinate pair 23 public void setx( int xvalue ) 24 { 25 x = xvalue; // no need for validation 26 } 27 Point implements interface Shape Point.java Line 4 Point implements interface Shape 28 // return x from coordinate pair 29 public int getx() 30 { 31 return x; 32 } // set y in coordinate pair 35 public void sety( int yvalue ) 36 { 37 y = yvalue; // no need for validation 38 } // return y from coordinate pair 41 public int gety() 42 { 43 return y; 44 } 45 Point.java

324 46 // declare abstract method getarea 47 public double getarea() 48 { 49 return 0.0; 50 } // declare abstract method getvolume 53 public double getvolume() Implement methods specified 54 { by interface Shape 55 return 0.0; 56 } // override abstract method getname to return "Point" 59 public String getname() 60 { 61 return "Point"; 62 } // override tostring to return String representation of Point 65 public String tostring() 66 { 67 return "[" + getx() + ", " + gety() + "]"; 68 } } // end class Point Point.java Lines Implement methods specified by interface Shape 1 // Fig : InterfaceTest.java 2 // Test Point, Circle, Cylinder hierarchy with interface Shape. 3 import java.text.decimalformat; 4 import javax.swing.joptionpane; 5 6 public class InterfaceTest { 7 8 public static void main( String args[] ) 9 { 10 // set floating-point number format 11 DecimalFormat twodigits = new DecimalFormat( "0.00" ); // create Point, Circle and Cylinder objects 14 Point point = new Point( 7, 11 ); 15 Circle circle = new Circle( 22, 8, 3.5 ); 16 Cylinder cylinder = new Cylinder( 20, 30, 3.3, ); // obtain name and string representation of each object 19 String output = point.getname() + ": " + point + "\n" + 20 circle.getname() + ": " + circle + "\n" Create + Shape array 21 cylinder.getname() + ": " + cylinder + "\n"; Shape arrayofshapes[] = new Shape[ 3 ]; // create Shape array 24 InterfaceTest.j ava Line 23 Create Shape array

325 25 // aim arrayofshapes[ 0 ] at subclass Point object 26 arrayofshapes[ 0 ] = point; // aim arrayofshapes[ 1 ] at subclass Circle object 29 arrayofshapes[ 1 ] = circle; // aim arrayofshapes[ 2 ] at subclass Cylinder object 32 arrayofshapes[ 2 ] = cylinder; // loop through arrayofshapes to get name, string 35 // representation, area and volume of every Shape in array 36 for ( int i = 0; i < arrayofshapes.length; i++ ) { 37 output += "\n\n" + arrayofshapes[ i ].getname() + ": " + 38 arrayofshapes[ i ].tostring() + "\narea = " + 39 twodigits.format( arrayofshapes[ i ].getarea() ) + 40 "\nvolume = " + 41 twodigits.format( arrayofshapes[ i ].getvolume() ); 42 } JOptionPane.showMessageDialog( null, output ); // display output System.exit( 0 ); } // end main } // end class InterfaceTest InterfaceTest.j ava Loop through arrayofshapes to get name, string representation, area Lines and volume of every shape in array Loop through arrayofshapes to get name, string representation, area and volume of every shape in array. InterfaceTest.j ava

326 Case Study: Creating and Using Interfaces (Cont.) Implementing Multiple Interface classes can implement as many interfaces as needed Provide common-separated list of interface names after keyword implements Declaring Constants with Interfaces public interface Constants { public static final int ONE = 1; public static final int TWO = 2; public static final int THREE = 3; } classes that implement interface Constants can use ONE, TWO, and THREE anywhere in the class declaration. Nested and Inner Classes Top-level classes Not declared inside a class or a method Nested classes Declared inside other classes Nested classes can be static. Inner classes are non-static nested classes Inner classes are frequently used for event handling or hiding implementation Inner classes: can directly access its outer class s members reference this inside an inner class refers to current inner-class object. refer to outer-class this by OuterClassName.this Inner classes can be declared private, protected, public or package access (default) Outer class is responsible for creating inner class objects Nested classes can be declared static

327 1 // Fig : Time.java 2 // Time class declaration with set and get methods. 3 import java.text.decimalformat; 4 5 public class Time { 6 private int hour; // private int minute; // private int second; // // one formatting object to share in tostring and touniversalstring 11 private static DecimalFormat twodigits = new DecimalFormat( "00" ); // Time constructor initializes each instance variable to zero; 14 // ensures that Time object starts in a consistent state 15 public Time() 16 { 17 this( 0, 0, 0 ); // invoke Time constructor with three arguments 18 } // Time constructor: hour supplied, minute and second defaulted to 0 21 public Time( int h ) 22 { 23 this( h, 0, 0 ); // invoke Time constructor with three arguments 24 } 25 Time.java 26 // Time constructor: hour and minute supplied, second defaulted to 0 27 public Time( int h, int m ) 28 { 29 this( h, m, 0 ); // invoke Time constructor with three arguments 30 } // Time constructor: hour, minute and second supplied 33 public Time( int h, int m, int s ) 34 { 35 settime( h, m, s ); 36 } // Time constructor: another Time3 object supplied 39 public Time( Time time ) 40 { 41 // invoke Time constructor with three arguments 42 this( time.gethour(), time.getminute(), time.getsecond() ); 43 } // Set Methods 46 // set a new time value using universal time; perform 47 // validity checks on data; set invalid values to zero 48 public void settime( int h, int m, int s ) 49 { 50 sethour( h ); // set the hour 51 setminute( m ); // set the minute 52 setsecond( s ); // set the second 53 } 54 Time.java

328 55 // validate and set hour 56 public void sethour( int h ) 57 { 58 hour = ( ( h >= 0 && h < 24 )? h : 0 ); 59 } // validate and set minute 62 public void setminute( int m ) 63 { 64 minute = ( ( m >= 0 && m < 60 )? m : 0 ); 65 } // validate and set second 68 public void setsecond( int s ) 69 { 70 second = ( ( s >= 0 && s < 60 )? s : 0 ); 71 } // Get Methods 74 // get hour value 75 public int gethour() 76 { 77 return hour; 78 } 79 Time.java 80 // get minute value 81 public int getminute() 82 { 83 return minute; 84 } // get second value 87 public int getsecond() 88 { 89 return second; 90 } // convert to String in universal-time format 93 public String touniversalstring() Override method 94 { 95 return twodigits.format( gethour() ) + ":" + 96 twodigits.format( getminute() ) + ":" + 97 twodigits.format( getsecond() ); 98 } // convert to String in standard-time format 101 public String tostring() 102 { 103 return ( ( gethour() == 12 gethour() == 0 )? : gethour() % 12 ) + ":" + twodigits.format( getminute() ) ":" + twodigits.format( getsecond() ) ( gethour() < 12? " AM" : " PM" ); 107 } } // end class Time java.lang.object.tostring Time.java Lines Override method java.lang.objec t.tostring

329 1 // Fig : TimeTestWindow.java 2 // Inner class declarations used to create JFrame event provides handlers. basic window 3 import java.awt.*; attributes and behaviors 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class TimeTestWindow extends JFrame { 8 private Time time; 9 private JLabel hourlabel, minutelabel, secondlabel; 10 private JTextField hourfield, minutefield, secondfield, displayfield; 11 private JButton exitbutton; // set up GUI 14 public TimeTestWindow() 15 { 16 // call JFrame constructor to set title bar string Instantiate Time object 17 super( "Inner Class Demonstration" ); time = new Time(); // create Time object // use inherited method getcontentpane to get window's content pane 22 Container container = getcontentpane(); 23 container.setlayout( new FlowLayout() ); // change layout // set up hourlabel and hourfield 26 hourlabel = new JLabel( "Set Hour" ); 27 hourfield = new JTextField( 10 ); 28 container.add( hourlabel ); 29 container.add( hourfield ); 30 TimeTestWindow. java Line 7 JFrame provides basic window attributes and behaviors has constructor Line 17 JFrame (unlike JApplet) has constructor JFrame (unlike JApplet) Line 19 Instantiate Time object 31 // set up minutelabel and minutefield 32 minutelabel = new JLabel( "Set Minute" ); 33 minutefield = new JTextField( 10 ); 34 container.add( minutelabel ); 35 container.add( minutefield ); // set up secondlabel and secondfield 38 secondlabel = new JLabel( "Set Second" ); 39 secondfield = new JTextField( 10 ); 40 container.add( secondlabel ); 41 container.add( secondfield ); // set up displayfield 44 displayfield = new JTextField( 30 ); 45 displayfield.seteditable( false ); 46 container.add( displayfield ); // set up exitbutton 49 exitbutton = new JButton( "Exit" ); 50 container.add( exitbutton ); // create an instance of inner class ActionEventHandler 53 ActionEventHandler handler = new ActionEventHandler(); 54 Instantiate object of innerclass that implements ActionListener TimeTestWindow. java Line 53 Instantiate object of inner-class that implements ActionListener.

330 55 // register event handlers; the object referenced by handler 56 // is the ActionListener, which contains method actionperformed 57 // that will be called to handle action events generated by 58 // hourfield, minutefield, secondfield and exitbutton 59 hourfield.addactionlistener( handler ); 60 minutefield.addactionlistener( handler ); 61 secondfield.addactionlistener( handler ); 62 exitbutton.addactionlistener( handler ); } // end constructor // display time in displayfield 67 public void displaytime() 68 { 69 displayfield.settext( "The time is: " + time ); 70 } // launch application: create, size and display TimeTestWindow; 73 // when main terminates, program continues execution because a 74 // window is displayed by the statements in main 75 public static void main( String args[] ) 76 { 77 TimeTestWindow window = new TimeTestWindow(); window.setsize( 400, 140 ); 80 window.setvisible( true ); } // end main TimeTestWindow. Register java ActionEventHandler with GUI components Lines Register ActionEventHand ler with GUI components. 84 // inner class declaration for handling JTextField and JButton events 85 private class ActionEventHandler implements ActionListener { // method to handle action events 88 public void actionperformed( ActionEvent event ) 89 { 90 // user pressed exitbutton When user presses JButton or Enter key, 91 if ( event.getsource() == exitbutton ) method actionperformed is invoked 92 System.exit( 0 ); // terminate the application // user pressed Enter key in hourfield 95 else if ( event.getsource() == hourfield ) { 96 time.sethour( Integer.parseInt( 97 event.getactioncommand() ) ); 98 hourfield.settext( "" ); 99 } // user pressed Enter key in minutefield 102 else if ( event.getsource() == minutefield ) { 103 time.setminute( Integer.parseInt( 104 event.getactioncommand() ) ); 105 minutefield.settext( "" ); 106 } 107 Declare inner class that implements ActionListener interface TimeTestWindow. java Line 85 Declare inner class Must implement method actionperformed of ActionListener Line 88 Must implement Determine action method depending on where event actionperformed originated Line 88 When user presses button or key, method actionperformed is invoked Lines Determine action depending on where event originated

331 108 // user pressed Enter key in secondfield 109 else if ( event.getsource() == secondfield ) { 110 time.setsecond( Integer.parseInt( 111 event.getactioncommand() ) ); 112 secondfield.settext( "" ); 113 } displaytime(); // call outer class's method } // end method actionperformed } // end inner class ActionEventHandler } // end class TimeTestWindow TimeTestWindow. java TimeTestWindow. java

332 Type-Wrapper Classes for Primitive Types Type-wrapper class Each primitive type has one Character, Byte, Intege, Boolean, Short, Long, Float, and Double. Enable to represent primitive as Object Primitive types can be processed polymorphically Every type wrapper class is declared as final and extends class Number. Methods of final classes are implicitly final (cannot be overwritten). Summary Inheriting from concrete classes (extends) means inheriting both implementation and type. Polymorphism allows to create programs to process objects of types that might not exist when the program is under development. Abstract classes can be declared for which no objects ever will be created. Interfaces allow a strict separation of implementation from a type. Abstract classes are a mixture of inheritance and interfaces which allow to inherit a type and partially also implementation. Inner classes is another mechanism for hiding implementation.

333 Part 13 Exception Handling Main concepts to be covered Defensive programming. Anticipating that things could go wrong. Exception handling and throwing. Error reporting.

334 Motivation (1) original simple control flow without considering potential errors doa(); dob(); doc(); Motivation (2) Extended source code with error handling disturbs original control flow. Error cases dominate program logic. Complexity may prevent programmers from dealing with error cases Note that reading EOF, last element of list (-1), etc. are not errors but normal control flow. doa(); if (doa erroneous) treat error cases for doa; else dob(); if (dob erroneous) treat error cases for dob; else doc(); if (doc erroneous) treat error cases for doc; else etc.

335 Exception-Handling Overview Uses of exception handling Process exceptions from program components Handle exceptions in a uniform manner in large projects Remove error-handling code from main line of execution A method detects an error and throws an exception Exception handler processes the error Uncaught exceptions yield adverse effects Might terminate program execution Exception-Handling Overview Code that could generate errors put in try blocks Code for error handling enclosed in a catch clause The finally clause always executes Termination model of exception handling The block in which the exception occurs terminates before dealing with the exception throws clause specifies exceptions that a method throws

336 Some causes of error situations Incorrect implementation. Does not meet the specification. Inappropriate object request. E.g., invalid index. Inconsistent or inappropriate object state. E.g. arising through class extension. Not always programmer error Errors often arise from the environment: Incorrect URL entered. Network interruption. File processing is particular error-prone: Missing files. Lack of appropriate permissions.

337 Exploring errors Explore error situations through the address-book projects. Two aspects: Error reporting. Error handling. Defensive programming Client-server interaction. Should a server assume that clients are well-behaved? Or should it assume that clients are potentially erroneous? Significant differences in implementation required.

338 Issues to be addressed How much checking by a server on method calls? How to report errors? How can a client anticipate failure? How should a client deal with failure? An Example Create an AddressBook object. Try to remove a non-existing entry in empty AddressBook. A runtime error results. Whose fault is this? Anticipation and prevention are preferable to apportioning blame.

339 Argument values Arguments represent a major vulnerability for a server object. Constructor arguments initialize state. Method arguments often contribute to behavior. Argument checking is one defensive measure. Server Error Reporting How to report illegal arguments? To the user? Is there a human user? Can they solve the problem? To the client object? Return a diagnostic value. Throw an exception

340 Test the return value. Attempt recovery on error. Avoid program failure. Ignore the return value. Client responses Cannot be prevented. Likely to lead to program failure. Exceptions are preferable. Exception-throwing principles A special language feature. No special return value needed. Errors cannot be ignored in the client. The normal flow-of-control is interrupted. Specific recovery actions are encouraged.

341 Throwing an exception /** * Look up a name or phone number and return the * corresponding contact details. key The name or number to be looked up. The details corresponding to the key, * or null if there are none matching. NullPointerException if the key is null. */ public ContactDetails getdetails(string key) { if(key == null){ throw new NullPointerException( "null key in getdetails"); } return (ContactDetails) book.get(key); } Throwing an exception An exception object is constructed: new ExceptionType("..."); The exception object is thrown: throw...

342 Inheritance hierarchy for class Throwable Throwable Exception Error RuntimeException IOException AWTError ThreadDeath OutOfMemoryError The exception class hierarchy

Part 1: Introduction. Course Contents. Books. Goals. Sources for Slides (Acknowledgements) Webpage. The course web page is at

Part 1: Introduction. Course Contents. Books. Goals. Sources for Slides (Acknowledgements) Webpage. The course web page is at 1 Course Contents 2 Part 1: Introduction Difference between conventional and objectoriented programming Introduction to object-oriented programming with Java lots of Java details aimed at producing and

More information

Chapter 3 - Introduction to Java Applets

Chapter 3 - Introduction to Java Applets 1 Chapter 3 - Introduction to Java Applets 2 Introduction Applet Program that runs in appletviewer (test utility for applets) Web browser (IE, Communicator) Executes when HTML (Hypertext Markup Language)

More information

Course PJL. Arithmetic Operations

Course PJL. Arithmetic Operations Outline Oman College of Management and Technology Course 503200 PJL Handout 5 Arithmetic Operations CS/MIS Department 1 // Fig. 2.9: Addition.java 2 // Addition program that displays the sum of two numbers.

More information

Copyright 1999 by Deitel & Associates, Inc. All Rights Reserved.

Copyright 1999 by Deitel & Associates, Inc. All Rights Reserved. CHAPTER 2 1 2 1 // Fig. 2.1: Welcome1.java 2 // A first program in Java 3 4 public class Welcome1 { 5 public static void main( String args[] ) 6 { 7 System.out.println( "Welcome to Java Programming!" );

More information

Road Map. Introduction to Java Applets Review applets that ship with JDK Make our own simple applets

Road Map. Introduction to Java Applets Review applets that ship with JDK Make our own simple applets Java Applets Road Map Introduction to Java Applets Review applets that ship with JDK Make our own simple applets Introduce inheritance Introduce the applet environment html needed for applets Reading:

More information

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M tutor Isam M. Al Jawarneh, PhD student isam.aljawarneh3@unibo.it Mobile Middleware

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

Introduction to OOP Using Java Pearson Education, Inc. All rights reserved.

Introduction to OOP Using Java Pearson Education, Inc. All rights reserved. 1 1 Introduction to OOP Using Java 2 Introduction Sun s implementation called the Java Development Kit (JDK) Object-Oriented Programming Java is language of choice for networked applications Java Enterprise

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application Last Time v We created our first Java application v What are the components of a basic Java application? v What GUI component did we use in the examples? v How do we write to the standard output? v An

More information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

Chapter 1 Introduction to Computers and C++ Programming

Chapter 1 Introduction to Computers and C++ Programming Chapter 1 Introduction to Computers and C++ Programming 1 Outline 1.1 Introduction 1.2 What is a Computer? 1.3 Computer Organization 1.7 History of C and C++ 1.14 Basics of a Typical C++ Environment 1.20

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.1: Introduction to C# App Programming Xianrong (Shawn) Zheng Spring 2017 1 Outline Introduction Creating a Simple App String Interpolation

More information

Introduction to C# Applications

Introduction to C# Applications 1 2 3 Introduction to C# Applications OBJECTIVES To write simple C# applications To write statements that input and output data to the screen. To declare and use data of various types. To write decision-making

More information

TTh 9.25 AM AM Strain 322

TTh 9.25 AM AM Strain 322 TTh 9.25 AM - 10.40 AM Strain 322 1 Questions v What is your definition of client/server programming? Be specific. v What would you like to learn in this course? 2 Aims and Objectives v Or, what will you

More information

Chapter 2 - Introduction to C Programming

Chapter 2 - Introduction to C Programming Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic

More information

Chapter 1 & 2 Introduction to C Language

Chapter 1 & 2 Introduction to C Language 1 Chapter 1 & 2 Introduction to C Language Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 1 & 2 - Introduction to C Language 2 Outline 1.1 The History

More information

Introduction to Java Applications; Input/Output and Operators

Introduction to Java Applications; Input/Output and Operators www.thestudycampus.com Introduction to Java Applications; Input/Output and Operators 2.1 Introduction 2.2 Your First Program in Java: Printing a Line of Text 2.3 Modifying Your First Java Program 2.4 Displaying

More information

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

Introduction to C++ Programming Pearson Education, Inc. All rights reserved. 1 2 Introduction to C++ Programming 2 What s in a name? that which we call a rose By any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would be the

More information

Section 2.2 Your First Program in Java: Printing a Line of Text

Section 2.2 Your First Program in Java: Printing a Line of Text Chapter 2 Introduction to Java Applications Section 2.2 Your First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler are denoted using a. Two

More information

CSC System Development with Java Introduction to Java Applets Budditha Hettige

CSC System Development with Java Introduction to Java Applets Budditha Hettige CSC 308 2.0 System Development with Java Introduction to Java Applets Budditha Hettige Department of Statistics and Computer Science What is an applet? applet: a Java program that can be inserted into

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba Laboratory Session: Exercises on classes Analogy to help you understand classes and their contents. Suppose you want to drive a car and make it go faster by pressing down

More information

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.

More information

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

Introduction to C++ Programming. Adhi Harmoko S, M.Komp Introduction to C++ Programming Adhi Harmoko S, M.Komp Machine Languages, Assembly Languages, and High-level Languages Three types of programming languages Machine languages Strings of numbers giving machine

More information

Introduction to Java. Nihar Ranjan Roy. https://sites.google.com/site/niharranjanroy/

Introduction to Java. Nihar Ranjan Roy. https://sites.google.com/site/niharranjanroy/ Introduction to Java https://sites.google.com/site/niharranjanroy/ 1 The Java Programming Language According to sun Microsystems java is a 1. Simple 2. Object Oriented 3. Distributed 4. Multithreaded 5.

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 5 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel s slides Sahrif University of Technology Outlines

More information

Chapter 2: Using Data

Chapter 2: Using Data Chapter 2: Using Data TRUE/FALSE 1. A variable can hold more than one value at a time. F PTS: 1 REF: 52 2. The legal integer values are -2 31 through 2 31-1. These are the highest and lowest values that

More information

Programming for Engineers Introduction to C

Programming for Engineers Introduction to C Programming for Engineers Introduction to C ICEN 200 Spring 2018 Prof. Dola Saha 1 Simple Program 2 Comments // Fig. 2.1: fig02_01.c // A first program in C begin with //, indicating that these two lines

More information

Introduction to Java Applications

Introduction to Java Applications 2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

More information

Full file at

Full file at Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional

More information

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Introduction to C Programming Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline Printing texts Adding 2 integers Comparing 2 integers C.E.,

More information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

Chapter. Focus of the Course. Object-Oriented Software Development. program design, implementation, and testing

Chapter. Focus of the Course. Object-Oriented Software Development. program design, implementation, and testing Introduction 1 Chapter 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design 2007 Pearson Addison-Wesley. All rights reserved Focus of the Course Object-Oriented Software Development

More information

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance. 2.1 Introduction (No questions.) 2.2 A Simple Program: Printing a Line of Text 2.1 Which of the following must every C program have? (a) main (b) #include (c) /* (d) 2.2 Every statement in C

More information

Introduction to Computers and Java

Introduction to Computers and Java Introduction to Computers and Java Chapter 1 Chapter 1 1 Objectives overview computer hardware and software introduce program design and object-oriented programming overview the Java programming language

More information

Fundamentals of Programming Session 4

Fundamentals of Programming Session 4 Fundamentals of Programming Session 4 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2011 These slides are created using Deitel s slides, ( 1992-2010 by Pearson Education, Inc).

More information

Chapter 1. Introduction to Computers and Java Objects. Background information. » important regardless of programming language. Introduction to Java

Chapter 1. Introduction to Computers and Java Objects. Background information. » important regardless of programming language. Introduction to Java Chapter 1 Introduction to Computers and Java Objects Background information» important regardless of programming language Introduction to Java Chapter 1 Java: an Introduction to Computer Science & Programming

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Chapter 02: Using Data

Chapter 02: Using Data True / False 1. A variable can hold more than one value at a time. ANSWER: False REFERENCES: 54 2. The int data type is the most commonly used integer type. ANSWER: True REFERENCES: 64 3. Multiplication,

More information

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved. 1 3 Introduction to Classes and Objects 2 You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

More information

Chapter 2, Part I Introduction to C Programming

Chapter 2, Part I Introduction to C Programming Chapter 2, Part I Introduction to C Programming C How to Program, 8/e, GE 2016 Pearson Education, Ltd. All rights reserved. 1 2016 Pearson Education, Ltd. All rights reserved. 2 2016 Pearson Education,

More information

2 rd class Department of Programming. OOP with Java Programming

2 rd class Department of Programming. OOP with Java Programming 1. Structured Programming and Object-Oriented Programming During the 1970s and into the 80s, the primary software engineering methodology was structured programming. The structured programming approach

More information

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved. 1 3 Introduction to Classes and Objects 2 You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

More information

Chapter 2: Using Data

Chapter 2: Using Data Chapter 2: Using Data TRUE/FALSE 1. A variable can hold more than one value at a time. F PTS: 1 REF: 52 2. The legal integer values are -2 31 through 2 31-1. These are the highest and lowest values that

More information

Full file at

Full file at Chapter 2 Introduction to Java Applications Section 2.1 Introduction ( none ) Section 2.2 First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler

More information

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional

More information

Control Structures (Deitel chapter 4,5)

Control Structures (Deitel chapter 4,5) Control Structures (Deitel chapter 4,5) 1 2 Plan Control Structures ifsingle-selection Statement if else Selection Statement while Repetition Statement for Repetition Statement do while Repetition Statement

More information

Sun ONE Integrated Development Environment

Sun ONE Integrated Development Environment DiveIntoSunONE.fm Page 197 Tuesday, September 24, 2002 8:49 AM 5 Sun ONE Integrated Development Environment Objectives To be able to use Sun ONE to create, compile and execute Java applications and applets.

More information

Introduction to C# Applications Pearson Education, Inc. All rights reserved.

Introduction to C# Applications Pearson Education, Inc. All rights reserved. 1 3 Introduction to C# Applications 2 What s in a name? That which we call a rose by any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would be the

More information

Introduction to Classes and Objects

Introduction to Classes and Objects 1 2 Introduction to Classes and Objects You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

More information

CS112 Lecture: Working with Numbers

CS112 Lecture: Working with Numbers CS112 Lecture: Working with Numbers Last revised January 30, 2008 Objectives: 1. To introduce arithmetic operators and expressions 2. To expand on accessor methods 3. To expand on variables, declarations

More information

19. GUI Basics. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

19. GUI Basics. Java. Fall 2009 Instructor: Dr. Masoud Yaghini 19. GUI Basics Java Fall 2009 Instructor: Dr. Masoud Yaghini Outline Displaying Text in a Message Dialog Box Getting Input from Input Dialogs References Displaying Text in a Message Dialog Box Displaying

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Chapter 1 Introduction to Computers, Programs, and Java

Chapter 1 Introduction to Computers, Programs, and Java Chapter 1 Introduction to Computers, Programs, and Java 1 Programs Computer programs, known as software, are instructions to the computer. You tell a computer what to do through programs. Without programs,

More information

Full file at C How to Program, 6/e Multiple Choice Test Bank

Full file at   C How to Program, 6/e Multiple Choice Test Bank 2.1 Introduction 2.2 A Simple Program: Printing a Line of Text 2.1 Lines beginning with let the computer know that the rest of the line is a comment. (a) /* (b) ** (c) REM (d)

More information

Summary. 962 Chapter 23 Applets and Java Web Start

Summary. 962 Chapter 23 Applets and Java Web Start 962 Chapter 23 Applets and Java Web Start Summary Section 23.1 Introduction Applets (p. 942) are Java programs that are typically embedded in HTML (Extensible Hyper- Text Markup Language) documents also

More information

Chapter 2 Author Notes

Chapter 2 Author Notes Chapter 2 Author Notes Good Programming Practice 2.1 Every program should begin with a comment that explains the purpose of the program, the author and the date and time the program was last modified.

More information

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output Last revised January 12, 2006 Objectives: 1. To introduce arithmetic operators and expressions 2. To introduce variables

More information

GETTING STARTED. The longest journey begins with a single step. In this chapter, you will learn about: Compiling and Running a Java Program Page 2

GETTING STARTED. The longest journey begins with a single step. In this chapter, you will learn about: Compiling and Running a Java Program Page 2 ch01 11/17/99 9:16 AM Page 1 CHAPTER 1 GETTING STARTED The longest journey begins with a single step. CHAPTER OBJECTIVES In this chapter, you will learn about: Compiling and Running a Java Program Page

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Chapter 1 Introduction to Computers, Programs, and Java

Chapter 1 Introduction to Computers, Programs, and Java Chapter Introduction to Computers, Programs, and Java. Introduction Java is the Internet program language Why Java? The answer is that Java enables user to deploy applications on the Internet for servers,

More information

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

More information

Chapter 1 Introduction to Computers, Programs, and Java. What is a Computer? A Bit of History

Chapter 1 Introduction to Computers, Programs, and Java. What is a Computer? A Bit of History Chapter 1 Introduction to Computers, Programs, and Java CS170 Introduction to Computer Science 1 What is a Computer? A machine that manipulates data according to a list of instructions Consists of hardware

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

Introduction to Computers and Java. Objectives. Outline. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich.

Introduction to Computers and Java. Objectives. Outline. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich. Introduction to Computers and Java Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich http://seal.ifi.uzh.ch 2008 W. Savitch, F.M. Carrano, Pearson Prentice Hall Objectives! Overview computer

More information

Introduction to Computers and Java

Introduction to Computers and Java Introduction to Computers and Java Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich http://seal.ifi.uzh.ch 2008 W. Savitch, F.M. Carrano, Pearson Prentice Hall Objectives! Overview computer

More information

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

More information

Introduction to Software Development (ISD) David Weston and Igor Razgon

Introduction to Software Development (ISD) David Weston and Igor Razgon Introduction to Software Development (ISD) David Weston and Igor Razgon Autumn term 2013 Course book The primary book supporting the ISD module is: Java for Everyone, by Cay Horstmann, 2nd Edition, Wiley,

More information

Section 2.2 Your First Program in Java: Printing a Line of Text

Section 2.2 Your First Program in Java: Printing a Line of Text Chapter 2 Introduction to Java Applications Section 2.2 Your First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler are denoted using a. Two

More information

Introduction to Computers and Java

Introduction to Computers and Java Introduction to Computers and Java Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich http://seal.ifi.uzh.ch 2008 W. Savitch, F.M. Carrano, Pearson Prentice Hall Objectives Overview computer

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

More about JOptionPane Dialog Boxes

More about JOptionPane Dialog Boxes APPENDIX K More about JOptionPane Dialog Boxes In Chapter 2 you learned how to use the JOptionPane class to display message dialog boxes and input dialog boxes. This appendix provides a more detailed discussion

More information

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved.

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Methods 2003 Prentice Hall, Inc. All rights reserved. 2 Introduction Modules Small pieces of a problem e.g., divide and conquer Facilitate design, implementation, operation and maintenance

More information

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture

More information

Chapter 4 Introduction to Control Statements

Chapter 4 Introduction to Control Statements Introduction to Control Statements Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives 2 How do you use the increment and decrement operators? What are the standard math methods?

More information

Fundamentals of Programming. Lecture 3: Introduction to C Programming

Fundamentals of Programming. Lecture 3: Introduction to C Programming Fundamentals of Programming Lecture 3: Introduction to C Programming Instructor: Fatemeh Zamani f_zamani@ce.sharif.edu Sharif University of Technology Computer Engineering Department Outline A Simple C

More information

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual: Java Programming, Eighth Edition 2-1 Chapter 2 Using Data A Guide to this Instructor s Manual: We have designed this Instructor s Manual to supplement and enhance your teaching experience through classroom

More information

Introduction to Computers and Java. Objectives. Outline. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich.

Introduction to Computers and Java. Objectives. Outline. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich. Introduction to Computers and Java Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich http://seal.ifi.uzh.ch 2008 W. Savitch, F.M. Carrano, Pearson Prentice Hall Objectives Overview computer

More information

An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a

An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a CBOP3203 An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a page. When you use a Java technology-enabled

More information

Introduction to Computers and Programming Languages. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Introduction to Computers and Programming Languages. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Introduction to Computers and Programming Languages CS 180 Sunil Prabhakar Department of Computer Science Purdue University 1 Objectives This week we will study: The notion of hardware and software Programming

More information

CST141 Thinking in Objects Page 1

CST141 Thinking in Objects Page 1 CST141 Thinking in Objects Page 1 1 2 3 4 5 6 7 8 Object-Oriented Thinking CST141 Class Abstraction and Encapsulation Class abstraction is the separation of class implementation from class use It is not

More information

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language Chapter 1 Getting Started Introduction To Java Most people are familiar with Java as a language for Internet applications We will study Java as a general purpose programming language The syntax of expressions

More information

Chapter 1 Introduction to Computers, Programs, and Java

Chapter 1 Introduction to Computers, Programs, and Java Chapter 1 Introduction to Computers, Programs, and Java 1 Objectives To review computer basics, programs, and operating systems ( 1.2-1.4). To explore the relationship between Java and the World Wide Web

More information

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java Introduction Objectives An overview of object-oriented concepts. Programming and programming languages An introduction to Java 1-2 Problem Solving The purpose of writing a program is to solve a problem

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Spring 2005 Lecture 1 Jan 6, 2005 Course Information 2 Lecture: James B D Joshi Tuesdays/Thursdays: 1:00-2:15 PM Office Hours:

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Chapter 4 Control Structures: Part 2

Chapter 4 Control Structures: Part 2 Chapter 4 Control Structures: Part 2 1 2 Essentia ls of Counter-Controlled Repetition Counter-controlled repetition requires: Control variable (loop counter) Initial value of the control variable Increment/decrement

More information

Chapter 2 ELEMENTARY PROGRAMMING

Chapter 2 ELEMENTARY PROGRAMMING Chapter 2 ELEMENTARY PROGRAMMING Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk ١ Objectives To write Java programs to perform simple

More information

9/11/08 (c) 2008 Matthew J. Rutherford Class (c) 2008 Matthew J. Rutherford Class

9/11/08 (c) 2008 Matthew J. Rutherford Class (c) 2008 Matthew J. Rutherford Class 1 2 3 4 5 6 Walter Savitch Frank M. Carrano Introduction to Computers and Java Chapter 1 ISBN 0136130887 2007 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved 7 Hardware and Software

More information

Chapter 17. Fundamental Concepts Expressed in JavaScript

Chapter 17. Fundamental Concepts Expressed in JavaScript Chapter 17 Fundamental Concepts Expressed in JavaScript Learning Objectives Tell the difference between name, value, and variable List three basic data types and the rules for specifying them in a program

More information

Basic Programming Language Syntax

Basic Programming Language Syntax Java Created in 1990 by Sun Microsystems. Free compiler from Sun, commercial from many vendors. We use free (Sun) Java on UNIX. Compiling and Interpreting...are processes of translating a high-level programming

More information

0 Introduction: Computer systems and program development

0 Introduction: Computer systems and program development 0 Introduction: Computer systems and program development Outline 1 Introduction 2 What Is a Computer? 3 Computer Organization 4 Evolution of Operating Systems 5 Personal Computing, Distributed Computing

More information

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

2.5 Another Application: Adding Integers

2.5 Another Application: Adding Integers 2.5 Another Application: Adding Integers 47 Lines 9 10 represent only one statement. Java allows large statements to be split over many lines. We indent line 10 to indicate that it s a continuation of

More information

Intro to Computer Programming (ICP) Rab Nawaz Jadoon

Intro to Computer Programming (ICP) Rab Nawaz Jadoon Intro to Computer Programming (ICP) Rab Nawaz Jadoon DCS COMSATS Institute of Information Technology Assistant Professor COMSATS IIT, Abbottabad Pakistan Introduction to Computer Programming (ICP) What

More information

2.8. Decision Making: Equality and Relational Operators

2.8. Decision Making: Equality and Relational Operators Page 1 of 6 [Page 56] 2.8. Decision Making: Equality and Relational Operators A condition is an expression that can be either true or false. This section introduces a simple version of Java's if statement

More information

last time in cs recitations. computer commands. today s topics.

last time in cs recitations. computer commands. today s topics. last time in cs1007... recitations. course objectives policies academic integrity resources WEB PAGE: http://www.columbia.edu/ cs1007 NOTE CHANGES IN ASSESSMENT 5 EXTRA CREDIT POINTS ADDED sign up for

More information

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2 CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information