1. Trang chủ
  2. » Công Nghệ Thông Tin

Ebook Java: An introduction to problem solving & programming (Sixth edition) – Part 2

473 72 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 473
Dung lượng 7,27 MB

Nội dung

Ebook Java: An introduction to problem solving & programming (Sixth edition) – Part 2 presents the following chapters: Chapter 7 arrays; chapter 8 inheritance, polymorphism and interfaces; chapter 9 exception handling; chapter 10 streams and file I/O; chapter 11 recursion; chapter 12 dynamic data structures and generics; chapter 13 window interfaces using swing; chapter 14 applets and HTML; chapter 15 more swing.

Arrays 7.4 SORTING AND SEARCHING ARRAYS 525 Selection Sort 525 Other Sorting Algorithms 529 Searching an Array 531 7.1 ARRAY BASICS 481 Creating and Accessing Arrays 482 Array Details 485 The Instance Variable length 488 More About Array Indices 491 Initializing Arrays 494 7.5 MULTIDIMENSIONAL ARRAYS 532 Multidimensional-Array Basics 533 Multidimensional-Array Parameters and Returned Values 536 Java’s Representation of Multidimensional Arrays 539 Ragged Arrays (Optional ) 540 Programming Example: Employee Time Records 542 7.2 ARRAYS IN CLASSES AND METHODS 495 Case Study: Sales Report 495 Indexed Variables as Method Arguments 503 Entire Arrays as Arguments to a Method 505 Arguments for the Method main 507 Array Assignment and Equality 508 Methods That Return Arrays 511 7.3 PROGRAMMING WITH ARRAYS AND CLASSES 515 Programming Example: A Specialized List Class Partially Filled Arrays 523 Chapter Summary 556 515 Programming Projects 7.6 GRAPHICS SUPPLEMENT 548 Text Areas and Text Fields 548 Programming Example: A Question-and-Answer Applet 548 The Classes JTextArea and JTextField 551 Drawing Polygons 553 562 Answers to Self-Test Questions 568 They stood at attention in a neat row, all with the same uniform, yet each with his own values ‰8"33&/1&"$& The Lieutenant’s Array An array is a special kind of object used to store a collection of data An array differs from the other objects you have seen in two ways: t "MM UIF EBUB TUPSFE JO BO BSSBZ NVTU CF PG UIF TBNF UZQF 'PS FYBNQMF  you might use an array to store a list of values of type double that record rainfall readings in centimeters Or you might use an array to store a list of objects of some class called Species that contain the records for various endangered species t "OBSSBZPCKFDUIBTPOMZBTNBMMOVNCFSPGQSFEFGJOFENFUIPET#FDBVTF arrays were used by programmers for many years before classes were JOWFOUFE  UIFZ VTF B TQFDJBM OPUBUJPO PG UIFJS PXO UP JOWPLF UIPTF GFX QSFEFGJOFE NFUIPET  BOE NPTU QFPQMF EP OPU FWFO UIJOL PG UIFN BT methods *OUIJTDIBQUFS XFJOUSPEVDFZPVUPBSSBZTBOETIPXZPVIPXUPVTFUIFN in Java OBJECTIVES "GUFSTUVEZJOHUIJTDIBQUFS ZPVTIPVMECFBCMFUP t %FTDSJCFUIFOBUVSFBOEQVSQPTFPGBOBSSBZ t 6TFBSSBZTJOTJNQMF+BWBQSPHSBNT t %FGJOFNFUIPETUIBUIBWFBOBSSBZBTBQBSBNFUFS t %FGJOFNFUIPETUIBUSFUVSOBOBSSBZ t 6TFBOBSSBZBTBOJOTUBODFWBSJBCMFJOBDMBTT t 6TFBOBSSBZUIBUJTOPUGJMMFEDPNQMFUFMZ t 0SEFS PSTPSU UIFFMFNFOUTJOBOBSSBZ t 4FBSDIBOBSSBZGPSBQBSUJDVMBSJUFN t %FGJOFBOEVTFNVMUJEJNFOTJPOBMBSSBZT t *OTFSUUFYUGJFMETBOEUFYUBSFBTJOUPZPVSBQQMFUT t %SBXBSCJUSBSZQPMZHPOTJOZPVSBQQMFUT PREREQUISITES This is the first point in this book where you have a significant choice as to XIBUUPSFBEOFYU*GZPVQSFGFS JOTUFBEPGSFBEJOHUIJTDIBQUFSOPX ZPVDBO go on in the book and return to this discussion of arrays at a later time You 480 7.1 Array Basics 481 DBOSFBE$IBQUFSTUISPVHI   BOE FYDFQUGPS4FDUJPO BT ZPVXJTICFGPSFZPVSFBEUIJTDIBQUFS4FDUJPOTBOEJODMVEFSFGFSFODFT UPBSSBZTGPSTPNFPGUIFFYBNQMFT 4FDUJPOEFQFOETPOMZPO$IBQUFSTUISPVHI)PXFWFS ZPVTIPVME be familiar with the material in all of the previous chapters before reading the remaining sections of this chapter *G ZPV BSF SFBEJOH UIF HSBQIJDT TVQQMFNFOU TFDUJPOT JO FBDI DIBQUFS  you can—and are encouraged to—read the first part of this chapter’s graphic TVQQMFNFOU XIFUIFSZPVSFBEUIFSFTUPGUIFDIBQUFSPSOPU 7.1 ARRAY BASICS And in such indexes, although small pricks To their subsequent volumes, there is seen The baby figure of the giant mass Of things to come —WILLIAM SHAKESPEARE, TROILUS AND CRESSIDA 4VQQPTFZPVXBOUUPDPNQVUFUIFBWFSBHFUFNQFSBUVSFGPSUIFTFWFOEBZTJOB week You might use the following code: Scanner keyboard = new Scanner(System.in); System.out.println("Enter temperatures:"); double sum = 0; for (int count = 0; count < 7; count++) { double next = keyboard.nextDouble(); sum = sum + next; } double average = sum / 7; 5IJTXPSLTGJOFJGBMMZPVXBOUUPLOPXJTUIFBWFSBHF#VUMFUTTBZZPVBMTP want to know which temperatures are above and which are below the average /PX ZPV IBWF B QSPCMFN *O PSEFS UP DPNQVUF UIF BWFSBHF  ZPV NVTU SFBE UIFTFWFOUFNQFSBUVSFT BOEZPVNVTUDPNQVUFUIFBWFSBHFCFGPSFDPNQBSJOH FBDIUFNQFSBUVSFUPJU5IVT UPCFBCMFUPDPNQBSFFBDIUFNQFSBUVSFUPUIF BWFSBHF ZPVNVTUSFNFNCFSUIFTFWFOUFNQFSBUVSFT)PXDBOZPVEPUIJT  The obvious answer is to use seven variables of type double This is a bit BXLXBSE CFDBVTFTFWFOJTBMPUPGWBSJBCMFTUPEFDMBSF BOEJOPUIFSTJUVBUJPOT  the problem can be even worse Imagine doing the same thing for each day of UIFZFBSJOTUFBEPGKVTUFBDIEBZPGUIFXFFL8SJUJOHWBSJBCMFEFDMBSBUJPOT would be absurd Arrays provide us with an elegant way to declare a collection of related variables An array is a collection of items of the same type It is Items in an array TPNFUIJOHMJLFBMJTUPGWBSJBCMFT CVUJUIBOEMFTUIFOBNJOHPGUIFWBSJBCMFTJO have the same data type BOJDF DPNQBDUXBZ 482 CHAPTER / Arrays Creating and Accessing Arrays *O+BWB BOBSSBZJTBTQFDJBMLJOEPGPCKFDU CVUJUJTPGUFONPSFVTFGVMUPUIJOLPGBO BSSBZBTBDPMMFDUJPOPGWBSJBCMFTPGUIFTBNFUZQF'PSFYBNQMF BOBSSBZDPOTJTUJOH of a collection of seven variables of type double can be created as follows: double[] temperature = new double[7]; This is like declaring the following seven strangely named variables to have the type double: temperature[0], temperature[1], temperature[2], temperature[3], temperature[4], temperature[5], temperature[6] An index is an integer expression that indicates an array element Variables like temperature[0] and temperature[1] that have an integer FYQSFTTJPO JO TRVBSF CSBDLFUT BSF DBMMFE indexed variables, subscripted variable, array elements, or simply elements.5IFJOUFHFSFYQSFTTJPOXJUIJO UIFTRVBSFCSBDLFUTJTDBMMFEBOindex or a subscript Note that the numbering TUBSUTXJUI OPU REMEMBER Array Indices Begin at In Java, the indices of an array always start with They never start with or any number other than Each of these seven variables can be used just like any other variable of type double'PSFYBNQMF BMMPGUIFGPMMPXJOHTUBUFNFOUTBSFBMMPXFEJO+BWB temperature[3] = 32; temperature[6] = temperature[3] + 5; System.out.println(temperature[6]); 8IFOXFUIJOLPGUIFTFJOEFYFEWBSJBCMFTBTCFJOHHSPVQFEUPHFUIFSJOUPPOF DPMMFDUJWFJUFN XFXJMMDBMMUIFNBOBSSBZ4PXFDBOSFGFSUPUIFBSSBZOBNFE temperatureXJUIPVUVTJOHBOZTRVBSFCSBDLFUT'JHVSFJMMVTUSBUFTUIFBSSBZ temperature #VUUIFTFTFWFOWBSJBCMFTBSFNPSFUIBOKVTUTFWFOQMBJOPMEWBSJBCMFTPG type double 5IF OVNCFS JO TRVBSF CSBDLFUT JT QBSU PG UIF OBNF PG FBDI PG UIFTFWBSJBCMFT BOEJUEPFTOPUIBWFUPCFBOJOUFHFSDPOTUBOU*OTUFBE ZPV DBOVTFBOZFYQSFTTJPOUIBUFWBMVBUFTUPBOJOUFHFSUIBUJTBUMFBTUBOE‰GPS UIJTFYBNQMF‰BUNPTU4PUIFGPMMPXJOHDPEF GPSJOTUBODF JTBMMPXFE Scanner keyboard = new Scanner(System.in); System.out.println("Enter day number (0 - 6):"); int index = keyboard.nextInt(); System.out.println("Enter temperature for day " + index); temperature[index] = keyboard.nextDouble(); 7.1 Array Basics FIGURE 7.1 A Common Way to Visualize an Array Indices 32 30 25.7 26 34 31.5 29 The array temperature temperature[5] 4JODFBOJOEFYDBOCFBOFYQSFTTJPO XFDBOXSJUFBMPPQUPSFBEWBMVFTJOUP the array temperature BTGPMMPXT System.out.println("Enter temperatures:"); for (int index = 0;index < 7; index++) temperature[index] = keyboard.nextDouble(); 5IFVTFSDPVMEUZQFUIFTFWFOWBMVFTPOTFQBSBUFMJOFTPSBMMPOPOFMJOF TFQBSBUFE CZTQBDFT"GUFSUIFBSSBZWBMVFTBSFSFBEJO XFDBOEJTQMBZUIFNBTGPMMPXT System.out.println("The temperatures are:"); for (int index = 0; index < 7; index++) System.out.print(temperature[index] + " "); System.out.println( ); 5IFQSPHSBNJO-JTUJOHTIPXTBOFYBNQMFUIBUVTFTPVSTBNQMFBSSBZ temperature BT TFWFO JOEFYFE WBSJBCMFT  BMM PG UZQF double Note that the program uses for loops similar to the ones we just considered LISTING 7.1 An Array of Temperatures (part of 2) /** Reads temperatures from the user and shows which are above and which are below the average of the temperatures */ import java.util.Scanner; public class ArrayOfTemperatures { public static void main(String[] args) { double[] temperature = new double[7]; // Read temperatures and compute their average: Scanner keyboard = new Scanner(System.in); System.out.println("Enter temperatures:"); double sum = 0; for (int index = 0; index < 7; index++) (continued) 483 484 CHAPTER / Arrays LISTING 7.1 An Array of Temperatures (part of 2) { temperature[index] = keyboard.nextDouble(); sum = sum + temperature[index]; } double average = sum / 7; System.out.println("The average temperature is " + average); // Display each temperature and its relation to the average: System.out.println("The temperatures are"); for (int index = 0; index < 7; index++) { if (temperature[index] < average) System.out.println(temperature[index] + " below average"); else if (temperature[index] > average) System.out.println(temperature[index] + " above average"); else //temperature[index] == average System.out.println(temperature[index] + " the average"); } System.out.println("Have a nice week."); } } Sample Screen Output Enter temperatures: 32 30 25.7 26 34 31.5 29 The average temperature is 29.7428 The temperatures are 32.0 above average 30.0 above average 25.7 below average 26.0 below average 34.0 above average 31.5 above average 29.0 below average Have a nice week 7.1 Array Basics 485 Array Details You create an array in the same way that you would create an object of a class type using the operation new  CVU UIF OPUBUJPO JT TMJHIUMZ EJGGFSFOU 8IFO creating an array of elements of type Base_Type UIFTZOUBYJTBTGPMMPXT Base_Type[] Array_Name = new Base_Type[Length]; 'PSFYBNQMF UIFGPMMPXJOHDSFBUFTBOBSSBZOBNFEpressureUIBUJTFRVJWBMFOU UPWBSJBCMFTPGUZQFint: int[] pressure = new int[100]; "MUFSOBUJWFMZ UIFQSFDFEJOHDBOCFCSPLFOEPXOJOUPUXPTUFQT int[] pressure; pressure = new int[100]; The first step declares as an array of integers The second ASIDE Alternative Syntax for Declaring step allocates enough memory an Array GPSUIFBSSBZUPIPMEVQUP Although we not encourage its use, there integers is an alternative syntax for array declarations The type for the array that you may encounter You can write the square brackets after the variable instead elements is called the base of after the base type, as in the following type of the array In this example: FYBNQMF UIFCBTFUZQFJT int The number of elements in char alphabet[]; an array is called the length, size, or capacity of the array 4P UIJT TBNQMF BSSBZ pressure IBT MFOHUI   XIJDI NFBOT JU IBT JOEFYFE variables pressure[0]through pressure[99] Note that because the indices TUBSU BU   BO BSSBZ PG MFOHUI   TVDI BT pressure  XJMM IBWF no JOEFYFE variable pressure[100] 5IF CBTF UZQF PG BO BSSBZ DBO CF BOZ EBUB UZQF *O QBSUJDVMBS  JU DBO CF a class type The following statement creates an array named entry whose elements are SpeciesPCKFDUT XIFSFSpecies is a class: Species[] entry = new Species[3]; This array is a collection of the three variables entry[0]  entry[1]  BOE entry[2] BMMPGUZQFSpecies RECAP Declaring and Creating an Array You declare and create an array in almost the same way that you declare and create objects of classes There is only a slight difference in the syntax (continued) The number of elements in an array is its length The type of the array elements is the array’s base type 486 CHAPTER / Arrays SYNTAX Base_Type[] Array_Name = new Base_Type[Length]; EXAMPLES char[] symbol = new char[80]; double[] reading = new double[100]; Species[] specimen = new Species[80]; //Species is a class REMEMBER How to Use Square Brackets with Arrays There are three different ways to use square brackets [] with an array name They can be used t 8JUIBEBUBUZQFXIFOEFDMBSJOHBOBSSBZ'PSFYBNQMF int[] pressure; declares—but does not allocate memory for—pressure as an array of inteHFST t 5PFODMPTFBOJOUFHFSFYQSFTTJPOXIFODSFBUJOHBOFXBSSBZ'PSFYBNQMF pressure = new int[100]; allocates memory for the array pressurePGJOUFHFST t 5POBNFBOJOEFYFEWBSJBCMFPGUIFBSSBZ'PSFYBNQMF pressure[3] in the following two lines is an indexed variable: pressure[3] = keyboard.nextInt(); System.out.println("You entered" + pressure[3]); "TXFNFOUJPOFEQSFWJPVTMZ UIFWBMVFJOTJEFUIFTRVBSFCSBDLFUTDBOCF BOZ FYQSFTTJPO UIBU FWBMVBUFT UP BO JOUFHFS 8IFO DSFBUJOH BO BSSBZ  JOTUFBE PGVTJOHBOJOUFHFSMJUFSBM ZPVDBO‰BOETIPVME‰VTFBOBNFEDPOTUBOU'PS FYBNQMF ZPVTIPVMEVTFBDPOTUBOUTVDIBT NUMBER_OF_READINGS instead of XIFOZPVDSFBUFUIFBSSBZpressure: Use a named constant when defining an array public static final int NUMBER_OF_READINGS = 100; int[] pressure = new int[NUMBER_OF_READINGS]; +BWB BMMPDBUFT NFNPSZ GPS BO BSSBZ  BT XFMM BT GPS BOZ PUIFS PCKFDU  BU FYFDVUJPO UJNF 4P JG ZPV EP OPU LOPX IPX MBSHF UP NBLF BO BSSBZ XIFO ZPVXSJUFBQSPHSBN ZPVDBOSFBEUIFBSSBZTMFOHUIGSPNUIFLFZCPBSE BT follows: 7.1 Array Basics 487 FIGURE 7.2 Array Terminology Array name temperature[n + 2] Index (also called a subscript) Indexed variable (also called an array element, an element, or a subscripted variable) temperature[n + 2] temperature[n + 2] Value of the indexed variable (also called an element of the array) temperature[n + 2] = 32; System.out.println("How many temperatures you have?"); int size = keyboard.nextInt(); double[] temperature = new double[size]; :PVDBOBMTPVTFBOZFYQSFTTJPOUIBUFWBMVBUFTUPBOBQQSPQSJBUFJOUFHFS XIFOOBNJOHBOJOEFYFEWBSJBCMFPGBOBSSBZ BTJOUIFGPMMPXJOHFYBNQMFT int point = 2; temperature[point + 3] = 32; System.out.println("Temperature is " + temperature[point + 3]); Note that temperature[point + 3]JOUIFQSFDFEJOHDPEFJTUIFTBNFJOEFYFE variable as temperature[5] CFDBVTFpoint + 3FWBMVBUFTUP 'JHVSFJMMVTUSBUFTTPNFPGUIFNPTUDPNNPOUFSNTVTFEXIFOSFGFSSJOH to arrays Notice that the word element has two meanings It can be used to SFGFSUPBOJOEFYFEWBSJBCMFBTXFMMBTUPUIFWBMVFPGBOJOEFYFEWBSJBCMF ■ PROGRAMMING TIP In General, Use Singular Names for Arrays *GZPVXBOUBOBSSBZUPIPMEFOUSJFT FBDIPGXIJDIJTBOPCKFDUPGBDMBTTDBMMFE Species ZPVNJHIUCFUFNQUFEUPVTFTPNFUIJOHMJLFUIFGPMMPXJOH Species[] entries = new Species[20]; //Valid but not nice 6TJOHBQMVSBM MJLFentries TFFNTUPNBLFTFOTF TJODFUIFBSSBZIPMETNPSF UIBOPOFFMFNFOU)PXFWFS QSPHSBNNFSTGJOEUIBUUIFJSQSPHSBNTPGUFOSFBE CFUUFSJGUIFZVTFBTJOHVMBSGPSNGPSBOBSSBZOBNF MJLFUIFGPMMPXJOH Species[] entry = new Species[20]; //Nicer Reading an array length 488 CHAPTER / Arrays 5IF SFBTPO UIBU UIF TJOHVMBS GPSN XPSLT CFUUFS IFSF JT UIBU  XIFO UIF BSSBZ OBNF JT VTFE JO TPNF TPSU PG DPNQVUBUJPO  UIF OBNF SFGFST UP POMZ POF FMFNFOU 5IF FYQSFTTJPO entry[2] JT B TJOHMF FMFNFOU PG UIF BSSBZ  BT JO B statement such as System.out.println("The entry is " + entry[2]); 5IFVTFPGTJOHVMBSOBNFTGPSBSSBZTJTOPUBOBCTPMVUFSVMF4PNFUJNFT JU NBLFT TFOTF UP VTF QMVSBM OBNFT 'PS FYBNQMF  JG BO JOEFYFE WBSJBCMF contains the number of hours worked by employee number n  UIF QMVSBM form hours[n] makes sense The only sure test of whether to use a singular or QMVSBMOBNFJTUPDPOTJEFSIPXBOJOEFYFEWBSJBCMFXPVMESFBEJOUIFDPOUFYU of your Java code ■ The Instance Variable length "O BSSBZ JT B LJOE PG PCKFDU  BOE MJLF PUIFS PCKFDUT  JU NJHIU IBWF JOTUBODF WBSJBCMFT "T JU UVSOT PVU  BO BSSBZ IBT POMZ POF QVCMJD JOTUBODF WBSJBCMF  namely the variable length  XIJDI JT FRVBM UP UIF MFOHUI PG UIF BSSBZ 'PS FYBNQMF JGZPVDSFBUFBOBSSBZCZXSJUJOH The array e has a length of e.length Species[] entry = new Species[20]; entry.length IBT B WBMVF PG  #Z VTJOH UIF JOTUBODF WBSJBCMF length instead of a literal like 20  ZPV DBO NBLF ZPVS QSPHSBN DMFBSFS BOE NPSF general A name like entry.length means more to a reader of your program UIBOBOVNCFSXIPTFNFBOJOHNBZOPUBMXBZTCFPCWJPVT*OBEEJUJPO JG ZPVMBUFSEFDJEFUPDIBOHFUIFTJ[FPGUIFBSSBZ ZPVIBWFOPOFFEUPDIBOHF occurrences of entry.length Note that lengthJTGJOBM TPJUTWBMVFDBOOPU be changed GOTCHA Assigning a Value to the Instance Variable length Your program cannot assign a value to the instance variable length  BT JU JT BGJOBMWBSJBCMF'PSFYBNQMF UIFGPMMPXJOHBUUFNQUUPDIBOHFUIFTJ[FPGBO array is invalid: entry.length = 10; //Illegal! ■ *O -JTUJOH  XF IBWF SFXSJUUFO UIF QSPHSBN JO -JTUJOH  VTJOH the instance variable length We have also read the size of the array temperature from the user into the variable size *O UIJT FYBNQMF  XF could use size instead of temperature.length )PXFWFS  TJODF size is OPUGJOBM JUTWBMVFDBODIBOHFBOETPNJHIUOPUBMXBZTFRVBMUIFWBMVFPG temperature.length APPENDIX Differences Between C++ and Java This appendix is for readers who have had significant programming experience with either C or C++ Other readers can ignore this appendix Java and C++ appear to be very similar, but they have more differences than a casual examination of the two languages might lead you to believe We will not describe all of the differences in this appendix, but we will go over a few similarities and differences in order to help you make the transition from C++ (or C) to Java Primitive Types Java has most of the same basic primitive types as C and C++ (int, short, long, float, double, and char), but Java adds the types byte and boolean The Java type boolean corresponds to the C++ type bool Java has no type named long double Unlike C and C++, in Java the size, in bytes, of a value for some specific primitive type is fully specified and is not implementation dependent See Chapter for details Strings Unlike some versions of C and C++, in Java strings are not special kinds of arrays of characters Java has a class String that serves as a predefined type String is somewhat similar to the class String in recent versions of C++ (Coverage of the String class starts in Chapter 2.) Flow of Control Control structures (if-else, switch, while, do-while, and for) are the same in Java as in C and C++ However, there are some differences in Java that can affect your use of control structures Specifically, Java has no comma operator; the type boolean in Java is not a numeric type, nor can its values be type cast to a numeric type; and the assignment operator is better behaved in Java than in C and C++ We discuss each of these differences briefly below Java does not have the comma operator However, the for statement in Java has been defined so as to allow the use of the comma, as in the following code: 928 Appendix for (int n = 1, product = 1; n < = 10; n++) product = product * n; This “comma operator” can be used only in a for statement In Java, the type boolean has the two values, true and false, which cannot be interpreted as numeric values, even with a type cast A classic error in C and C++ is to use = in place of ==, as in the following code: if (n = 42) In C and C++, the expression n = 42 returns the value 42, which either is or will be converted to a boolean value, depending on what version of C or C++ you are using In Java, n = 42 also returns the value 42, but in Java, 42 is not of type boolean, nor will it convert to type boolean So in Java, this mistake will produce a compiler error message Testing for Equality Testing objects of a class type for equality can be troublesome in Java With values of a primitive type, the == operator tests for equality, as you might expect However, when you use == to compare two objects of a class type, the addresses of the objects are compared instead of their data Java classes often define a method called equals to test objects for our intuitive idea of equality You cannot overload the == operator (or any operator) in Java main Method (Function) and Other Methods Functions are called methods in Java The main method serves the same purpose in Java as the main function in C and C++ In Java, the main method heading is always as follows: public static void main(String[] Parameter_Name) In Java, all methods are defined inside of a class, as is code of any kind Files and Including Files Java does not have an #include directive, but it does have an import statement that allows you to import either a class or an entire package (library) for use in a class The general layout of a Java program consists of a number of classes, each in a file by itself If all the classes are in the same folder (directory), Java will automatically find the class (file) it needs when it needs it The import statement also makes it possible to combine classes (files) from different folders See Section 6.7 in Chapter for more details 929 930 APPENDIX / Differeces Between C++ and Java In Java, a class must be in a file that has the same name as the class, but with the suffix java For example, a class named MyClass must be in a file named MyClass.java The compiled version of the class will be placed in a file named MyClass.class Class and Method (Function) Definitions In Java, all methods must be defined in some class Additionally, a class definition can be fully defined in one file Java has no required header, or h, file, as C and C++ In particular, all method definitions are given in their entirety in their class definition See Chapter for more details Java does provide for an interface, which is similar in form to a header file in C and C++ but serves a different purpose Chapter introduces Java interfaces No Pointer Types in Java There are no pointer types in Java Java does have pointers; in fact, all objects are named by means of pointers However, the pointers are called references, and they are handled automatically For example, a variable of type String will contain a reference (pointer) to a string, but there is no type for a pointer to a String See Section 5.3 in Chapter for more details Method (Function) Parameters Strictly speaking, Java has only one mechanism for parameter passing, namely, call-by-value In practice, however, Java’s parameter-passing mechanism behaves one way for primitive types—such as int, double, and char—and another way for class types For primitive types, the call-by-value parameter-passing mechanism behaves as C and C++ programmers would expect That is, the parameter contains the value of its corresponding argument But Java parameters of a class type contain a reference to the class object that is passed This allows a method (function) to change the data in the object, and so some people consider this mechanism to be a call-by-reference mechanism It does not satisfy the most common definition of call-by-reference, but when doing most simple tasks, it behaves very much like call-by-reference See Chapter for more details Arrays Java arrays are very much like C or C++ arrays, but there are some differences, and Java arrays are better behaved An array in Java “knows” its range If a is an array, the instance variable a.length contains an integer equal to the number of elements that the array can hold Java ensures that the values of array indices (subscripts) are valid, and an exception is thrown if your code attempts to use an array index that is out of range See Chapter for more details Appendix Garbage Collection Memory management and garbage collection are automatic in Java Java uses the new operator to create and allocate memory for a new object of a class type This is the only way to explicitly allocate memory Additionally, Java provides automatic garbage collection, relieving the programmer from this responsibility Memory leaks, which can be a problem in C and C++, are not an issue in Java Other Comparisons t $PNNFOUTJO+BWBBOE$ BSFFTTFOUJBMMZUIFTBNF t 5IFSFBSFOPHMPCBMWBSJBCMFTJO+BWB t +BWBIBTOPtypedef t +BWBIBTOPTUSVDUVSFTPSVOJPOT t :PVDBOPWFSMPBENFUIPE GVODUJPO OBNFTJO+BWB BTZPVDBOJO$ CVU you cannot overload operators in Java t +BWB IBT OP NVMUJQMF JOIFSJUBODF  CVU JOUFSGBDFT QSPWJEF NVDI PG UIF functionality of multiple inheritance See Chapter for more details on interfaces t +BWB IBT OP UFNQMBUFT  CVU JU EPFT IBWF HFOFSJDT JO UIFJS QMBDF 4FF Chapter 12 for an introduction to generics t *O+BWB BDMBTTDBOIBWFBDPOTUSVDUPSXJUIBQBSBNFUFSPGUIFTBNFUZQF as the class, but this constructor has no special status, unlike a copy constructor in C++ t +BWBIBTOPEFTUSVDUPST 931 APPENDIX Unicode Character Codes The printable characters shown are a subset of the Unicode character set known as the ASCII character set The numbering is the same whether the characters are considered to be members of the Unicode character set or members of the ASCII character set (Character number 32 is the blank.) 32 932 56 80 P 104 h 33 ! 57 81 Q 105 i 34 " 58 : 82 R 106 j 35 # 59 ; 83 S 107 k 36 $ 60 < 84 T 108 l 37 % 61 = 85 U 109 m 38 & 62 > 86 V 110 n 39 ' 63 ? 87 W 111 o 40 ( 64 @ 88 X 112 p 41 ) 65 A 89 Y 113 q 42 * 66 B 90 Z 114 r 43 + 67 C 91 [ 115 s 44 , 68 D 92 \ 116 t 45 - 69 E 93 ] 117 u 46 70 F 94 ^ 118 v 47 / 71 G 95 _ 119 w 48 72 H 96 ' 120 x 49 73 I 97 a 121 y 50 74 J 98 b 122 z 51 75 K 99 c 123 { 52 76 L 100 d 124 | 53 77 M 101 e 125 } 54 78 N 102 f 126 ~ 55 79 O 103 g Index SYMBOLS ' ', single quotes for characters, 52–53 !, not (logical) operator, 148–150 !=, not equal to operator, 145 " ", double quotes, 16, 82–83, 88 printed statements, 16 string value, 82–83, 88 "##" whitespace delimiter, 99–100 $, special symbol, 53 %, remainder (modulus) operator, 70 %c, character format specifier, 102 %d, decimal format specifier, 101–102 %e, exponential floating-point format specifier, 102 %f, floating-point format specifier, 101–102 %s, string format specifier, 102 &&, and (logical) operator, 146–148 ( ), parentheses, 16–18, 71–73, 84 arithmetic expressions, 71–73 arguments, 16–18, 84 *, multiplication operator, 56, 69 , decrement operator, 79–80 –, minus (dash) symbol, 56, 69–71, 320–321 number sign (unary) operator, 70–71 subtraction (binary) operator, 56, 69, 71 UML private notation, 320–321 ,, comma operator, 220 , dot notation, 16–18, 84–85, 282–283 instance variables, 282–283 invoking (calling) methods, 16–18, 84–85, 282 /* */, comments, 104, 106 /** */, comments, 104–106 /, division operator, 69–70 //, comments, 104, 106 ;, semicolons, 17, 201, 218–219 end of instructions, 17 loop body, 201, 218–219 [ ], brackets for arrays, 482, 485–486, 535–536, 538 \", escape character, 88–89 \', escape character, 88–89 \\, double slash, 88–89, 743–744 escape character, 88–89 path names, 743–744 \, single slash for path names, 743–744 '\n', end of line character, 95, 98–99 \n, newline escape character, 88–89 \r, carriage return escape character, 88–89 \t, tab escape character, 88–89 _ , underscore character, 53–54, 63 { }, braces, 14–15, 50, 106–107, 140–142, 156–157, 199–201, 272, 286–287 blocks, 286–287 loop body, 199–201 if-else statements, 140–142, 156–157 indentation, programming style, 106–107, 140, 156–157 methods, 14–15, 272 variable declaration, 50, 286–287 ||, or (logical) operator, 147– 148 +, plus symbol, 56, 69, 70–71, 82–83, 320–321 addition (binary) operator, 56, 69, 71 concatenation operator, 82–83 number sign (unary) operator, 70–71 UML public notation, 320–321 ++, increment operator, 79–80 =, greater than or equal to operator, 139–140, 145 class bytecode ending, 20 java file ending, 19–20 A Abstract classes, interfaces and, 636–638 Abstract data type (ADT), 319 Abstraction, see Information hiding 933 934 INDEX Accessor (get) methods, 302–305 Action event and listeners, 450 ActionListener interface, 644 actionPerformed method, 451–453, 711 Actual parameters, 288 Addition operator +, 56, 69, 71 Address, main memory, 3–4 ADT stack, 894 Algorithms, 25–26, 206–209, 230, 410–411, 526–527, 529–531, 624–626, 830–831 interchange sorting, 526–527 interfaces, 624–626 loops, 206–209, 230 merge sort, 830–831 programming use of, 25–26, 207 sorting arrays, 526–527, 529–531, 830–831 writing methods, 410–411 Alphabetical order, strings, 154 American Standard Code for Information Interchange (ASCII), 67, 89 Ancestor class, see Base class Appending (adding) to text files, 736–737 Applets,13–14, 30–32, 37–38, 110–113, 241–247, 346–355, 447–467, 548–556, 918–919 buttons, 447–461 class methods and parameters, 346–356 content pane, 353–355 conversion to application, 110–113 event handlers, 449–453 Graphics class methods, 346–351, 553–556 init method, 352–353, 455 Internet use of, 13–14 Java programs, 13–14, 30–32, 37–38, 918–919 labels added to, 352–355 listener objects handlers, 449–453 multifaced (looping and branching), 241–247, 348–351 named constants in, 110 paint method, 32, 352 polygons, drawing, 553–556 programming style rules, 110 running (executing), 37–38, 918–919 text areas, 548–552 Appletviewer, 37–38, 918–919 Applications, 13–19, 30, 110–126 conversion from applet to, 110–113 dialog windows, 113–126 graphical user interface (GUI), 110–126 Java computer programs, 13–19, 30 JFrame class, 110–114 JOptionPane class, 113–122 windowing, 110–126 Arcs drawn in graphics programs, 35–37 Arguments, 16–18, 287–292, 340–343, 503–505 array methods and, 503–505 braces ( ) for Java methods, 16–18 class type variables and, 340–343 indexed variables as, 503–505 methods and, 16–18, 84, 503–508 parameters, 287–292, 340–343, 505–507 primitive type variables and, 287–292 Arithmetic operators, 56–57, 68–81 addition operator +, 56, 69, 71 assignment operators combined with, 72–73 assignment statements and, 56–57, 68–81 binary, 70 decrement operator ––, 79–80 division operator /, 69–70 expressions and, 56–57, 68–81 increment operator ++, 79–80 multiplication operator *, 56, 69 number signs + –, 70–71 operands, 98 parentheses ( ) for, 71–73 precedence rules, 71–72 remainder (modulus) operator %, 70 spacing, 71 subtraction operator -, 56, 69, 71 unary, 70 variable values and, 56–57, 80 Array-based data structures, 849–859 assignment statements for, 858–859 copying, 858–859 for-each loop (statement) for, 858 instantiation, 850–852 list, 850 methods, 852–855 parameterized class, as a, 859 ArrayList class, 850–859 Arrays, 479–573, 776–779, 822–834 accessing, 482–484 arguments and, 503–508 assignment operator = and, 508–511 binary files and, 776–779 brackets [ ] for, 482, 485– 486, 535–536, 538 classes and, 495–503, 515–525 creating, 482–484, 533–536 declaring, 485–488, 533–536 elements, 482–488 equality operator == and, 508–511 graphic applications, 548–556 index (subscript), 482–483, 487 indexed variables, 482–488, 491–493, 503–505 INDEX initializing, 494–495 length instance variable for, 488–490, 539 loops and, 490, 502, 535–536 methods and, 503–508, 511–515 multidimensional, 532–548 naming, 487–488 objects, 776–779 parameters, 505–507 partially filled, 523–524 programming with, 515–525 ragged, 540–542 recursion and, 822–834 returning, 511–513 searching, 531, 822–829 sorting, 525–531, 830–834 strings and, 516 subscript (index), 482–483, 487 ASCII characters, 67, 89, 729, 932 Assembly language, Assertion checks, 239–240 Assignment operator =, 55–56, 72–73, 146, 508–511 Assignment statements, 55–81, 87, 508–511, 858–859 arithmetic operators and, 56–57, 68–81 array-based data structures, 858–859 arrays and, 508–511 assignment operator =, 55–56, 72–73, 508–511 constants (literals) and, 60–63 data type compatibilities, 63–64 decrement operator ––, 79–80 expression values, 55–56 floating-point numbers and, 60–62 increment operator ++, 79–80 input/output (I/O) using, 58–60 primitive data types and, 57 simple input using, 58–59 simple screen output using, 60 String variables and, 87 type casting, 65–67 variable declarations, 57–58 variable values, 55–81 Auxiliary (secondary) memory, 3, B Base (stopping) case, 801–802, 809, 811 Base class (superclass), 579, 584–585, 589–591 class definition, 579 constructors, 589–591 inheritance and, 579, 584– 585, 590 private instance variables and methods of, 584–585 Binary files, 728–729, 751–779 array objects and, 776–779 class objects and, 771–776 end of file errors, 766 EOFException class, 764–765 exceptions in, 764–766, 769–770 ObjectInputStream class, 751–758 ObjectOuputStream class, 758–763 objects and, 771–779 primitive data values, 729, 753–756 reading from, 758–766 storage in, 728–729 strings, writing to, 756–757 writeInt method, 753–757 writeUTF method, 757–758 writing (creating), 751–758 Binary operators, 70 See also Arithmetic operators Binary search, 822–829 Binary trees, 894–895 BlueJ, 917 Body, Java methods, 16, 373 boolean data type, 52 Boolean expressions, 53, 139–142, 145–152, 166–172, 227–229 and (logical) operator, &&, 146–148 boolean operators, 145–151 935 boolean variables, 167–168, 227–229 comparison operators, 145–146 data types, 53, 166–172 equality operator, ==, 145–146, 150–152 floating-point comparisons, 146 greater than operator, >, 145 greater than or equal to operator, >=, 139–140, 145 if-else statements, 139–142, 145–152, 167–168 input/output (I/O) of values, 171–172 less than operator,

Ngày đăng: 09/01/2023, 02:56

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN