id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
20,700 | second_true_statement else false_statement if the first boolean expression is falsethe second boolean expression will be testedand so on an if statement can have an arbitrary number of else if parts for examplethe following is correct if statement if (snowlevel gotoclass()comehome()else if (snowlevel gosledding()havesnowballfight()else stayathome()switch statements java provides for multiple-value control flow using the switch statementwhich is especially useful with enum types the following is an indicative example (based on variable of the day enum type of section switch (dcase mon |
20,701 | breakcase tuesystem out println("this is getting better ")breakcase wedsystem out println("half way there ")breakcase thusystem out println(" can see the light ")breakcase frisystem out println("now we are talking ")breakdefaultsystem out println("day off ")breakthe switch statement evaluates an integer or enum expression and causes control flow to jump to the code location labeled with the value of this expression if there is no matching labelthen control flow jumps to the location labeled "default this is the only explicit jump performed by the switch statementhoweverso flow of control "falls throughto other cases if the code for each case is not ended with break statement (which causes control flow to jump to the next line after the switch statementloops |
20,702 | java provides for three types of loops while loops the simplest kind of loop in java is while loop such loop tests that certain condition is satisfied and will perform the body of the loop each time this condition is evaluated to be true the syntax for such conditional test before loop body is executed is as followswhile (boolean_exploop_statement at the beginning of each iterationthe loop tests the expressionboolean expand then executes the loop bodyloop_statementonly if this boolean expression evaluates to true the loop body statement can also be block of statements considerfor examplea gnome that is trying to water all of the carrots in his carrot patchwhich he does as long as his watering can is not empty since his can might be empty to begin withwe would write the code to perform this task as followspublic void watercarrots (carrot current garden findnextcarrot ()while (!watercan isempty ()water (currentwatercan)current garden findnextcarrot ()recall that "!in java is the "notoperator for loops another kind of loop is thefor loop in their simplest formfor loops provide for repeated code based on an integer index in javawe can do that and much more the functionality of for loop is significantly more flexible in particularthe usage of for loop is split into four sectionsthe initializationthe conditionthe incrementand the body |
20,703 | here is the syntax for java for loopfor (initializationconditionincrementloop_statement where each of the sections initializationconditionand increment can be empty in the initialization sectionwe can declare an index variable that will only exist in the scope of the for loop for exampleif we want loop that indexes on counterand we have no need for the counter variable outside of the for loopthen declaring something like the following for (int counter conditionincrementloop_statement will declare variable counter whose scope is the loop body only in the condition sectionwe specify the repeat (whilecondition of the loop this must be boolean expression the body of the for loop will be executed each time the condition is true when evaluated at the beginning of potential iteration as soon as condition evaluates to falsethen the loop body is not executedandinsteadthe program executes the next statement after the for loop in the increment sectionwe declare the incrementing statement for the loop the incrementing statement can be any legal statementallowing for significant flexibility in coding thusthe syntax of for loop is equivalent to the followinginitializationwhile (conditionloop_statementincrementexcept thatin javaa while loop cannot have an empty boolean conditionwhereas for loop can the following example shows simple for loop in java |
20,704 | numapples apples getnumapples ()for (int numapplesx++eatapple (apples getapple ( ))spitoutcore ()in the java example abovethe loop variable was declared as int before each iterationthe loop tests the condition numapplesand executes the loop body only if this is true finallyat the end of each iteration the loop uses the statement +to increment the loop variable before again testing the condition incidentallysince java also includes for-each loopwhich we discuss in section do-while loops java has yet another kind of loop besides the for loop and the standard while loop--the do-while loop the former loops tests condition before performing an iteration of the loop bodythe do-while loop tests condition after the loop body the syntax for do-while loop is as shown belowdo loop_statement while (boolean_expagainthe loop body statementloop_statementcan be single statement or block of statementsand the conditionalboolean_expmust be boolean expression in do-while loopwe repeat the loop body for as long as the condition is true each time it is evaluated considerfor examplethat we want to prompt the user for input and then do something useful with that input (we discuss java input and output in more detail in section possible conditionin this casefor exiting the loop is when the user enters an empty string howevereven in this casewe may want to handle |
20,705 | illustrates this casepublic void getuserinput(string inputdo input getinputstring()handleinput(input)while (input length()> )notice the exit condition for the above example specificallyit is written to be consistent with the rule in java that do-while loops exit when the condition is not true (unlike the repeat-until construct used in other languagesexplicit control-flow statements java also provides statements that allow for explicit change in the flow of control of program returning from method if java method is declared with return type of voidthen flow of control returns when it reaches the last line of code in the method or when it encounters return statement with no argument if method is declared with return typehoweverthe method is function and it must exit by returning the function' value as an argument to return statement the following (correctexample illustrates returning from function/check for specific birthday public boolean checkbday (int dateif (date =birthdays mikes_bdayreturn truereturn false |
20,706 | it follows that the return statement must be the last statement executed in functionas the rest of the code will never be reached note that there is significant difference between statement being the last line of code that is executed in method and the last line of code in the method itself in the example abovethe line return trueis clearly not the last line of code that is written in the functionbut it may be the last line that is executed (if the condition involving date is truesuch statement explicitly interrupts the flow of control in the method there are two other such explicit control-flow statementswhich are used in conjunction with loops and switch statements the break statement the typical use of break statement has the following simple syntaxbreakit is used to "breakout of the innermost switchforwhileor dowhile statement body when it is executeda break statement causes the flow of control to jump to the next line after the loop or switch to the body containing the break the break statement can also be used in labeled form to jump out of an outernested loop or switch statement in this caseit has the syntax break labelwhere label is java identifier that is used to label loop or switch statement such label can only appear at the beginning of the declaration of loop there are no other kinds of "go tostatements in java we illustrate the use of label with break statement in the following simple examplepublic static boolean haszeroentry (int[][aboolean foundflag falsezerosearchfor (int = < lengthi++for (int = < [ilengthj++ |
20,707 | foundflag truebreak zerosearchreturn foundflagthe example above also uses arrayswhich are covered in section the continue statement the other statement to explicitly change the flow of control in java program is the continue statementwhich has the following syntaxcontinue labelwhere label is an optional java identifier that is used to label loop as mentioned abovethere are no explicit "go tostatements in java likewisethe continue statement can only be used inside loops (forwhileand dowhilethe continue statement causes the execution to skip over the remaining steps of the loop body in the current iteration (but then continue the loop if its condition is satisfied arrays common programming task is to keep track of numbered group of related objects for examplewe may want video game to keep track of the top ten scores for that game rather than use ten different variables for this taskwe would prefer to use single name for the group and use index numbers to refer to the high scores in that group similarlywe may want medical information system to keep track of the patients currently assigned to beds in certain hospital againwe would rather not have to introduce variables in our program just because the hospital has beds in such caseswe can save programming effort by using an arraywhich is numbered collection of variables all of the same type each variableor cellin an array has an indexwhich uniquely refers to the value stored in that cell the cells of |
20,708 | video game in figure figure an illustration of an array of ten (inthigh scores for video game such an organization is quite usefulfor it allows us to do some interesting computations for examplethe following method adds up all the numbers in an array of integers/*adds all the numbers in an integer array *public static int sum(int[aint total for (int = lengthi==/note the use of the length variable total + [ ]return totalthis example takes advantage of nice feature of javawhich allows us to find the number of cells an array storesthat isits length in javaan array is special kind of object and the length of is stored in an instance variablelength that iswe never need to guess the length of an array in javathe length of an array can be accessed as followsarray_name length where array_name is the name of the array thusthe cells of an array are numbered , and so onup to length array elements and capacities each object stored in an array is called an element of that array element number is [ ]element number is [ ]element number is [ ]and so on since the length of an array determines the maximum number of things that can be stored in |
20,709 | another simple use of an array in the following code fragmentwhich counts the number of times certain number appears in an array/*counts the number of times an integer appears in an array *public static int findcount(int[aint kint count for (int ea/note the use of the "foreachloop if ( = /check if the current element equals count++return countout of bounds errors it is dangerous mistake to attempt to index into an array using number outside the range from to length &minus such reference is said to be out of bounds out of bounds references have been exploited numerous times by hackers using method called the buffer overflow attack to compromise the security of computer systems written in languages other than java as safety featurearray indices are always checked in java to see if they are ever out of bounds if an array index is out of boundsthe run-time java environment signals an error condition the name of this condition is the arrayindexoutofboundsexception this check helps java avoid number of security problems (including buffer overflow attacksthat other languages must cope with we can avoid out-of-bounds errors by making sure that we alway index into an arrayausing an integer value between and length one shorthand way we can do this is by carefully using the early termination feature of boolean operations in java for examplea statement like the following will never generate an index out-of-bounds errorif (( > &( [ ] |
20,710 | comparisons succeed declaring arrays one way to declare and initialize an array is as followselement_type[array_name {init_val_ ,init_val_ ,init_val_n- }the element_type can be any java base type or class nameand array_name can be any value java identifier the initial values must be of the same type as the array for exampleconsider the following declaration of an array that is initialized to contain the first ten prime numbersint[primes { }in addition to creating an array and defining all its initial values when we declare itwe can declare an array variable without initializing it the form of this declaration is as followselement_type[array_namean array created in this way is initialized with all zeros if the array type is number type arrays of objects are initialized to all null references once we have declared an array in this waywe can create the collection of cells for an array later using the following syntaxnew element_type[lengthwhere length is positive integer denoting the length of the array created typically this expression appears in an assignment statement with an array name on the left hand side of the assignment operator sofor examplethe following statement defines an array variable named aand later assigns it an array of cellseach of type doublewhich it then initializesdouble[ /various steps new double[ ]for (int = lengthk++ [ |
20,711 | (recall that arrays in java always start indexing at )andlike every array in javaall the cells in this array are of the same type--double arrays are objects arrays in java are special kinds of objects in factthis is the reason we can use the new operator to create new instance of an array an array can be used just like any general object in javabut we have special syntax (using square brackets"[and "]"to refer to its members an array in java can do everything that general object can since an array is an objectthoughthe name of an array in java is actually reference to the place in memory where the array is stored thusthere is nothing too special about using the dot operator and the instance variablelengthto refer to the length of an arrayfor exampleas " length the nameain this case is just referenceor pointerto the underlying array object the fact that arrays in java are objects has an important implication when it comes to using array names in assignment statements for when we write something like ain java programwe really mean that and now both refer to the same array soif we then write something like [ then we will also be setting the number [ to we illustrate this crucial point in figure figure an illustration of an assignment of array objects we show the result of setting " [ ;after previously setting " ; |
20,712 | if insteadwe wanted to create an exact copy of the arrayaand assign that array to the array variablebwe should write clone()which copies all of the cells of into new array and assigns to point to that new array in factthe clone method is built-in method of every java objectwhich makes an exact copy of that object in this caseif we then write [ then the new (copiedarray will have its cell at index assigned the value but [ will remain unchanged we illustrate this point in figure figure an illustration of cloning of array objects we show the result of setting " [ ;after previously setting " clone();we should stress that the cells of an array are copied when we clone it if the cells are base typelike inttheir values are copied but if the cells are object referencesthen those references are copied this means that there are now two |
20,713 | exercise - simple input and output java provides rich set of classes and methods for performing input and output within program there are classes in java for doing graphical user interface designcomplete with pop-up windows and pull-down menusas well as methods for the display and input of text and numbers java also provides methods for dealing with graphical objectsimagessoundsweb pagesand mouse events (such as clicksmouse oversand draggingmoreovermany of these input and output methods can be used in either stand-alone programs or in applets unfortunatelygoing into the details on how all of the methods work for constructing sophisticated graphical user interfaces is beyond the scope of this book stillfor the sake of completenesswe describe how simple input and output can be done in java in this section simple input and output in java occurs within the java console window depending on the java environment we are usingthis window is either special pop-up window that can be used for displaying and inputting textor window used to issue commands to the operating system (such windows are referred to as shell windowsdos windowsor terminal windowssimple output methods java provides built-in static objectcalled system outthat performs output to the "standard outputdevice most operating system shells allow users to redirect standard output to files or even as input to other programsbut the default output is to the java console window the system out object is an instance of the java io printstream class this class defines methods for buffered output streammeaning that characters are put in temporary locationcalled bufferwhich is then emptied when the console window is ready to print characters specificallythe java io printstream class provides the following methods for performing simple output (we use base_type here to refer to any of the possible base types)print(object )print the object using its tostring method print(string )print the string print(base_type )print the base type value println(string )print the string sfollowed by the newline character |
20,714 | considerfor examplethe following code fragmentsystem out print("java values")system out print( )system out print(',')system out print( )system out println((double,char,int")when executedthis fragment will output the following in the java console windowjava values , (double,char,intsimple input using the java util scanner class just as there is special object for performing output to the java console windowthere is also special objectcalled system infor performing input from the java console window technicallythe input is actually coming from the "standard inputdevicewhich by default is the computer keyboard echoing its characters in the java console the system in object is an object associated with the standard input device simple way of reading input with this object is to use it to create scanner objectusing the expression new scanner(system inthe scanner class has number of convenient included methods that read from the given input stream for examplethe following program uses scanner object to process inputimport java io *import java util scannerpublic class inputexample public static void main(string args[]throws ioexception scanner new scanner(system in)system out print("enter your height in centimeters") |
20,715 | system out print("enter your weight in kilograms")float weight nextfloat()float bmi weight/(height*height)* system out println("your body mass index is bmi ")when executedthis program could produce the following on the java consoleenter your height in centimeters: enter your weight in kilograms your body mass index is java util scanner methods the scanner class reads the input stream and divides it into tokenswhich are contiguous strings of characters separated by delimiterswhich are special separating characters the default delimiter is whitespacethat istokens are separated by strings of spacestabsand newlinesby default tokens can either be read immediately as strings or scanner object can convert token to base typeif the token is in the right syntax specificallythe scanner class includes the following methods for dealing with tokenshasnext()return true if and only if there is another token in the input stream next()return the next token string in the input streamgenerate an error if there are no more tokens left hasnexttype()return true if and only if there is another token in the input stream and it can be interpreted as the corresponding base typetypewhere type can be booleanbytedoublefloatintlongor short nexttype()return the next token in the input streamreturned as the base type corresponding to typegenerate an error if there are no more tokens left or if the next token cannot be interpreted as base type corresponding to type |
20,716 | and even look for patterns within lines while doing so the methods for processing input in this way include the followinghasnextline()returns true if and only if the input stream has another line of text nextline()advances the input past the current line ending and returns the input that was skipped findinline(string )attempts to find string matching the (regular expressionpattern in the current line if the pattern is foundit is returned and the scanner advances to the first character after this match if the pattern is not foundthe scanner returns null and doesn' advance these methods can be used with those aboveas wellas in the followingscanner input new scanner(system in)system out print("please enter an integer")while (!input hasnextint()input nextline()system out print("thats not an integerplease enter an integer")int input nextint() an example program in this sectionwe describe simple example java program that illustrates many of the constructs defined above our example consists of two classesonecreditcardthat defines credit card objectsand anothertestthat tests the functionality of creditcard class the credit card objects defined by the creditcard class are simplified versions of traditional credit cards they have identifying numbersidentifying information about their owners and their issuing bankand information about their current balance and credit limit they do not charge interest or late paymentshoweverbut they do restrict charges that would cause card' balance to go over its spending limit the creditcard class |
20,717 | creditcard class defines five instance variablesall of which are private to the classand it provides simple constructor that initializes these instance variables it also defines five accessor methods that provide access to the current values of these instance variables of coursewe could have alternatively defined the instance variables as being publicwhich would have made the accessor methods moot the disadvantage with this direct approachhoweveris that it allows users to modify an object' instance variables directlywhereas in many cases such as thiswe prefer to restrict the modification of instance variables to special update methods we include two such update methodschargeit and makepayment in code fragment in additionit is often convenient to include action methodswhich define specific actions for that object' behavior to demonstratewe have defined such an action methodthe printcard methodas static methodwhich is also included in code fragment the test class we test the creditcard class in test class note the use of an arraywalletof creditcard objects hereand how we are using iteration to make charges and payments we show the complete code for the test class in code fragment for simplicity' sakethe test class does not do any fancy graphical outputbut simply sends its output to the java console we show this output in code fragment note the difference between the way we utilize the nonstatic chargeit and make-payment methods and the static printcard method code fragment the creditcard class |
20,718 | the test class |
20,719 | output from the test class |
20,720 | nested classes and packages the java language takes general and useful approach to the organization of classes into programs every stand-alone public class defined in java must be given in separate file the file name is the name of the class with java extension so classpublic class smartboardis defined in filesmartboard java in this sectionwe describe two ways that java allows multiple classes to be organized in meaningful ways nested classes java allows class definitions to be placed insidethat isnested inside the definitions of other classes this is useful constructwhich we will exploit several times in this book in the implementation of data structures the main use for such nested classes is to define class that is strongly affiliated with another class for example |
20,721 | class as nested class inside the definition of the text editor class keeps these two highly related classes together in the same file moreoverit also allows each of them to access nonpublic methods of the other one technical point regarding nested classes is that the nested class should be declared as static this declaration implies that the nested class is associated with the outer classnot an instance of the outer classthat isa specific object packages set of classesall defined in common subdirectorycan be java package every file in package starts with the linepackage package_namethe subdirectory containing the package must be named the same as the package we can also define package in single file that contains several class definitionsbut when it is compiledall the classes will be compiled into separate files in the same subdirectory in javawe can use classes that are defined in other packages by prefixing class names with dots (that isusing the characterthat correspond to the other packagesdirectory structures public boolean temperature(ta measures thermometer thermometerint temperature/the function temperature takes class thermometer as parameter thermometer is defined in the ta package in subpackage called measures the dots in ta measures thermometer correspond directly to the directory structure in the ta package all the extra typing needed to refer to class outside of the current package can get tiring in javawe can use the import keyword to include external classes or entire packages in the current file to import an individual class from specific packagewe type the following at the beginning of the fileimport packagename classnamesfor examplewe could type |
20,722 | import ta measures thermometerimport ta measures scaleat the beginning of project package to indicate that we are importing the classes named ta measures thermometer and ta measures scale the java run-time environment will now search these classes to match identifiers to classesmethodsand instance variables that we use in our program we can also import an entire packageby using the following syntaximport *for examplepackage studentimport ta measures *public boolean temperature(thermometer thermometerint temperature/in the case where two packages have classes of the same namewe must specifically reference the package that contains class for examplesuppose both the package gnomes and package cooking have class named mushroom if we provide an import statement for both packagesthen we must specify which class we mean as followsgnomes mushroom shroom new gnomes mushroom ("purple")cooking mushroom topping new cooking mushroom ()if we do not specify the package (that isin the previous example we just use variable of type mushroom)the compiler will give an "ambiguous classerror to sum up the structure of java programwe can have instance variables and methods inside classand classes inside package writing java program |
20,723 | design coding testing and debugging we briefly discuss each of these steps in this section design the design step is perhaps the most important step in the process of writing program for it is in the design step that we decide how to divide the workings of our program into classeswe decide how these classes will interactwhat data each will storeand what actions each will perform indeedone of the main challenges that beginning java programmers face is deciding what classes to define to do the work of their program while general prescriptions are hard to come bythere are some general rules of thumb that we can apply when determining how to define our classesresponsibilitiesdivide the work into different actorseach with different responsibility try to describe responsibilities using action verbs these actors will form the classes for the program independencedefine the work for each class to be as independent from other classes as possible subdivide responsibilities between classes so that each class has autonomy over some aspect of the program give data (as instance variablesto the class that has jurisdiction over the actions that require access to this data behaviorsso that the consequences of each action performed by class will be well understood by other classes that interact with itdefine the behaviors for each class carefully and precisely these behaviors will define the methods that this class performs the set of behaviors for class is sometimes referred to as protocolfor we expect the behaviors for class to hold together as cohesive unit defining the classestogether with their instance variables and methodsdetermines the design of java program good programmer will naturally develop greater skill in performing these tasks over timeas experience teaches him or her to notice patterns in the requirements of program that match patterns that he or she has seen before pseudo-code |
20,724 | human eyes onlyprior to writing actual code such descriptions are called pseudocode pseudo-code is not computer programbut is more structured than usual prose pseudo-code is mixture of natural language and high-level programming constructs that describe the main ideas behind generic implementation of data structure or algorithm there really is no precise definition ofthe pseudo-code languagehoweverbecause of its reliance on natural language at the same timeto help achieve claritypseudo-code mixes natural language with standard programming language constructs the programming language constructs we choose are those consistent with modern high-level languages such as cc++and java these constructs include the followingexpressionswe use standard mathematical symbols to express numeric and boolean expressions we use the left arrow sign (-as the assignment operator in assignment statements (equivalent to the operator in javaand we use the equal sign (=as the equality relation in boolean expressions (equivalent to the "==relation in javamethod declarationsalgorithm name(param par am declares new method "nameand its parameters decision structuresif condition then true-actions [else false-actionswe use indentation to indicate what actions should be included in the true-actions and false-actions while-loopswhile condition do actions we use indentation to indicate what actions should be included in the loop actions repeat-loopsrepeat actions until condition we use indentation to indicate what actions should be included in the loop actions for-loopsfor variable-increment-definition do actions we use indentation to indicate what actions should be included among the loop actions array indexinga[irepresents the ith cell in the array the cells of an -celled array are indexed from [ to [ (consistent with javamethod callsobject method(args(object is optional if it is understoodmethod returnsreturn value this operation returns the value specified to the method that called this one commentscomment goes here we enclose comments in braces when we write pseudo-codewe must keep in mind that we are writing for human readernot computer thuswe should strive to communicate high-level ideasnot |
20,725 | important steps like many forms of human communicationfinding the right balance is an important skill that is refined through practice coding as mentioned aboveone of the key steps in coding up an object-oriented program is coding up the descriptions of classes and their respective data and methods in order to accelerate the development of this skillwe discuss various design patterns for designing object-oriented programs (see section at various points throughout this text these patterns provide templates for defining classes and the interactions between these classes many programmers do their initial coding not on computerbut by using crc cards component-responsibility-collaboratoror crc cardsare simple index cards that subdivide the work required of program the main idea behind this tool is to have each card represent componentwhich will ultimately become class in our program we write the name of each component on the top of an index card on the left-hand side of the cardwe begin writing the responsibilities for this component on the right-hand sidewe list the collaborators for this componentthat isthe other components that this component will have to interact with to perform its duties the design process iterates through an action/actor cyclewhere we first identify an action (that isa responsibility)and we then determine an actor (that isa componentthat is best suited to perform that action the design is complete when we have assigned all actions to actors by the wayin using index cards to begin our codingwe are assuming that each component will have small set of responsibilities and collaborators this assumption is no accidentfor it helps keep our programs manageable an alternative to crc cards is the use of uml (unified modeling languagediagrams to express the organization of programand the use of pseudo-code to describe the algorithms uml diagrams are standard visual notation to express object-oriented software designs several computer-aided tools are available to build uml diagrams describing algorithms in pseudo-codeon the other handis technique that we utilize throughout this book once we have decided on the classes for our program and their responsibilitieswe are ready to begin the actual coding on computer we create the actual code for the classes in our program by using either an independent text editor (such as emacswordpador vi)or the editor embedded in an integrated development environment (ide)such as eclipse or borland jbuilder once we have completed coding for class (or package)we compile this file into working code by invoking compiler if we are not using an idethen we compile our program by calling programsuch as javacon our file if we are using an |
20,726 | if we are fortunateand our program has no syntax errorsthen this compilation process will create files with classextension if our program contains syntax errorsthen these will be identifiedand we will have to go back into our editor to fix the offending lines of code once we have eliminated all syntax errorsand created the appropriate compiled codewe can run our program by either invoking commandsuch as "java(outside an ide)or by clicking on the appropriate "runbutton (within an idewhen java program is run in this waythe run-time environment locates the directories containing the named class and any other classes that are referenced from this class according to special operating system environment variable this variable is named "classpath,and the ordering of directories to search in is given as list of directorieswhich are separated by colons in unix/linux or semicolons in dos/windows an example classpath assignment in the dos/windows operating system could be the followingset classpath; :\java; :\program files\javawhereas an example classpath assignment in the unix/linux operating system could be the followingsetenv classpath :/usr/local/java/lib:/usr/netscape/classesin both casesthe dot ("refers to the current directory in which the run-time environment is invoked javadoc in order to encourage good use of block comments and the automatic production of documentationthe java programming environment comes with documentation production program called javadoc this program takes collection of java source files that have been commented using certain keywordscalled tagsand it produces series of html documents that describe the classesmethodsvariablesand constants contained in these files for space reasonswe have not used javadocstyle comments in all the example programs included in this bookbut we include javadoc example in code fragment as well as other examples at the web site that accompanies this book each javadoc comment is block comment that starts with "/**and ends with "*/,and each line between these two can begin with single asterisk"*,which is ignored the block comment is assumed to start with descriptive sentencefollowed by blank linewhich is followed by special lines that begin with javadoc tags block comment that comes just before class definitioninstance |
20,727 | comment about that classvariableor method code fragment an example class definition using javadoc-style comments note that this class includes two instance variablesone constructorand two accessor methods |
20,728 | @author textidentifies each author (one per linefor class |
20,729 | @exception exception-name descriptionidentifies an error condition that is signaled by this method (see section @param parameter-name descriptionidentifies parameter accepted by this method @return descriptiondescribes the return type and its range of values for method there are other tags as wellthe interested reader is referred to on-line documentation for javadoc for further discussion readability and style programs should be made easy to read and understand good programmers should therefore be mindful of their coding styleand develop style that communicates the important aspects of program' design for both humans and computers much has been written about good coding stylewith some of the main principles being the followinguse meaningful names for identifiers try to choose names that can be read aloudand choose names that reflect the actionresponsibilityor data each identifier is naming the tradition in most java circles is to capitalize the first letter of each word in an identifierexcept for the first word in an identifier for variable or method soin this tradition"date,"vector,"devicemanagerwould identify classesand 'isfull(),"insertitem(),"studentname,and "studentheightwould respectively identify methods and variables use named constants or enum types instead of literals readabilityrobustnessand modifiability are enhanced if we include series of definitions of named constant values in class definition these can then be used within this class and others to refer to special values for this class the tradition in java is to fully capitalize such constantsas shown belowpublic class student public static final int mincredits /min credits in term public static final int maxcredits /max credits in term public static final int freshman /code for freshman |
20,730 | sophomore public static final int junior /code for junior public static final int senior /code for senior /instance variablesconstructorsand method definitions go here indent statement blocks typically programmers indent each statement block by spacesin this book we typically use spaceshoweverto avoid having our code overrun the book' margins organize each class in the following order constants instance variables constructors methods we note that some java programmers prefer to put instance variable definitions last we put them earlier so that we can read each class sequentially and understand the data each method is working with use comments that add meaning to program and explain ambiguous or confusing constructs in-line comments are good for quick explanations and do not need to be sentences block comments are good for explaining the purpose of method and complex code sections testing and debugging testing is the process of experimentally checking the correctness of programwhile debugging is the process of tracking the execution of program and discovering the errors in it testing and debugging are often the most timeconsuming activity in the development of program testing |
20,731 | the correctness of program over all possible inputs is usually infeasiblewe should aim at executing the program on representative subset of inputs at the very minimumwe should make sure that every method in the program is tested at least once (method coverageeven bettereach code statement in the program should be executed at least once (statement coverageprograms often tend to fail on special cases of the input such cases need to be carefully identified and tested for examplewhen testing method that sorts (that isputs in orderan array of integerswe should consider the following inputsthe array has zero length (no elementsthe array has one element all the elements of the array are the same the array is already sorted the array is reverse sorted in addition to special inputs to the programwe should also consider special conditions for the structures used by the program for exampleif we use an array to store datawe should make sure that boundary casessuch as inserting/removing at the beginning or end of the subarray holding dataare properly handled while it is essential to use hand-crafted test suitesit is also advantageous to run the program on large collection of randomly generated inputs the random class in the java util package provides several methods to generate random numbers there is hierarchy among the classes and methods of program induced by the caller-callee relationship namelya method is above method in the hierarchy if calls there are two main testing strategiestop-down and bottom-upwhich differ in the order in which methods are tested bottom-up testing proceeds from lower-level methods to higher-level methods namelybottom-level methodswhich do not invoke other methodsare tested firstfollowed by methods that call only bottom-level methodsand so on this strategy ensures that errors found in method are not likely to be caused by lower-level methods nested within it top-down testing proceeds from the top to the bottom of the method hierarchy it is typically used in conjunction with stubbinga boot-strapping technique that replaces lower-level method with stuba replacement for the method that simulates the output of the original method for exampleif method calls |
20,732 | that returns fixed string debugging the simplest debugging technique consists of using print statements (using method system out println(string)to track the values of variables during the execution of the program problem with this approach is that the print statements need to be eventually removed or commented out before the software is finally released better approach is to run the program within debuggerwhich is specialized environment for controlling and monitoring the execution of program the basic functionality provided by debugger is the insertion of breakpoints within the code when the program is executed within the debuggerit stops at each breakpoint while the program is stoppedthe current value of variables can be inspected in addition to fixed breakpointsadvanced debuggers allow for specification of conditional breakpointswhich are triggered only if given expression is satisfied the standard java tools include basic debugger called jdbwhich is commandline oriented ides for java programming provide advanced debugging environments with graphical user interfaces exercises for source code and help with exercisesplease visit java datastructures net reinforcement - suppose that we create an array of gameentry objectswhich has an integer scores fieldand we clone and store the result in an array if we then immediately set [ score equal to what is the score value of the gameentry object referenced by [ ] - |
20,733 | each payment - modify the creditcard class from code fragment to charge late fee for any payment that is past its due date - modify the creditcard class from code fragment to include modifier methodswhich allow user to modify internal variables in creditcard class in controlled manner - modify the declaration of the first for loop in the test class in code fragment so that its charges will eventually cause exactly one of the three credit cards to go over its credit limit which credit card is itr- write short java functioninputallbasetypesthat inputs different value of each base type from the standard input device and prints it back to the standard output device - write java classflowerthat has three instance variables of type stringintand floatwhich respectively represent the name of the flowerits number of pedalsand price your class must include constructor method that initializes each variable to an appropriate valueand your class should include methods for setting the value of each typeand getting the value of each type - write short java functionismultiplethat takes two long valuesn and mand returns true if and only if is multiple of mthat isn mi for some integer - write short java functionisoddthat takes an int and returns true if and only if is odd your function cannot use the multiplicationmodulusor division operatorshowever - |
20,734 | integers smaller than - write short java function that takes an integer and returns the sum of all the odd integers smaller than creativity - write short java function that takes an array of int values and determines if there is pair of numbers in the array whose product is odd - write java method that takes an array of int values and determines if all the numbers are different from each other (that isthey are distinctc- write java method that takes an array containing the set of all integers in the range to and shuffles it into random order your method should output each possible order with equal probability - write short java program that outputs all possible strings formed by using the characters ' '' '' ' ' 'and 'nexactly once - write short java program that takes all the lines input to standard input and writes them to standard output in reverse order that iseach line is output in the correct orderbut the ordering of the lines is reversed - write short java program that takes two arrays and of length storing int valuesand returns the dot product of and that isit returns an array of length such that [ia[ib[ ]for , projects - |
20,735 | times write java stand-alone program that will write out the following sentence one hundred times" will never spam my friends again your program should number each of the sentences and it should make eight different random-looking typos - (for those who know java graphical user interface methodsdefine graphicaltest class that tests the functionality of the creditcard class from code fragment using text fields and buttons - the birthday paradox says that the probability that two people in room will have the same birthday is more than half as long as nthe number of people in the roomis more than this property is not really paradoxbut many people find it surprising design java program that can test this paradox by series of experiments on randomly generated birthdayswhich test this paradox for , , , notes for more detailed information about the java programming languagewe refer the reader to some of the fine books about javaincluding the books by arnold and gosling [ ]cam-pione and walrath [ ]cornell and horstmann [ ]flanagan [ ]and horstmann [ ]as well as sun' java web site ( |
20,736 | object-oriented design contents goalsprinciplesand patterns object-oriented design goals |
20,737 | design patterns inheritance and polymorphism inheritance polymorphism using inheritance in java exceptions throwing exceptions catching exceptions |
20,738 | interfaces and abstract classes implementing interfaces multiple inheritance in interfaces abstract classes and strong typing casting and generics casting generics exercises |
20,739 | goalsprinciplesand patterns as the name impliesthe main "actorsin the object-oriented design paradigm are called objects an object comes from classwhich is specification of the data fieldsalso called instance variablesthat the object containsas well as the methods (operationsthat the object can execute each class presents to the outside world concise and consistent view of the objects that are instances of this classwithout going into too much unnecessary detail or giving others access to the inner workings of the objects this view of computing is intended to fulfill several goals and incorporate several design principleswhich we discuss in this object-oriented design goals software implementations should achieve robustnessadaptabilityand reusability (see figure figure goals of object-oriented design robustness every good programmer wants to develop software that is correctwhich means that program produces the right output for all the anticipated inputs in the program' application in additionwe want software to be robustthat iscapable of handling unexpected inputs that are not explicitly defined for its application for exampleif program is expecting positive integer (for examplerepresenting the price of an itemand instead is given negative integerthen the program should be able to recover gracefully from this error more importantlyin life-critical applicationswhere software error can lead to injury or loss of lifesoftware that is not robust could be deadly this point was driven home in the late in accidents involving therac- radiation-therapy machinewhich |
20,740 | complications resulting from their radiation overdose all six accidents were traced to software errors adaptability modern software applicationssuch as web browsers and internet search enginestypically involve large programs that are used for many years softwarethereforeneeds to be able to evolve over time in response to changing conditions in its environment thusanother important goal of quality software is that it achieves adaptability (also called evolvabilityrelated to this concept is portabilitywhich is the ability of software to run with minimal change on different hardware and operating system platforms an advantage of writing software in java is the portability provided by the language itself reusability going hand in hand with adaptability is the desire that software be reusablethat isthe same code should be usable as component of different systems in various applications developing quality software can be an expensive enterpriseand its cost can be offset somewhat if the software is designed in way that makes it easily reusable in future applications such reuse should be done with carehoweverfor one of the major sources of software errors in the therac- came from inappropriate reuse of software from the therac- (which was not objectoriented and not designed for the hardware platform used with the therac- object-oriented design principles chief among the principles of the object-oriented approachwhich are intended to facilitate the goals outlined aboveare the following (see figure )abstraction encapsulation modularity figure principles of object-oriented design |
20,741 | the notion of abstraction is to distill complicated system down to its most fundamental parts and describe these parts in simpleprecise language typicallydescribing the parts of system involves naming them and explaining their functionality applying the abstraction paradigm to the design of data structures gives rise to abstract data types (adtsan adt is mathematical model of data structure that specifies the type of data storedthe operations supported on themand the types of parameters of the operations an adt specifies what each operation doesbut not how it does it in javaan adt can be expressed by an interfacewhich is simply list of method declarationswhere each method has an empty body (we say more about java interfaces in section an adt is realized by concrete data structurewhich is modeled in java by class class defines the data being stored and the operations supported by the objects that are instances of the class alsounlike interfacesclasses specify how the operations are performed in the body of each method java class is said to implement an interface if its methods include all the methods declared in the interfacethus providing body for them howevera class can have more methods than those of the interface encapsulation another important principle of object-oriented design is the concept of encapsulationwhich states that different components of software system should not reveal the internal details of their respective implementations one of the main advantages of encapsulation is that it gives the programmer freedom in implementing the details of system the only constraint on the programmer is to maintain the abstract interface that outsiders see |
20,742 | in addition to abstraction and encapsulationa fundamental principle of object oriented design is modularity modern software systems typically consist of several different components that must interact correctly in order for the entire system to work properly keeping these interactions straight requires that these different components be well organized in object-oriented designthis code structuring approach centers around the concept of modularity modularity refers to an organizing principle for code in which different components of software system are divided into separate functional units hierarchical organization the structure imposed by modularity helps to enable software reusability if software modules are written in an abstract way to solve general problemsthen modules can be reused when instances of these same general problems arise in other contexts for examplethe structural definition of wall is the same from house to housetypically being defined in terms of by -inch studsspaced certain distance apartetc thusan organized architect can reuse his or her wall definitions from one house to another in reusing such definitionsome parts may require redefinitionfor examplea wall in commercial building may be similar to that of housebut the electrical system and stud material might be different natural way to organize various structural components of software package is in hierarchical fashionwhich groups similar abstract definitions together in level-by-level manner that goes from specific to more general as one traverses up the hierarchy common use of such hierarchies is in an organizational chartwhere each link going up can be read as "is ,as in " ranch is house is building this kind of hierarchy is useful in software designfor it groups together common functionality at the most general leveland views specialized behavior as an extension of the general one figure an example of an "is ahierarchy involving architectural buildings |
20,743 | one of the advantages of object-oriented design is that it facilitates reusablerobustand adaptable software designing good code takes more than simply understanding object-oriented methodologieshowever it requires the effective use of objectoriented design techniques computing researchers and practitioners have developed variety of organizational concepts and methodologies for designing quality object-oriented software that is concisecorrectand reusable of special relevance to this book is the concept of design patternwhich describes solution to "typicalsoftware design problem pattern provides general template for solution that can be applied in many different situations it describes the main elements of solution in an abstract way that can be specialized for specific problem at hand it consists of namewhich identifies the patterna contextwhich describes the scenarios for which this pattern can be applieda templatewhich describes how the pattern is appliedand resultwhich describes and analyzes what the pattern produces we present several design patterns in this bookand we show how they can be consistently applied to implementations of data structures and algorithms these design patterns fall into two groups--patterns for solving algorithm design problems and patterns for solving software engineering problems some of the algorithm design patterns we discuss include the followingrecursion (section amortization (section |
20,744 | divide-and-conquer (section prune-and-searchalso known as decrease-and-conquer (section brute force (section the greedy method (section dynamic programming (section likewisesome of the software engineering design patterns we discuss includeposition (section adapter (section iterator (section template method (sections and composition (section comparator (section decorator (section rather than explain each of these concepts herehoweverwe introduce them throughout the text as noted above for each patternbe it for algorithm engineering or software engineeringwe explain its general use and we illustrate it with at least one concrete example inheritance and polymorphism to take advantage of hierarchical relationshipswhich are common in software projectsthe object-oriented design approach provides ways of reusing code inheritance the object-oriented paradigm provides modular and hierarchical organizing structure for reusing codethrough technique called inheritance this technique allows the design of general classes that can be specialized to more particular classeswith the specialized classes reusing the code from the general class the general classwhich is also known as base class or superclasscan define standard instance variables and methods that apply in multitude of situations class that specializesor extendsor inherits froma superclass need not give new implementations for the general methodsfor it inherits them it should only define those methods that are specialized for this particular subclass |
20,745 | methodsa() ()and (suppose we were to define classt that extendss and includes an additional fieldyand two methodsd(ande(the classt would theninherit the instance variablex and the methodsa() ()andc(froms we illustrate the relationships between the classs and the classt in aclass inheritance diagram in figure each box in such diagram denotes classwith its namefields (or instance variables)and methods included as subrectangles figure class inheritance diagram each box denotes classwith its namefieldsand methodsand an arrow between boxes denotes an inheritance relation object creation and referencing when an object is createdmemory is allocated for its data fieldsand these same fields are initialized to specific beginning values typicallyone associates the new object with variablewhich serves as "linkto object oand is said to reference when we wish to access object (for the purpose of getting at its fields or executing its methods)we can either request the execution of one of ' methods (defined by the class that belongs to)or look up one of the fields of indeedthe primary way that an object interacts with another object is for to |
20,746 | description of itselffor to convert itself to stringor for to return the value of one of its data fields the secondary way that can interact with is for to access one of ' fields directlybut only if has given other objects like permission to do so for examplean instance of the java class integer storesas an instance variablean integerand it provides several operations for accessing this dataincluding methods for converting it into other number typesfor converting it to string of digitsand for converting strings of digits to number it does not allow for direct access of its instance variablehoweverfor such details are hidden dynamic dispatch when program wishes to invoke certain method (of some object oit sends message to owhich is usually denotedusing the dot-operator syntax (section )as " (in the compiled version of this programthe code corresponding to this invocation directs the run-time environment to examine ' class to determine if the class supports an (methodandif soto execute it specificallythe run-time environment examines the class to see if it defines an (method itself if it doesthen this method is executed if does not define an (methodthen the run-time environment examines the superclass of if defines ()then this method is executed if does not define ()on the other handthen the run-time environment repeats the search at the superclass of this search continues up the hierarchy of classes until it either finds an (methodwhich is then executedor it reaches topmost class (for examplethe object class in javawithout an (methodwhich generates run-time error the algorithm that processes the message (to find the specific method to invoke is called the dynamic dispatch (or dynamic bindingalgorithmwhich provides an effective mechanism for locating reused software it also allows for another powerful technique of object-oriented programming--polymorphism polymorphism literally"polymorphismmeans "many forms in the context of object-oriented designit refers to the ability of an object variable to take different forms objectoriented languagessuch as javaaddress objects using reference variables the reference variable must define which class of objects it is allowed to refer toin terms of some class but this implies that can also refer to any object belonging to class that extends now consider what happens if defines an (method and also defines an (method the dynamic dispatch algorithm for method invocation always starts its search from the most restrictive class that applies when refers to an object from class tthen it will use ' (method when asked for ()not ' in this caset is said to override method (from alternativelywhen refers to an object from class (that is not also object)it will execute |
20,747 | because the caller of (does not have to know whether the object refers to an instance of or in order to get the (method to execute correctly thusthe object variable can be polymorphicor take many formsdepending on the specific class of the objects it is referring to this kind of functionality allows specialized class to extend class sinherit the standard methods from sand redefine other methods from to account for specific properties of objects of some object-oriented languagessuch as javaalso provide useful technique related to polymorphismwhich is called method overloading overloading occurs when single class has multiple methods with the same nameprovided each one has different signature the signature of method is combination of its name and the type and number of arguments that are passed to it thuseven though multiple methods in class can have the same namethey can be distinguished by compilerprovided they have different signaturesthat isare different in actuality in languages that allow for method overloadingthe run-time environment determines which actual method to invoke for specific method call by searching up the class hierarchy to find the first method with signature matching the method being invoked for examplesuppose class twhich defines method ()extends class uwhich defines method ( ,yif an object from class receives the message " ( , ),then it is ' version of method that is invoked (with the two parameters and ythustrue polymorphism applies only to methods that have the same signaturebut are defined in different classes inheritancepolymorphismand method overloading support the development of reusable software we can define classes that inherit the standard instance variables and methods and can then define new more-specific instance variables and methods that deal with special aspects of objects of the new class using inheritance in java there are two primary ways of using inheritance of classes in javaspecialization and extension specialization in using specialization we are specializing general class to particular subclasses such subclasses typically possess an "is arelationship to their superclass subclass then inherits all the methods of the superclass for each inherited methodif that method operates correctly independent of whether it is operating for specializationno additional work is needed ifon the other handa general method of the superclass would not work correctly on the subclassthen we should override the method to have the correct functionality for the subclass for examplewe could have general classdogwhich has method drink and method sniff specializing this class to bloodhound class would probably not |
20,748 | same way but it could require that we override the sniff methodas bloodhound has much more sensitive sense of smell than standard dog in this waythe bloodhound class specializes the methods of its superclassdog extension in using extensionon the other handwe utilize inheritance to reuse the code written for methods of the superclassbut we then add new methods that are not present in the superclassso as to extend its functionality for examplereturning to our dog classwe might wish to create subclassbordercolliewhich inherits all the standard methods of the dog classbut then adds new methodherdsince border collies have herding instinct that is not present in standard dogs by adding the new methodwe are extending the functionality of standard dog in javaeach class can extend exactly one other class even if class definition makes no explicit use of the extends clauseit still inherits from exactly one other classwhich in this case is class java lang object because of this propertyjava is said to allow only for single inheritance among classes types of method overriding inside the declaration of new classjava uses two kinds of method overridingrefinement and replacement in the replacement type of overridinga method completely replaces the method of the superclass that it is overriding (as in the sniff method of bloodhound mentioned abovein javaall regular methods of class utilize this type of overriding behavior in the refinement type of overridinghowevera method does not replace the method of its superclassbut instead adds additional code to that of its superclass in javaall constructors utilize the refinement type of overridinga scheme called constructor chaining namelya constructor begins its execution by calling constructor of the superclass this call can be made explicitly or implicitly to call constructor of the superclass explicitlywe use the keyword super to refer to the superclass (for examplesuper(calls the constructor of the superclass with no arguments if no explicit call is made in the body of constructorhoweverthe compiler automatically insertsas the first line of the constructora call to super((there is an exception to this general rulewhich is discussed in the next section summarizingin javaconstructors use the refinement type of method overriding whereas regular methods use replacement the keyword this |
20,749 | that class java provides keywordcalled thisfor such reference reference this is usefulfor exampleif we would like to pass the current object as parameter to some method another application of this is to reference field inside the current object that has name clash with variable defined in the current blockas shown in the program given in code fragment code fragment sample program illustrating the use of reference this to disambiguate between field of the current object and local variable with the same name when this program is executedit prints the followingthe dog local variable = the dog field an illustration of inheritance in java to make some of the notions above about inheritance and polymorphism more concretelet us consider some simple examples in java in particularwe consider series of several classes for stepping through and printing out numeric progressions numeric progression is sequence of numberswhere each number depends on one or more of the previous numbers for examplean arithmetic progression determines the next number by addition and geometric progression determines the next number by multiplication in |
20,750 | way of identifying the current value as well we begin by defining classprogressionshown in code fragment which defines the standard fields and methods of numeric progression specificallyit defines the following two long-integer fieldsfirstfirst value of the progressioncurcurrent value of the progressionand the following three methodsfirstvalue()reset the progression to the first valueand return that value nextvalue()step the progression to the next value and return that value printprogression( )reset the progression and print the first values of the progression we say that the method printprogression has no output in the sense that it does not return any valuewhereas the methods firstvalue and nextvalue both return long-integer values that isfirstvalue and nextvalue are functionsand printprogression is procedure the progression class also includes method progression()which is constructor recall that constructors set up all the instance variables at the time an object of this class is created the progression class is meant to be general superclass from which specialized classes inheritso this constructor is code that will be included in the constructors for each class that extends the progression class code fragment class general numeric progression |
20,751 | nextwe consider the class arithprogressionwhich we present in code fragment this class defines an arithmetic progressionwhere the next value is determined by adding fixed incrementincto the previous value arithprogression inherits fields first and cur and methods firstvalue(and printprogression(nfrom the progression class it adds new fieldincto store the incrementand two constructors for setting the increment finallyit overrides the nextvalue(method to conform to the way we get the next value for an arithmetic progression polymorphism is at work here when progression reference is pointing to an arith progression objectthen it is the arithprogression methods firstvalue(and nextvalue(that will be used this polymorphism is also true inside the inherited version of printprogression( )because the calls to the firstvalue(and nextvalue(methods here are implicit for the "currentobject (called this in java)which in this case will be of the arith progression class example constructors and the keyword this in the definition of the arith progression classwe have added two constructorsa default onewhich takes no parametersand parametric onewhich takes an integer parameter as the increment for the progression the default constructor actually calls the parametric oneusing the keyword this and passing as the value of the increment parameter these two constructors illustrate method overloading (where method name can have multiple versions inside the same class)since method is actually specified by its namethe class of the object that calls itand the types of arguments that are passed to it--its signature in this casethe overloading is for constructors ( default constructor and parametric constructorthe call this( to the parametric constructor as the first statement of the default constructor triggers an exception to the general constructor chaining rule discussed in section namelywhenever the first statement of constructor calls another constructor 'of the same class using the this referencethe superclass constructor is not implicitly called for note that superclass constructor will eventually be called along the chaineither explicitly or implicitly in particularfor our arithprogression classthe default constructor of the superclass (progressionis implicitly called as the first statement of the parametric constructor of arith progression we discuss constructors in more detail in section |
20,752 | class for arithmetic progressionswhich inherits from the general progression class shown in code fragment geometric progression class let us next define classgeomprogressionshown in code fragment which steps through and prints out geometric progressionwhere the next value is determined by multiplying the previous value by fixed basebase |
20,753 | determine the next value hencegeom progression is declared as subclass of the progression class as with the arith progression classthe geomprogression class inherits the fields first and curand the methods firstvalue and printprogression from progression code fragment progressions class for geometric |
20,754 | as further examplewe define fibonacciprogression class that represents another kind of progressionthe fibonacci progressionwhere the next value is defined as the sum of the current and previous values we show class fibonacciprogression in code fragment note our use of |
20,755 | different way of starting the progression code fragment progression class for the fibonacci in order to visualize how the three different progression classes are derived from the general progression classwe give their inheritance diagram in figure |
20,756 | inheritance diagram for class progression and its subclasses to complete our examplewe define class testprogressionshown in code fragment which performs simple test of each of the three classes in this classvariable prog is polymorphic during the execution of the main methodsince it references objects of class arithprogressiongeomprogressionand fibonacciprogression in turn when the main method of the testprogression class is invoked by the java run-time systemthe output shown in code fragment is produced the example presented in this section is admittedly smallbut it provides simple illustration of inheritance in java the progression classits subclassesand the tester program have number of shortcomingshoweverwhich might not be immediately apparent one problem is that the geometric and fibonacci progressions grow quicklyand there is no provision for handling the inevitable overflow of the long integers involved for examplesince geometric progression with base will overflow long integer after iterations likewisethe th fibonacci number is greater than hencethe fibonacci progression will overflow long integer after iterations another problem is that we may not allow arbitrary starting values for fibonacci progression for exampledo we allow fibonacci progression starting with and - dealing with input errors or error conditions that occur during the running of java program requires that we have some mechanism for handling them we discuss this topic next |
20,757 | progression classes program for testing the code fragment output of the testprogression program shown in code fragment |
20,758 | exceptions exceptions are unexpected events that occur during the execution of program an exception can be the result of an error condition or simply an unanticipated input in any casein an object-oriented languagesuch as javaexceptions can be thought of as being objects themselves throwing exceptions in javaexceptions are objects that are thrown by code that encounters some sort of unexpected condition they can also be thrown by the java run-time environment should it encounter an unexpected conditionlike running out of object memory thrown exception is caught by other code that "handlesthe exception somehowor the program is terminated unexpectedly (we will say more about catching exceptions shortly exceptions originate when piece of java code finds some sort of problem during execution and throws an exception object it is convenient to give descriptive name to the class of the exception object for instanceif we try to delete the tenth element from sequence that has only five elementsthe code may throw boundaryviolationexception this action could be donefor exampleusing the following code fragmentif (insertindex > lengththrow new boundaryviolationexception("no element at index insertindex) |
20,759 | it is often convenient to instantiate an exception object at the time the exception has to be thrown thusa throw statement is typically written as followsthrow new exception_type(param param param - )where exception_type is the type of the exception and the param ' form the list of parameters for constructor for this exception exceptions are also thrown by the java run-time environment itself for examplethe counterpart to the example above is arrayindexoutofboundsexception if we have six-element array and ask for the ninth elementthen this exception will be thrown by the java run-time system the throws clause when method is declaredit is appropriate to specify the exceptions it might throw this convention has both functional and courteous purpose for oneit lets users know what to expect it also lets the java compiler know which exceptions to prepare for the following is an example of such method definitionpublic void goshopping(throws shoppinglisttoosmallexceptionoutofmoneyexception /method body by specifying all the exceptions that might be thrown by methodwe prepare others to be able to handle all of the exceptional cases that might arise from using this method another benefit of declaring exceptions is that we do not need to catch those exceptions in our method sometimes this is appropriate in the case where other code is responsible for causing the circumstances leading up to the exception the following illustrates an exception that is "passed through"public void getreadyforclass(throws shoppinglisttoosmallexceptionoutofmoneyexception |
20,760 | the exceptions / don' have to try or catch /which goshopping(might throw because /getreadyforclass(will just pass these along makecookiesforta() function can declare that it throws as many exceptions as it likes such listing can be simplified somewhat if all exceptions that can be thrown are subclasses of the same exception in this casewe only have to declare that method throws the appropriate superclass kinds of throwables java defines classes exception and error as subclasses of throwablewhich denotes any object that can be thrown and caught alsoit defines class runtimeexception as subclass of exception the error class is used for abnormal conditions occurring in the run-time environmentsuch as running out of memory errors can be caughtbut they probably should not bebecause they usually signal problems that cannot be handled gracefully an error message or sudden program termination is about as much grace as we can expect the exception class is the root of the exception hierarchy specialized exceptions (for exampleboundaryviolationexceptionshould be defined by subclassing from either exception or runtimeexception note that exceptions that are not subclasses of runtimeexception must be declared in the throws clause of any method that can throw them catching exceptions when an exception is thrownit must be caught or the program will terminate in any particular methodan exception in that method can be passed through to the calling method or it can be caught in that method when an exception is caughtit can be analyzed and dealt with the general methodology for dealing with exceptions is to "tryto execute some fragment of code that might throw an exception if it does throw an exceptionthen that exception is caught by having the flow of control jump to predefined catch block that contains the code dealing with the exception the general syntax for try-catch block in java is as follows |
20,761 | main_block_of_statements catch (exception_type variable block_of_statements catch (exception_type variable block_of_statements finally block_of_statements where there must be at least one catch partbut the finally part is optional each exception_type is the type of some exceptionand each variable is valid java variable name the java run-time environment begins performing try-catch block such as this by executing the block of statementsmain_block_of_statements if this execution generates no exceptionsthen the flow of control continues with the first statement after the last line of the entire try-catch blockunless it includes an optional finally part the finally partif it existsis executed regardless of whether any exceptions are thrown or caught thusin this caseif no exception is thrownexecution progresses through the try-catch blockjumps to the finally partand then continues with the first statement after the last line of the try-catch block ifon the other handthe blockmain_block_of_statementsgenerates an exceptionthen execution in the try-catch block terminates at that point and execution jumps to the catch block whose exception_type most closely matches the exception thrown the variable for this catch statement references the exception object itselfwhich can be used in the block of the matching catch statement once execution of that catch block completescontrol flow is passed to the optional finally blockif it existsor immediately to the first statement after the last line of the entire try-catch block if there is no finally block otherwiseif there is no catch block matching the exception thrownthen control is passed to the optional finally blockif it existsand then the exception is thrown back to the calling method consider the following example code fragmentint index integer max_value/ billion |
20,762 | problem /this code might have string tobuy shoppinglist[index]catch (arrayindexoutofboundsexception aioobxsystem out println("the index "+index+is outside the array ")if this code does not catch thrown exceptionthe flow of control will immediately exit the method and return to the code that called our method therethe java runtime environment will look again for catch block if there is no catch block in the code that called this methodthe flow of control will jump to the code that called thisand so on eventuallyif no code catches the exceptionthe java run-time system (the origin of our program' flow of controlwill catch the exception at this pointan error message and stack trace is printed to the screen and the program is terminated the following is an actual run-time error messagejava lang nullpointerexceptionreturned null locator at java awt component handleevent(component java: at java awt component postevent(component java: at java awt component postevent(component java: at sun awt motif mbuttonpeer action(mbuttonpeer java: at java lang thread run(thread javaonce an exception is caughtthere are several things programmer might want to do one possibility is to print out an error message and terminate the program there are also some interesting cases in which the best way to handle an exception is to ignore it (this can be done by having an empty catch block |
20,763 | care whether there was an exception or not another legitimate way of handling exceptions is to create and throw another exceptionpossibly one that specifies the exceptional condition more precisely the following is an example of this approachcatch (arrayindexoutofboundsexception aioobxthrow new shoppinglisttoosmallexception"product index is not in the shopping list")perhaps the best way to handle an exception (although this is not always possibleis to find the problemfix itand continue execution interfaces and abstract classes in order for two objects to interactthey must "knowabout the various messages that each will acceptthat isthe methods each object supports to enforce this "knowledge,the object-oriented design paradigm asks that classes specify the application programming interface (api)or simply interfacethat their objects present to other objects in the adt-based approach (see section to data structures followed in this bookan interface defining an adt is specified as type definition and collection of methods for this typewith the arguments for each method being of specified types this specification isin turnenforced by the compiler or run-time systemwhich requires that the types of parameters that are actually passed to methods rigidly conform with the type specified in the interface this requirement is known as strong typing having to define interfaces and then having those definitions enforced by strong typing admittedly places burden on the programmerbut this burden is offset by the rewards it providesfor it enforces the encapsulation principle and often catches programming errors that would otherwise go unnoticed implementing interfaces the main structural element in java that enforces an api is the interface an interface is collection of method declarations with no data and no bodies that isthe methods of an interface are always empty (that isthey are simply method signatureswhen class implements an interfaceit must implement all of the methods declared in the interface in this wayinterfaces enforce requirements that an implementing class has methods with certain specified signatures supposefor examplethat we want to create an inventory of antiques we owncategorized as objects of various types and with various properties we mightfor |
20,764 | implement the sellable interface shown in code fragment we can then define concrete classphotographshown in code fragment that implements the sellable interfaceindicating that we would be willing to sell any of our photograph objectsthis class defines an object that implements each of the methods of the sellable interfaceas required in additionit adds methodiscolorwhich is specialized for photograph objects another kind of object in our collection might be something we could transport for such objectswe define the interface shown in code fragment code fragment interface sellable code fragment class photograph implementing the sellable interface |
20,765 | interface transportable we could then define the class boxeditemshown in code fragment for miscellaneous antiques that we can sellpackand ship thusthe class boxeditem implements the methods of the sellable interface and the transportable interfacewhile also adding specialized methods to set an insured value for boxed shipment and to set the dimensions of box for shipment code fragment class boxeditem |
20,766 | well-- class can implement multiple interfaces--which allows us great deal of flexibility when defining classes that should conform to multiple apis forwhile class in java can extend only one other classit can nevertheless implement many interfaces multiple inheritance in interfaces |
20,767 | inheritance in javamultiple inheritance is allowed for interfaces but not for classes the reason for this rule is that the methods of an interface never have bodieswhile methods in class always do thusif java were to allow for multiple inheritance for classesthere could be confusion if class tried to extend from two classes that contained methods with the same signatures this confusion does not exist for interfaceshoweversince their methods are empty sosince no confusion is involvedand there are times when multiple inheritance of interfaces is usefuljava allows for interfaces to use multiple inheritance one use for multiple inheritance of interfaces is to approximate multiple inheritance technique called the mixin unlike javasome object-oriented languagessuch as smalltalk and ++allow for multiple inheritance of concrete classesnot just interfaces in such languagesit is common to define classescalled mixin classesthat are never intended to be created as stand-alone objectsbut are instead meant to provide additional functionality to existing classes such inheritance is not allowed in javahoweverso programmers must approximate it with interfaces in particularwe can use multiple inheritance of interfaces as mechanism for "mixingthe methods from two or more unrelated interfaces to define an interface that combines their functionalitypossibly adding more methods of its own returning to our example of the antique objectswe could define an interface for insurable items as followspublic interface insurableitem extends transportablesellable /*returns insured value in cents *public int insuredvalue()this interface mixes the methods of the transportable interface with the methods of the sellable interfaceand adds an extra methodinsuredvalue such an interface could allow us to define the boxeditem alternately as followspublic class boxeditem implements insurableitem /same code as class boxeditem in this casenote that the method insuredvalue is not optionalwhereas it was optional in the declaration of boxeditem given previously java interfaces that approximate the mixin include java lang cloneablewhich adds copy feature to classjava lang comparablewhich adds |
20,768 | java util observerwhich adds an update feature to class that wishes to be notified when certain "observableobjects change state abstract classes and strong typing an abstract class is class that contains empty method declarations (that isdeclarations of methods without bodiesas well as concrete definitions of methods and/or instance variables thusan abstract class lies between an interface and complete concrete class like an interfacean abstract class may not be instantiatedthat isno object can be created from an abstract class subclass of an abstract class must provide an implementation for the abstract methods of its superclassunless it is itself abstract butlike concrete classan abstract class can extend another abstract classand abstract and concrete classes can further extend aas well ultimatelywe must define new class that is not abstract and extends (subclassesthe abstract superclassand this new class must fill in code for all abstract methods thusan abstract class uses the specification style of inheritancebut also allows for the specialization and extension styles as well (see section the java lang number class it turns out that we have already seen an example of an abstract class namelythe java number classes (shown in table specialize an abstract class called java lang number each concrete number classsuch as java lang integer and java lang doubleextends the java lang number class and fills in the details for the abstract methods of the superclass in particularthe methods intvaluefloatvaluedoublevalueand longvalue are all abstract in java lang number each concrete number class must specify the details of these methods strong typing in javaan object can be viewed as being of various types the primary type of an object is the class specified at the time was instantiated in additiono is of type for each superclass of and is of type for each interface implemented byc howevera variable can be declared as being of only one type (either class or an interface)which determines how the variable is used and how certain methods will act on it similarlya method has unique return type in generalan expression has unique type by enforcing that all variables be typed and that methods declare the types they expect and returnjava uses the technique of strong typing to help prevent bugs but with rigid requirements on typesit is sometimes necessary to changeor |
20,769 | an explicit cast operator we have already discussed (section how conversions and casting work for base types nextwe discuss how they work for reference variables casting and generics in this sectionwe discuss casting among reference variablesas well as techniquecalled genericswhich allow us to avoid explicit casting in many cases casting we begin our discussion with methods for type conversions for objects widening conversions widening conversion occurs when type is converted into "widertype the following are common cases of widening conversionst and are class types and is superclass of and are interface types and is superinterface of is class that implements interface widening conversions are automatically performed to store the result of an expression into variablewithout the need for an explicit cast thuswe can directly assign the result of an expression of type into variable of type when the conversion from to is widening conversion the example code fragment below shows that an expression of type integer ( newly constructed integer objectcan be assigned to variable of type number integer new integer( )number ito number /widening conversion from integer the correctness of widening conversion can be checked by the compiler and its validity does not require testing by the java run-time environment during program execution narrowing conversions narrowing conversion occurs when type is converted into "narrowertype the following are common cases of narrowing conversions |
20,770 | and are class types and is subclass of and are interface types and is subinterface of is an interface implemented by class in generala narrowing conversion of reference types requires an explicit cast alsothe correctness of narrowing conversion may not be verifiable by the compiler thusits validity should be tested by the java run-time environment during program execution the example code fragment below shows how to use cast to perform narrowing conversion from type number to type integer number new integer( )/widening conversion from integer to number integer (integernfrom number to integer /narrowing conversion in the first statementa new object of class integer is created and assigned to variable of type number thusa widening conversion occurs in this assignment and no cast is required in the second statementwe assign to variable of type integer using cast this assignment is possible because refers to an object of type integer howeversince variable is of type numbera narrowing conversion occurs and the cast is necessary casting exceptions in javawe can cast an object reference of type into type sprovided the object is referring to is actually of type ifon the other handobject is not also of type sthen attempting to cast to type will throw an exception called classcastexception we illustrate this rule in the following code fragmentnumber ninteger in new integer( ) (integern/this is legal new double( ) (integern/this is illegal |
20,771 | object cast will be correct namelyit provides an operatorinstanceofthat allows us to test whether an object variable is referring to an object of certain class (or implementing certain interfacethe syntax for using this operator is object referenceinstanceof reference_typewhere object_reference is an expression that evaluates to an object reference and reference_type is the name of some existing classinterfaceor enum (section if object_reference is indeed an instance of reference_typethen the expression above returns true otherwiseit returns false thuswe can avoid classcastexception from being thrown in the code fragment above by modifying it as followsnumber ninteger in new integer( )if ( instanceof integeri (integern/this is legal new double( )if ( instanceof integeri (integern/this will not be attempted casting with interfaces interfaces allow us to enforce that objects implement certain methodsbut using interface variables with concrete objects sometimes requires casting suppose we declare person interface as shown in code fragment note that method equalto of the person interface takes one parameter of type person thuswe can pass an object of any class implementing the person interface to this method code fragment interface person |
20,772 | the method equalto assumes that the argument (declared of type personis also of type student and performs narrowing conversion from type person (an interfaceto type student ( classusing cast the conversion is allowed in this casebecause it is narrowing conversion from class to interface uwhere we have an object taken from such that extends (or sand implements code fragment interface person class student implementing because of the assumption above in the implementation of method equaltowe have to make sure that an application using objects of class student will not attempt the comparison of student objects with other types of objectsor otherwisethe cast in method equalto will fail for exampleif our application manages directory of student objects and uses no other types of person objectsthe assumption will be satisfied |
20,773 | types allows us to write general kinds of data structures that only make minimal assumptions about the elements they store in code fragment we sketch how to build directory storing pairs of objects implementing the person interface the remove method performs search on the directory contents and removes the specified person pairif it existsandlike the findother methodit uses the equalto method to do this code fragment personpairdirectory sketch of class nowsuppose we have filled directorymydirectorywith pairs of student objects that represent roommate pairs in order to find the roommate of given student objectsmart_onewe may try to do the following (which is wrong)student cute_one mydirectory findother(smart_one)/wrongthe statement above causes an "explicit-cast-requiredcompilation error the problem here is that we are trying to perform narrowing conversion without an explicit cast namelythe value returned by method findother is of type person while the variable cute_oneto which it is assignedis of the narrower type studenta class implementing interface person thuswe use cast to convert type person to type studentas followsstudent cute_one (studentmydirectory findother(smart_one)casting the value of type person returned by method findother to type student works fine as long as we are sure that the call to mydirectory findother is really giving us student object in generalinterfaces can be valuable tool for the design of general data structureswhich can then be specialized by other programmers through the use of casting generics |
20,774 | way that avoids many explicit casts generic type is type that is not defined at compilation timebut becomes fully specified at run time the generics framework allows us to define class in terms of set of formal type parameterswith could be usedfor exampleto abstract the types of some internal variables of the class angle brackets are used to enclose the list of formal type parameters although any valid identifier can be used for formal type parametersingle-letter uppercase names are conventionally used given class that has been defined with such parameterized typeswe instantiate an object of this class by using actual type parameters to indicate the concrete types to be used in code fragment we show class pair storing key-value pairswhere the types of the key and value are specified by parameters and vrespectively the main method creates two instances of this classone for string-integer pair (for exampleto store dimension and its value)and the other for studentdouble pair (for exampleto store the grade given to studentcode fragment example using the student class from code fragment |
20,775 | [height [student(ida namesueage ) in the previous examplethe actual type parameter can be an arbitrary type to restrict the type of an actual parameterwe can use an extends clauseas shown belowwhere class personpairdirectorygeneric is defined in terms of generic type parameter ppartially specified by stating that it extends class person public class personpairdirectorygeneric< extends person/instance variables would go here public personpairdirectorygeneric(/default constructor goes here * |
20,776 | code goes here *public findother ( personreturn null/stub for find public void remove ( personp other/remove code goes here *this class should be compared with class personpairdirectory in code fragment given the class abovewe can declare variable referring to an instance of personpairdirectorygenericthat stores pairs of objects of type studentpersonpairdirectorygeneric mystudentdirectoryfor such an instancemethod findother returns value of type student thusthe following statementwhich does not use castis correctstudent cute_one mystudentdirectory findother(smart_one)the generics framework allows us to define generic versions of methods in this casewe can include the generic definition among the method modifiers for examplewe show below the definition of method that can compare the keys from any two pair objectsprovided that their keys implement the comparable interfacepublic static int comparepairs(pair ppair qreturn getkey(compareto( getkey())/ ' key implements compare to there is an important caveat related to generic typesnamelythat the elements stored in array cannot be type variable or parameterized type java allows for an array to be defined with parameterized typebut it doesn' allow parameterized type to be used to create new array fortunatelyit allows for an array defined with parameterized type to be initialized with newly creatednonparametric array even sothis latter mechanism causes the java compiler to issue warningbecause it is not type-safe we illustrate this point in the following |
20,777 | pair[ new pair[ ]/rightbut gives warning pair[ new pair[ ]/wrong [ new pair()/this is completely right [ set("dog", )/this and the next statement are right too system out println("first pair is "+ [ getkey()+""+ [ getvalue()) exercises for source code and help with exercisesplease visit java datastructures net reinforcement - can two interfaces extend each otherwhy or why notr- give three examples of life-critical software applications - give an example of software application where adaptability can mean the difference between prolonged sales lifetime and bankruptcy - describe component from text-editor gui (other than an "editmenuand the methods that it encapsulates - draw class inheritance diagram for the following set of classes |
20,778 | class goat extends object and adds an instance variable tail and methods milk(and jump(class pig extends object and adds an instance variable nose and methods eat(and wallow(class horse extends object and adds instance variables height and colorand methods run(and jump(class racer extends horse and adds method race(class equestrian extends horse and adds an instance variable weight and methods trot(and is trained( - give short fragment of java code that uses the progression classes from section to find the th value of fibonacci progression that starts with and as its first two values - if we choose inc how many calls to the nextvalue method from the arithprogression class of section can we make before we cause long-integer overflowr- suppose we have an instance variable that is declared of type progressionusing the classes of section suppose further that actually refers to an instance of the class geom progression that was created with the default constructor if we cast to type progression and call firstvalue()what will be returnedwhyr- |
20,779 | variable of type horse if refers to an actual object of type equestriancan it be cast to the class racerwhy or why notr- give an example of java code fragment that performs an array reference that is possibly out of boundsand if it is out of boundsthe program catches that exception and prints the following error message"don' try buffer overflow attacks in java! - consider the following code fragmenttaken from some packagepublic class maryland extends state maryland(/null constructor *public void printme(system out println("read it ")public static void main(string[argsregion mid new state()state md new maryland()object obj new place()place usa new region()md printme()mid printme()((placeobjprintme()obj md((marylandobjprintme()obj usa((placeobjprintme()usa md |
20,780 | class state extends region state(/null constructor *public void printme(system out println("ship it ")class region extends place region(/null constructor *public void printme(system out println("box it ")class place extends object place(/null constructor *public void printme(system out println("buy it ")what is the output from calling the main(method of the maryland classr- write short java method that counts the number of vowels in given character string - write short java method that removes all the punctuation from string storing sentence for examplethis operation would transform the string "let' trymike to "lets try miker- |
20,781 | java console and determines if they can be used in correct arithmetic formula (in the given order)like " ," ,or " * - write short java program that creates pair class that can store two objects declared as generic types demonstrate this program by creating and printing pair objects that contain five different kinds of pairssuch as and - generic parameters are not included in the signature of method declarationso you cannot have different methods in the same class that have different generic parameters but otherwise have the same names and the types and number of their parameters how can you change the signatures of the conflicting methods to get around this restrictioncreativity - explain why the java dynamic dispatch algorithmwhich looks for the method to invoke for call ()will never get into an infinite loop - write java class that extends the progression class so that each value in the progression is the absolute value of the difference between the previous two values you should include default constructor that starts with and as the first two values and parametric constructor that starts with specified pair of numbers as the first two values - write java class that extends the progression class so that each value in the progression is the square root of the previous value (note that you can no longer represent each value with an integer you should include default constructor that has , as the first value and parametric constructor that starts with specified (doublenumber as the first value - rewrite all the classes in the progression hierarchy so that all values are from the biginteger classin order to avoid overflows all together |
20,782 | write program that consists of three classesaband csuch that extends and extends each class should define an instance variable named " (that iseach has its own variable named xdescribe way for method in to access and set ' version of to given valuewithout changing or ' version - write set of java classes that can simulate an internet applicationwhere one partyaliceis periodically creating set of packets that she wants to send to bob an internet process is continually checking if alice has any packets to sendand if soit delivers them to bob' computerand bob is periodically checking if his computer has packet from aliceandif sohe reads and deletes it projects - write java program that inputs document and then outputs bar-chart plot of the frequencies of each alphabet character that appears in that document - write java program that simulates handheld calculator your program should be able process inputeither in gui or from the java consoleforthe buttons that are pushedand then output the contents of the screen after each operation is performed minimallyyour calculator should be able to process the basic arithmetic operations and reset/clear operation - fill in code for the personpairdirectory class of code fragment assuming person pairs are stored in an array with capacity , the directory should keep track of how many person pairs are actually in it - write java program that can take positive integer greater than as input and write out the number of times one must repeatedly divide this number by before getting value less than - |
20,783 | numbers as inputone that is monetary amount charged and the other that is monetary amount given it should then return the number of each kind of bill and coin to give back as change for the difference between the amount given and the amount charged the values assigned to the bills and coins can be based on the monetary system of any current or former government try to design your program so that it returns the fewest number of bills and coins as possible notes for broad overview of developments in computer science and engineeringwe refer the reader to the computer science and engineering handbook [ for more information about the therac- incidentplease see the paper by leveson and turner [ the reader interested in studying object-oriented programming furtheris referred to the books by booch [ ]budd [ ]and liskov and guttag [ liskov and guttag [ also provide nice discussion of abstract data typesas does the survey paper by cardelli and wegner [ and the book by demurjian [ in the the computer science and engineering handbook [ design patterns are described in the book by gammaet al [ the class inheritance diagram notation we use is derived from the book by gammaet al |
20,784 | arrayslinked listsand recursion contents using arrays storing game entries in an array sorting an array java util methods for arrays and random numbers simple cryptography with strings and character arrays |
20,785 | two-dimensional arrays and positional games singly linked lists insertion in singly linked list removing an element in singly linked list doubly linked lists insertion in the middle of doubly linked list removal in the middle of doubly linked list an implementation of doubly linked list |
20,786 | circularly linked lists and linked-list sorting circularly linked lists and duckduckgoose sorting linked list recursion linear recursion binary recursion multiple recursion exercises java datastructures net |
20,787 | using arrays in this sectionwe explore few applications of arrayswhich were introduced in section storing game entries in an array the first application we study is for storing entries in an array--in particularhigh score entries for video game storing entries in arrays is common use for arraysand we could just as easily have chosen to store records for patients in hospital or the names of students in data structures class but insteadwe have decided to store high score entrieswhich is simple application that presents some important data structuring concepts that we will use for other implementations in this book we should begin by asking ourselves what we want to include in high score entry obviouslyone component we should include is an integer representing the score itselfwhich we will call score another nice feature would be to include the name of the person earning this scorewhich we will simply call name we could go on from here adding fields representing the date the score was earned or game statistics that led to that score let us keep our example simplehoweverand just have two fieldsscore and name we show java classgameentryrepresenting game entry in code fragment code fragment java code for simple gameentry class note that we include methods for returning the name and score for game entry objectas well as method for return string representation of this entry |
20,788 | suppose we have some high scores that we want to store in an array named entries the number of scores we want to store could be or so let us use symbolic namemaxentrieswhich represents the number of scores we want to store we must set this variable to specific valueof coursebut by using this variable throughout our codewe can make it easy to change its value later if we need to we can then define the arrayentriesto be an array of length maxentries initiallythis array stores only nullentriesbut as users play our video gamewe will fill in the entries array with entriesbut as users play our video gamewe will fill in the entries array with references to new gameentry objects so we will eventually have to define methods for updating the gameentry references in the entries array the way we keep the entries array organized is simple--we store our set of gameentry objects ordered by their integer score valueshighest to lowest if the number of gameentry objects is less than maxentriesthen we let the end of the entries array store null references this approach prevents having any empty cellsor "holes,in the continuous series of cells of array entries that store the game entries from index onward we illustrate an instance of the data structure in figure and we give java code for such data structure in code fragment in an exercise ( - )we explore how game entry addition might be simplified for the case when we don' need to preserve relative orders |
20,789 | storing references to six gameentry objects in the cells from index to with the rest being null references code fragment class for maintaining set of scores as gameentry objects |
20,790 | representation of the high scores in the entries array this method is quite useful for debugging purposes in this casethe string will be comma-separated listing of the gameentry objects in the entries array we produce this listing with simple for-loopwhich adds comma just before each entry that comes after the first one with such string representationwe can print out the state of the entries array during debuggingfor testing how things look before and after we make updates insertion one of the most common updates we might want to make to the entries array of high scores is to add new game entry so suppose we want to insert new gameentry objecte in particularlet us consider how we might perform the following update operation on an instance of the scores classadd( )insert game entry into the collection of high scores if the collection is fullthen is added only if its score is higher than the lowest score in the setand in this casee replaces the entry with the lowest score the main challenge in implementing this operation is figuring out where should go in the entries array and making room for |
20,791 | to visualize this insertion processimagine that we store in array entries remote controls representing references to the nonnull gameentry objectslisted left-to-right from the one with highest score to the one with the lowest given the new game entryewe need to figure out where it belongs we start this search at the end of the entries array if the last reference in this array is not null and its score is bigger than ' scorethen we can stop immediately forin this casee is not high score--it doesn' belong in the entries array at all otherwisewe know that belongs in the arrayand we also know that the last thing in the entries array no longer belongs there nextwe go to the second to the last reference in the array if this reference is null or it points to gameentry object whose score is less thane'sthis reference needs to be moved one cell to the right in the entries array moreoverif we move this referencethen we need to repeat this comparison with the next oneprovided we haven' reached the beginning of the entries array we continue comparing and shifting references to game entries until we either reach the beginning of the entries array or we compare ' score with game entry with higher score in either casewe will have identified the place where belongs (see figure figure preparing to add new gameentry object to the entries array in order to make room for the new referencewe have to shift the references to game entries with smaller scores than the new one to the right by one cell |
20,792 | entryebelongswe add reference to at this position that iscontinuing our visualization of object references as remote controlswe add remote control designed especially for to this location in the entries array (see figure figure adding reference to new gameentry object to the entries array the reference can now be inserted at index since we have shifted all references to gameentry objects with scores less than the new one to the right |
20,793 | array are similar to this informal descriptionand are given in java in code fragment note that we use loop to move references out of the way the number of times we perform this loop depends on the number of references we have to move to make room for reference to the new game entry if there are or even just few references to move overthis add method will be pretty fast but if there are lot to movethen this method could be fairly slow also note that if the array is full and we perform an add on itthen we will either remove the reference to the current last game entry or we will fail to add reference to the new game entrye code fragment gameentry object java code for inserting |
20,794 | suppose some hot shot plays our video game and gets his or her name on our high score list in this casewe might want to have method that lets us remove game entry from the list of high scores thereforelet us consider how we might remove reference to gameentry object from the entries array that islet us consider how we might implement the following operationremove( )remove and return the game entry at index in the entries array if index is outside the bounds of the entries arraythen this method throws an exceptionotherwisethe entries array will be updated to remove the object at index and all objects previously stored at indices higher than are "moved overto fill in for the removed object our implementation for remove will be much like performing our algorithm for object additionbut in reverse againwe can visualize the entries array as an array of remote controls pointing to gameentry objects to remove the reference to the object at index iwe start at index and move all the references at indices higher than one cell to the left (see figure figure an illustration of removal at index in an array storing references to gameentry objects |
20,795 | the details for doing the remove operation contain few subtle points the first is thatin order to remove and return the game entry (let' call it eat index in our arraywe must first save in temporary variable we will use this variable to return when we are done removing it the second subtle point is thatin moving references higher than one cell to the leftwe don' go all the way to the end of the array--we stop at the second to last reference we stop just before the endbecause the last reference does not have any reference to its right (hencethere is no reference to move into the last place in the entries arrayfor the last reference in the entries arrayit is enough that we simply null it out we conclude by returning reference to the removed entry (which no longer has any reference pointing to it in the entries arraysee code fragment code fragment java code for performing the remove operation |
20,796 | simple neverthelessthey form the basis of techniques that are used repeatedly to build more sophisticated data structures these other structures may be more general than the array structure aboveof courseand often they will have lot more operations that they can perform than just add and remove but studying the concrete array data structureas we are doing nowis great starting point to understanding these other structuressince every data structure has to be implemented using concrete means in factlater in this bookwe will study java collections classarraylistwhich is more general than the array structure we are studying here the arraylist has methods to do lot of the things we will want to do with an arraywhile also eliminating the error that occurs when adding an object to full array the arraylist eliminates this error by automatically copying the objects into larger array if necessary rather than discuss this process herehoweverwe will say more about how this is done when we discuss the arraylist in detail sorting an array in the previous sectionwe worked hard to show how we can add or remove objects at certain index in an array while keeping the previous order of the objects intact in this sectionwe study way of starting with an array with objects that are out of order and putting them in order this is known as the sorting problem simple insertion-sort algorithm we study several sorting algorithms in this bookmost of which appear in as warm upwe describe in this section nicesimple sorting algorithm called insertion-sort in this casewe describe specific version of the algorithm where the input is an array of comparable elements we consider more general kinds of sorting algorithms later in this book |
20,797 | character in the array one character by itself is already sorted then we consider the next character in the array if it is smaller than the firstwe swap them next we consider the third character in the array we swap it leftward until it is in its proper order with the first two characters we then consider the fourth characterand swap it leftward until it is in the proper order with the first three we continue in this manner with the fifth integerthe sixthand so onuntil the whole array is sorted mixing this informal description with programming constructswe can express the insertion-sort algorithm as shown in code fragment code fragment high-level description of the insertion-sort algorithm this is nicehigh-level description of insertion-sort it also demonstrates why this algorithm is called "insertion-sort"--because each iteration of the main inserts the next element into the sorted part of the array that comes before it before we can code this description uphoweverwe need to work out more of the details of how we do this insertion task diving into those details bit morelet us rewrite our description so that we now use two nested loops the outer loop will consider each element in the array in turn and the inner loop will move that element to its proper location with the (sortedsubarray of characters that are to its left refining the details for insertion-sort refining the detailsthenwe can describe our algorithm as shown in code fragment code fragment intermediate-level description of the insertion-sort algorithm |
20,798 | how to insert the element [iinto the subarray that comes before it it still uses an informal description of moving elements if they are out of orderbut this is not terribly difficult thing to do java description of insertion-sort now we are ready to give java code for this simple version of the insertion-sort algorithm we give such description in code fragment for the special case when is an array of charactersa code fragment java code for performing insertion-sort on an array of characters we illustrate an example run of the insertion-sort algorithm in figure figure execution of the insertion-sort algorithm on an array of eight characters we show the |
20,799 | color the next element that is being inserted into the sorted part of the array with light blue we also highlight that character on the leftsince it is stored in the cur variable each row corresponds to an iteration of the outer loopand each copy of the array in row corresponds to an iteration of the inner loop each comparison is shown with an arc in additionwe indicate whether that comparison resulted in move or not an interesting thing happens in the insertion-sort algorithm if the array is already sorted in this casethe inner loop does only one comparisondetermines that |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.