Vous êtes sur la page 1sur 79

Topic Outline

Introduction
Some preliminary definitions are necessary for the use of this textnot because they are specifically computer programming in nature, but because I use a perhaps non-standard interpretation of these words in the context of this course. Problem a job that one needs or wants to complete which requires a non-tri ial amount of thought and effort by the person wor!ing. Exercise a tri ial job that is intended to highlight a particular s!ill or best-practice. Solution all the wor!, code, and pre-prescribed data used to complete a problem, neatly organi"ed in standard wor!able fashion. Good Solution a solution to a problem that minimi"es extraneous data and code, is easy to read and comprehend, and adheres to commonly accepted standards for writing.

Instructions for completing Exercises


#ll exercises that as! for written responses should be answered in your $ournal within the class page online. %xercises that as! for code should ha e the code submitted as an attachment to your $ournal.

Week 1Objects and Data


&his is where it all begins. #t the core of computer programming, underneath all the fancy guts of the myriad programming languages is one basic goalthe manipulation of data. &here are many different ways of attac!ing this problem, each of which has its ad antages and disad antages. In e ery strategy, the manipulation of data is accomplished by some acti e manipulators. In the grammar of e ery programming language, data are the nouns, and these nouns are affected by the use of erbs. &he different computer programming languages use erbs differently. In this course, we will be using the $a a programming language. $a a is a purely Object-Oriented language. &his means that data is treated not just as a static piece of information, but more li!e an abstract organism. In a fully 'bject-'riented language, e erything is an Object. (ut, what is an 'bject) &he concept of an 'bject is difficult to wrap your brain around the first time. *owe er, it is ery close to you as a human because your brain naturally interprets the world around you in terms of 'bjects. In your day to day life, e erything you encounter can be thought of as distinct 'bjectssome are more complicated than others, and some are built of smaller 'bjects. &he most abstracted 'bject definition is this+ #n 'bject is information combined together with beha iors in a self-contained unit. If you thin! about it hard enough, well, not too hard, or your brain might explode, you can easily describe anything you see in the world around you in terms of an 'bject structure. -hen describing an 'bject, there are two major aspects+ Attributes, and Behaviors. #n 'bject.s #ttributes are all the datanouns/used to describe the 'bject. #n 'bject.s (eha iors are all the actions erbsthat the 'bject can do to itself, to other 'bjects, pro ide access to data stored in the 'bject, or any other action that doesn.t necessarily change data directly in any particular way.

Alternate Vocabulary
0ou may see any of the following ocabulary words throughout this text and in con ersation. &he following terms are for the purposes of this classthough not necessarily in generalequi alent. Some ha e connotations that are not rele ant at this le el. #ttributes+ fields, instance ariables, properties. (eha iors+ functions, member functions, methods, processes, actions.
/ 0ou may thin! this should be adjecti es since they are describing. 1oun is in fact the correct interpretation here though. -e will discuss this distinction more when we design our own 'bjects.

Primitive Data T pes


$a a, li!e all computer programming languages requires acti e use of changeable datajust li!e 2ath class, we call these variables. &he twist for computer programming is that unli!e 2ath class, we use more than just 1umbers as data. 3or this reason, we distinguish our ariables with a data type. In $a a, all ariables must be declared with a data type to tell the computer how to allocate memory for this piece of information. #lso, in $a a, 'bjects are synonymous with data typeswe call them complex data types. -e.ll tal! about these more in later sections. $a a has many built-in data types, most of which are complex data types defined as objects in the arious $a a libraries we will discuss. *owe er, there is a core set of standard data types that are shared by pretty much all computer programming languages. &hese are the primitive data types. -e call them primiti e because they are the ery basic pieces of data that we use to build complex data types and data structures. 0ou can thin! of primiti e data types as the sub-atomic particles of computer programmingpretty simple in contrast to what you build out of them. The Primitive !ata Types in "ava 4escription # 78-bit integer alue # floating point decimal # single text character # logic ariable, / bit # />-bit integer alue # >=-bit integer alue # floating point decimal Bdouble is twice the si"e in bitsCD # single byte of raw data

Type name int double char boolean short lon# $loat byte

5iteral 6alue examples 9, -87, :8;/< 7./=/:<8, 8.>8</ ?a., ?@., ?=. true, false 1ot in #A Subset 1ot in #A Subset 1ot in #A Subset 1ot in #A Subset

Declaring !ariables
-hen writing $a a code, the grammarcalled syntax BSI1-tac!sDis absolutely precise. 1o errors are allowed or your program will not compile. #ll ariable declarations must follow this form+ Edata typeF E ariable nameFG to declare a ariable with its data type.s default alue. Edata typeF E ariable nameF H Eliteral alue or expressionFG 4eclares a ariable with a specific initial alue. It is possible to declare multiple ariables of the same type in a single statement of the form with commas separating the ariables.

Edata typeF E ariable nameF IH E alueFJ, E ariable nameF IH E alueFJ, , G

"tring
&here is one so-called complex data type that is often lumped in with the primiti es because of its use, and because it has its own compiler-le el literal alue expression. &his type is Strin#. String is an 'bject typethat is it has methods attached to it, but it also has literal alues li!e a primiti e data type. String is used to represent strings of charactersi.e. words and phrases, or e en whole text documents. # String literal is represented using double-quotes, as opposed to the character literal using singlequotes.

#ommand "tatements and "e$uential #ode Execution


&he first le el of data manipulation comes from basic command statements. &he most basic of these commands is the assi#nment statement. #n assignment statement is any statement of the form E ariableF H EexpressionFG In computer programming the single equals sign ?H. is called the assi#nment operator, and expects this format e ery time. It is important to remember that the left-hand-side of the equals sign must be a single ariable by itself, or a ariable declaration. &he standard arithmetic operators apply to numeric data types int and doublethough integer di ision warrants its own section in this chapter. (eware of mixing data typesC 2ost of the time, the compiler will call storing one data type into another an error, but not always. Integers and 4oubles are interchangeablehowe er, con erting a double to an

integer drops all information after the decimal point, lea ing only the integer part of the floating point number.

%rit&metic Operators
K M N #ddition Subtraction 2ultiplication 4i ision / K =.7 H :.7 BdoubleD 8= K L H 7/BintD 8=.9 K L H 7/.9 BdoubleD / - 9.: H 9.: BdoubleD /9 - L H 7 BintD /9.9 - L H 7.9 BdoubleD > M 9.: H 7.9 BdoubleD 7 M 8 H > BintD > N 8 H 7 BintD > N 8.9 H 7.9 BdoubleD < N 8 H = BintD < N 8.9 H =.: BdoubleD :O8H/ : O 8.9 H %PP'PC /8 O : H 8

2odulus Bremainder from integer di isionD 'nly usable with integers.

Exercise 1'1
Pun the following code and record its output in a journal entry.

Exercise 1'(
-hat does the K operator do when Strings are in ol ed)

#onverting Data and )eading from t&e *e board


Qonsider the following code+

Scanner is an 'bject class. 0ou can see that it is used just li!e a regular data type, except with a twist. &he !eyword ne% shows that this is a complex data type. &his is the form for declaring full on complex data types. EQlass 1ameF E ariable nameF H new EQlass 1ameFBIinitiali"ation aluesJDG -hen creating a new instance of the Scanner class, I need to tell it what it will be reading from. Since this Scanner.s job is to read from the !eyboard, I ha e named it R!eyboard.S &his doesn.t ha e any effect on the code, but it ma!es it easier to understand what I.m doing as you read further in the code. -hen I read from the !eyboard, I use a beha ior from the Scanner class. I access this member function by using the form Einstance nameF.Emethod nameFBDG So, in o!ing keyboard.nextLine() reads from the !eyboard until I hit the %nter !ey. #ll the text that I typed before the %nter !ey is returned and used in the assignment statement. I use the intermediate ariable textFromKeyboard because the nextLine() method in the Scanner class returns a String data typenot a double or an int. 5uc!ily, there are different 'bjects that will handle the con ersion of Strings into primiti e data types.

Double.parseDouble(textFromKeyboard); is an example of such a method call. parse4ouble in this case is a static method callthat is, a call to a method that does not require an instance of the class, li!e a erb in the command form. &his command erb ta!es a String as input, and spits out a double.

Exercise 1'+
-hat happens if you type something that is not a number into this program)

Exercise 1',
4escribe some differences between 'bjects and Arimiti e data types.

Problem 1
#long with Double.parseDouble(String str), there is an integer counterpart, Integer.parseInt(String str). Tse this static method along with the Scanner class to write a program that as!s the user for two integers, and then displays the integer di ision statement as follows+

Week (-lo. #ontrol


&ry the following example.

Exercise ('1
-hat happens if you enter a negati e number in either place) -hat happens if b is larger than a)

/oolean %lgebra
0ou are familiar with the #lgebra of numbers. *owe er, that is not the only #lgebra out there. In your e eryday life, you encounter (oolean algebra also, without e en reali"ing it. Boolean al#ebra is the algebra of logic. &hat is, the algebra of ariables with only two possible alues true or $alse, 9 or /, single bits of computer memory. &he rules that go ern this algebra are just as solid as the rules that go ern the algebra you.re used to. So, here goesC

0ava /oolean Operators


UU #nd UU 9 / 9 9 9 / 9 /

VV

'r

VV 9 /

9 9 /

/ / /

1egation

C9 H / C/ H 9

&he Qayley table in the third column shows the e aluation of the operator with the left-hand-side alues across the columns, and the right-hand-side alues down the rows. &he statement $alse && true would be e aluated by+ UU 9 / &his e aluates to $alse. 9 9 9 / 9 /

/oolean !ariables
# boolean ariable has possible alues true or $alse. %ach of these is a !eyword in $a a. $a a also supports expressions which e aluate to boolean alues. &hese statements are usually comparisons between aluesthough later we will explore 'bjects with boolean traits. # boolean expression is really any statement that is equi alent to a yes-or-no question. 3or now, we will be interested in comparison statements.

#omparison Operators
&he following table shows the standard comparison operators in $a a. &hese are only applicable to primiti e data typesno complex data types should use these comparison operators. E F EH FH HH CH 5ess than Wreater than 5ess than or equal to Wreater than or equal to %quals 4oes not equal L E 8= ;8 F /9 : EH : : FH : : HH : 7 CH 8

#ny statement of the form 'x ( y) where ( is any of the comparison operators, is a boolean expression, and can be used in conjunction with boolean operators.

#onditional "tatements
Arograms that always do the same thing e ery time are sometimes usefuloften a program this simple will be called a script, and usually is not written in a high le el programming language li!e $a a, because there are other languages more suited to scripting. In this course we want to do more interesting things. 2y programs should react differently gi en certain conditions. Qontrolling, and preparing your program for many different possible outcomes is what ma!es programming useful and fun. # well written program is ery meticulously prepared for all possible outcomes. In the following section, I outline the basic decision ma!ing structures of $a a.

/inar / pass if
# binary bypass is a flow control statement in which the code will execute a set of commands only if a particular condition is met. %xample+

&he message You have low hps! Be careful! is only printed if the player is under 89O of their max hps. If the player is not under 89O, the simply bypasses all the statements in the bloc! surrounded by X , Y following the if statement. &he X , Y are ery important grouping symbols. If there is only one statement following a flow control statement, the X , Y are not required, but I put them anyway for ease of reading.

/inar #&oice ifelse


# binary choice in ol es two possible code paths. Qode will follow either one path or the other, but ne er both at the same time. &he code inside the X , Y following the if statement executes if the statement is true, otherwise, the code defaults to the bloc! contained in X , Y following the else statement.

In this example, if the player has entered an in alid command, the game responds with I dont understand! &he game will only process the gi en command if the first statement did 1'& execute that is, the command is processed '150 I3 it is alid.

1ultiple #onditions ifelse ifelse


Sometimes two choices are not enough.

#s many conditions as you wish can be lined up in this manner. &here is some important logic to remember thoughC &he if statements are as!ed in order, so if two conditions are logically equi alent, then only the first will execute. Similarly, if one condition implies another condition, the program may not beha e the way you expect. &his does 1'& mean that your conditions should be logically independent of each other. (y s!illfully laying out your conditions, you can sometimes sa e calculation time by !nowing thatfor examplein reaching the third condition, I !now that conditions / and 8 are falseC

&his example, while syntactically correct, is ery wrong. See if you can identify the logic errors.

switch
&he swit ! statement is a shortcut if"else if"else statement. It is also less robust. # switch statement will only operate on primiti e data types, and only uses one type of condition.

&he syntax is ery pic!yC &he format must be+ ase E alueF# Eas many statements as you li!eF break; and the last conditionequi alent to an elsemust be default# EstatementsF break; 'nly one case will execute, if none of the declared cases are the alue of x, then the default case will execute. 0ou can ha e a do-nothing case by simply ha ing ase $%alue&# break; or default# break;

2ooping
3or just about any useful program, you will need to repeat the same code multiple times. &here are two main ways of thin!ing about repetition. %xecuting code a specific number of times, count-controlled, or executing indefinitely until a certain sentinel condition is met.

#ount3#ontrolled loop for


&he for loop is ery ersatile. It can be used in many different ways, but the primary construction we will use is to ma!e a count controlled loop.

&his loop executes 89 times, and prints the integers 9-/<. &he loop signature has 7 statements inside the B , D. &he first is a ariable declaration for the counting ariable, initiali"ed with the starting alue. &his loop starts counting at 9. Second is the continuation condition. &his loop repeats as long as i is less than 89. &he last statement is an increment for the count ariable. &his loop counts by / each time. It is important to !now the order in which code happens in this statement. /. 4eclare the counting ariable and assign initial alue. 8. Qhec! the ending condition. if it is false, exit the loop and resume code execution after the Y 7. Pun all code inside the X , Y =. %xecute the increment statement. :. Peturn to step 8. #nother for loop might loo! li!e this.

-hat would be the output of this loop)

while loop
-e will use the while loop to execute code an indefinite number of times. It.s easy to remember if you thin! of a while loop as executing while its condition is trueC -hen you.re thin!ing in %nglish, you may also run into situations where you want to execute a loop until some ending condition. &his is also a while loop. # while loop executes until its condition is false.

In a game, the game loop is always a while loop. &his game continues until the player wants to quit. 1otice that I used the condition w!ile 1'& player'ants(o)uit.

dowhile loop
&here is another way to formulate a while loop. # do , while loop is identical to a while loop except that the condition is chec!ed at the %14 of the loop and not at the (%WI11I1W. -ithout too much thought,

you can see that the only functional difference is that this loop is guaranteed to run at least once, while the standard while loop may ne er execute.

break and continue ke .ords


&wo additional degrees of control with loops are the !eywords break and ontinue. &he break command exits the loop immediately and resumes execution after the Y &he ontinue command s!ips the rest of the current iteration, and resumes execution at chec!ing the loops continue condition.

-hat is the output of this loop)

"tandard %rra s
%nter this program in a new project.

&he ariable numbers in this program is a standard array. # standard array is fixed-si"ed group of ariables all of the same data type. &he group is referenced as a whole by the assigned ariable name, while indi idual elements of the array are referenced by adding an index number to the end of the ariable name. It is important to remember that indices always start at 9. &he first position in an array is index 9. -hat is the index of the last element in the array)

1emor %llocation for "tandard %rra s

&his data structure allows for ha ing an indefinite number of ariables in a program. In the example program, I as! the user how many numbers they need to enter in order to complete the calculation. It is necessary to as! the user, howe er, because the standard array is only a fixed-si"e. 'nce, set, the si"e of the list cannot change. &o resi"e, you must recreate a new list with the appropriate si"e.

1et&ods
Qonsider the following extension of the pre ious example.

Qontinued on next page,

Exercise
Identify parts of the program that are repeated, or represent complete actions unto themsel es.

Program /reakdo.n
In this simple example, the most ob ious way to brea! down the problem is into the parts that are identified as actions that you would perform from the menu. %nter a new list. 4isplay the stored list. # erage the list. %ach of these bits of text are short hand for a larger, more complex action. 3or example, Enter a new list means+

&his code happens to be repeated almost exactly later in the program as well. So is the Display the stored list code. (loc!s of code such as this can be organi"ed into methods which allow me to gi e the bloc! of code a name, much li!e a ariable. (y invo*in# a method call, we tell the program to lea e from where the cursor is, and jump to the specified bloc! of code, execute it, and then return to the current statement with the result.

In o!es a call to+

1odified Program

Pequires the following methods to be declared inside the X , Y of the lass *rogram.

4ownload the source code for this example from my 4ropbox.

1et&od "ignatures
&he first line of each method is called the method signature. &he signature contains all the information necessary for the compiler to !now how to deal with the method. &he method signature is bro!en down into se eral parts+ /. #ccess le el+ public, private, or protectedfor now, stic! with public. 8. Static) Bfor now, all methods that you write in the Arogram class should ha e staticD 7. Peturn type+ 4ata type of the RanswerS to your method if your method is doing some calculation. RWetS type methods, should use the data type of the data that you are Rgetting.S If the method does not return a alue, use the !eyword void. =. 2ethod 1ame+ follows the same rules as ariable names. :. B parameters D+ if you thin! of 2ethods as 6erbs, then Aarameters are the direct or indirect objects of the erb. &hey are the ariables that the method must use to do its job. Some methods do not need any parametersin this case, lea e the BD emptyG they are still required.

Problem (
-rite a program which as!s the user for a list of words, then tells the user which word is the longest, and which word is the shortest, which comes first alphabetically, and which comes last alphabetically. 0ou will need to do a little research on the String class. 0ou should ma!e your program repeat until the user chooses to exit, and ha e a menu for choosing what you want to do.

Experiment4
#nswer the following questions in your journal. 0ou may use any program with a main() method to experiment. 2a!e the requisite changes, and then attempt to compile and run the program. /. -hat happens if the main() method is declared as private instead of public) 8. -hat happens if the static modifier is remo ed from the signature of the main() method) 7. -hat happens if I write static public void instead of public static void)

=. -hat happens if I do not include the String+, args parameter) :. -hat happens if I add additional parameters to the main() method)

Week +D namic %rra s


D namic %rra s
Standard arrays are straightforward and ha e low memory o erhead. &hey also are cumbersome to use if you don.t !now ahead of time how much data you need to reser e space for. 5uc!ily, the $a a standard library includes se eral different types of variable si+e arrays. -e will be interested in one particular dynamic array type#rray5ist. &o use the #rray5ist object type, you need to import -a%a.util..rrayList; at the top of your file. #s a companion class we will need to import -a%a.util.Iterator; for dealing with lists. *ere.s some example code+

%rra 2ist5E6
.rrayList can be declared in two different ways, both of which ha e their ad antages. .rrayList list/f/b-e ts 0 new .rrayList(); declares a generic list. &his .rrayList does not care what type of data is stored inside itit stores any 'bject data. &his means that I can potentially add data of different data types to the same list. &he drawbac! is that when I get data out of the list, I don.t !now what the data type isja a will treat it as a general 'bject. &his means, that if I need to use methods or attributes of the data stored in the list, I must cast the data bac! to its original data type. -e.ll see an example of this later. &he second way to declare an .rrayList is to declare right away what type of data is going to be stored in the list. So, the .rrayList$String& list/fStrings 0 new .rrayList$String&(); is limited to only adding String ariables, howe er, in return for this limitation, you get String as the return type on all data accessing methods of the .rrayList class.

Iterator5E6
Iterator is a companion to the List classes. $ust li!e .rrayList, it can be declared as generic or with a specific data type. &he #rray5ist.iteratorBD method builds the Iterator object for the gi en #rray5ist. &he word iterator is a noun that comes from the erb to iterate, meaning repeating the same process a number of different times. # for loop iterates a set number of times. %ach step through the loop is called an iteration. Tsing the same root word, the Iterator for an .rrayList is the 'bject which Iterates o er the gi en list. &he primary methods of an Iterator are Iterator.!as1ext() and Iterator.next(). Iterator.!as1ext() returns true if there are more items in the list. If the currently selected item is the last item in the list, then !as1ext() will return false. Iterator.next() is the acti e method. It mo es the pointer to select the next item in the list, and returns the newly selected alue. If you want to do more than one thing with the particular item, then you will want to hold onto this alue in a temporary ariable, such as in the following example+

-ithout using the ariable String !older, I would not be able to print both the word and its length.

Exercises
#nswer the following questions in your $ournal. /. -hat does the line numbers.add(Double.parseDouble(keyboard.nextLine())); do) 8. -hich method is in o!ed first) 7. #ssuming that numbers is an .rrayList$Double&, what is the data type expected as a parameter in the add(") method) Tse the official $a a4oc for the #rray5ist class to answer the following questions. /. -hat is the difference between numbers.add(2.2) and numbers.add(34 2.2)) 8. #ssuming .rrayList$Double& numbers, what is the return type of numbers.get(5)) 7. -hy must I use Double instead of double for an .rrayList) -hat is the difference) B2ay require researchCD =. In the $a a4oc, .rrayList uses the words capacity and size differently. B%xample, loo! at the documentation for trim(oSi6e()D. -hat is the difference between the .rrayList capacity and the .rrayList si"e)

%P 7ote
&he following methods in the #rray5ist class are part of the #A $a a subset, and you should be familiar with using themC add(7 e) add(int index4 7 element) get(int index) set(int index4 7 ob-) remo%e(int index) &he next methods are not part of the #A $a a subset, but are ery usefulC I expect you to be familiar with these as well. lear() ontains(/b-e t o)

index/f(/b-e t o)

is7mpty() iterator() remo%e(/b-e t o) si6e()

8nderstanding 1et&ods
*ere.s an experiment using 2ethods. &ype this program into a new Aroject and run it.

&here are two problems here. &he first problem here is scope.

"cope
&he ariable x in the main() method is not the same as the ariable x in the addSe ond(oFirst() method. &he scope of a ariable is determined by Band limited byD where and how it is defined. (y declaring int x 0 2 directly inside the main() method, I ha e put it in the scope of the main() method. &his means that it only exists within the main method. 2a!e the following change to the program to see that this is true+

&he red underline error message, Rx cannot be resol ed to a ariable,S means that x is not declared in this scopethat is, the scope of the addSe ond(oFirst() method. &o fix this error, redeclare x as an integer.

2a!ing this update does not fix the original issue, howe er. It only highlights a potential mista!e. Tnderstanding the scope of a ariable is ery important. In this case, scope highlights another concept that $a a uses. (y mo ing to a method, you gain a new ariable scope, and the ariables passed as parameters to that method transfer their alue to a new ariable in the scope of the new methodC &his style of passing ariables is called pass-by-value. -hen a ariable is passed-by-value, its alue is passed to a new instance of a ariable in the scope of the method it is being passed to. *ere.s how the code sees things+

%ach bloc! in memory is separate. (ed represents the scope of the addSe ond(oFirst() method, while Blac* represents the scope of the main() method. It should be noted that $a a only uses pass-by- alue. 'ther languages support another way called passby-re$erence in which the ariable.s scope is actually extended to include the new method.s scope. $a a does not ha e a way to pass-by-reference. So now, !nowing this, how do we ma!e the last println statement print the proper alue of x) &he answer is a design issue.

1et&od Design8sing return


(y only allowing pass-by- alue method parameters, $a a enforces a restriction on program design. (ecause methods cannot alter the alue of ariables passed in as parameters, you cannot write a method intended to ma!e sweeping changes to ariables not directly within its scope. It forces you to thin! of methods as simple operations. *ere is one solution to our example problem.

&he addSe ond(oFirst() method implied a particular way of thin!ing to the problem. (y stating, R#dd the second number to the first number,S I am implying that I intend to change the alue of the first number inside this method. Since that is not allowed by the $a a language, I need to rethin! my solution. (y mo ing the question of, Rwhat ariable am I changing)S up to the main() method, I can write the add() method independent of that question. &he new add() method is now purely an operation something that needs be done, and does not need to care about the ariable that is outside of its scope. &he return statement allows this !ind of con ersation+ mainBD method+ aside RI need to add : and L, "omghelpidont!nowhowCS addBD method+ aside RWi e me those, I can do it...S main ! calls add "# $!% addBD method+ RInside t!e met!od4 t!e %alue of x is# 89S add ! returns &'% mainBD method+ R:a k in t!e program4 t!e %alue of x is# 89S

*e T&oug&t Process
&his example highlights a really important point. $a a requires programmers to adhere to some particular styles. &his is one of them. 2ethods should only operate on ariables in their local scope. #ny ariables needed in the method must be passed into the method.s local scope as parameters, and the method is only allowed one response in the form of a return statement. 'nly the last example in this section is a correct way to write this method.

Problem +
Pesearch online and learn how to implement a RSelection Sort.S -rite a program that does the following+ /. #s! the user for a list of words. 8. Tse the selection sort algorithm in conjunction with the String. ompare(o() method to put the list of words in alphabetical order. 7. Arint the list of words in alphabetical order. =. Tse a menu to gi e the user the option to add a word to the list, or quit. :. #s long as the user wants to add more words, insert the words into the list in alphabetical order. a. &here are se eral good solutions to this problemC

Week ,Introducing #lasses


0ou ha e probably noticed at this point that e ery program you ha e written starts with public class , &his is because $a a is a fully 'bject 'riented language. % erything you do in $a a must be contained within an R'bject class.S &he class we ha e been using so far, public class *rogram, is a ery special !ind of class. % ery method you ha e written inside this class has had the !ey word static as part of the method signature. &he reason is, static tells the language that this method Bor ariableD is referenced independently of any particular instance of the gi en class. Qonsider this adaptation of an example that we ha e seen.

System is a class. out is a static member ariable Bof type *rintStreamD of the System classin %clipse, static member ariables are indicated by the blue italics. print() and println() are instance methods Bnon-static methodsD in the *rintStream class. So the call System.out.println(;stuff<); calls an instance method on a static member of the System class Qomplicated stuffC &he distinction is important though. 1e er ha e you e er had to, nor will you e er ha e to declare a ariable of type System. System is a static class, just li!e the *rogram classes you ha e written.

#lass #onception
&here are two major ocabulary words that you will be reading a lot for the remainder of your time in this class-lass and Object. -e ha e said a number of things about 'bjects in general, but it.s time for some specifics. # class is to an 'bject as the mold is to a piece of ceramic. (y writing the class, you describe in abstract all the details that are filled in during the creation instantiationof an 'bject. &his distinction is the most abstract concept we will co er in this classwell, the concept is meta-abstraction. &he ultimate goal of designing a class in an 'bject 'riented language li!e $a a is the concept of encapsulation. %ncapsulation is combining attributes and methods in a single logical entitythe class. $a a tries ery hard to enforce this programming paradigm, but it can still be done poorly or not at all depending on how you plan your project. In fact, all the Arogram classes that you ha e written thus far are not adhering to the 'bject 'riented principles. &he following project is an example of some classes that wor! together following as closely as possible the principles of good 'bject 'riented design as possible without getting o erly complicatedC &he source code is a ailable at the end of the chapterG howe er, for the sa!e of practice, I would li!e you to type the Qard class by hand the first time. *ere is an example of the planning that goes into a problem. &his diagram is called an object model, or a ./0 !ia#ram.

&he top is the Qlass name. &he middle area is for attributes, and the bottom area is for instance methods.

#lass Example#ard 9ame


Qonsider a game of cards. It doesn.t matter what game yet, we.ll decide on the rules later. 3ocus first on the essentials. &o play cards, what is necessary) &he first thing that comes to mind, hopefully, is RQardsCS

5et.s examine the Qard class line by line,

#lass Declaration

&he class has a signature, just li!e methods. &he blue underline shows the access le el of the class. &his could be public, private, or protected. If you lea e the word out completely, it is assumed to be public. &here are some instances where using a pri ate or protected class is appropriateG howe er, they are outside the scope of this boo!. 3or now, always use public. &he highlighted segment of text modifies the class in a different way. &here are two !ey words that can follow the class nameimplements and extends. &hese each ser e a specific purpose that we will discuss in detail in the lesson on class inheritance. 3or now, it is sufficient to !now that

=omparable$=ard& tells users of the Qard class that I intend to write a meaningful ompare(o() method in this class. &he String class also implements =omparable.

"tatic #onstants :Optional;


1ot e ery class will ha e static constants. &here is also a better way to achie e what I am using these static constants for, but for the purposes of this example, it is sufficient. &he final modifier tells $a a that these are constants and cannot change while the program is running.

-ields :%ttributes<Instance !ariables;

&hese are the ariables that describe what a Qard is. &o completely describe the meaningful information about a card, it is necessary and sufficient to !now the card.s suit and alue. #ny more information than this is extraneous, and any less is insufficient. (y these two criteria do I declare this a good data representation of a Qard. If the game has a Wraphical Interface and I am a la"y programmer, then I might include an image in this set of necessary and sufficient informatione en in that case though, the suit and alue should be sufficient information to deri e the location of image data. 1ote that the instance ariables are indicated in %clipse by blue normal weight non-italics text. It is also important to notice that the access le el modifier is private. 3ields in a well-written, wellplanned class are always pri ate. &his is to pre ent the data from being changed externally, and potentially improperly. &his method of protecting data is called data hidin#. It is an important practice partly for philosophical reasons. In the mindset of 'bject 'riented programming, your class is a selfcontained organism of sorts. 0ou can.t externally change attributes of objects without using the tools made a ailable on the object itself. Some attributes simply should not, and cannot be changedsuch as the suit and alue of a Qard. Qontrolling the change and access of pri ate data is the job of a special class of methodsAccessors and /utators.

%ccessors
#ccessor methods grant read-only access to the data in a pri ate field. Tsually, the return type of an accessor method is the same as the data type of the field it is accessing, howe er, in this case, the integer fields correspond to Strings in the STI&S and 6#5T%S arrays. &his is another reason for using data hiding. I ha e stored the data for the card in a smaller format Binteger s. a StringD. 3or a definition, an accessor method is a method which returns the alue of a field Bor some

deri ation of the alue of a fieldD but does not change any data. #ccessors are usually named with RgetS as a prefix. &he toString() method is a special accessor method. &his is the method that is called when an instance of the class is put in a print() or println() statement. It.s a useful method to include in a class.

1utators
&his class does not contain any mutator methods. &his is because a Qard, once created, cannot change its alue or suit. 2utator methods are used to change the alue of fields in a particular instance of a class. &he ad antage of using a mutator method, ersus simply allowing direct write access to the field itself, is that I can alidate the data being stored into the field before actually ma!ing a change. #n example for the Qard class might loo! li!e the setSuit() method abo e. 2utators usually are named with the RsetS prefix.

# mutator method is usually void. *owe er, this is not always true. 0ou may choose to return a (oolean or some other indicator to gi e a status response to whate er called the mutator method. &his method could be written as follows and ha e this effect.

&here are other appropriate ways of sending this status message bac! to where er the method was in o!ed, also.

#onstructor 1et&ods
#ny class that will ha e instances Bthat is 'bjects of that typeD must ha e at least one constructor method. &he constructor initiali"es all the fields in the object with dataeither default alues, or alues that are passed as parameters to the constructor.

It is the constructor.s job to erify the alidity of data before creating the new object. &he Qard class has only one constructor because a Qard must ha e suit and a alue. &here are se eral reasons why a class might ha e multiple constructors. 'ne such example is a de$ault constructor which simply sets all the fields to a predetermined default alueessentially creating a generic instance of the object. #nother standard constructor type is called the copy constructor which ta!es as the same data type as a parameter.

2ore complex objects often ha e multiple constructors because you can communicate information to be stored into fields in more than one way. &he most important attribute of the constructor method is its signature. &he constructor method must ha e no return type, not e en oid, and it must ha e the same name as the class that it is written in.

Instance 1et&ods
Instance methods are the beha iors of an object. &hese are the things an object can do, or things that the object allows to happen to itself. In this class I ha e written only one instance method+

1nstance /ethods are referenced by using the ?.. operator on an instance of the classhence instance method.

Problem ,
/. -hat is the meaning of the !eyword this) 8. 4ownload the source code for the 4ec! class. Pead the code and write notes in your journal on any parts of code that you ha e not seen before. Pesearch online to try to understand those parts. -rite a summary of what you find. 7. 4escribe how the s!uffle() method wor!s. =. 4escribe how the riffleS!uffle() method wor!s.

Exploration4
4ownload the source code and analy"e the Qard Wame project. &he project is in a $#P fileyou can import this directly into %clipse by following the tutorial in the #ppendix section at the end of this text. Pecord notes on any code that you do not understand. Tsing %clipse, ho er your mouse pointer o er ariables, class names, and methods to see documentation.

(e sure to write notes about which classes I wrote, and which classes are built into $a a. Tse the rightclic! menu to find definitions, and na igate through the code Open !eclaration '23) is a particularly useful toolC

Week =1odeling Data using #lasses


*ere.s a problemI want to write a program that will produce the 2orning 2eeting seating chart for me. *ow do I attac! this problem) 0ou may feel li!e you can jump right in and sol e the problem immediatelyand maybe you canC (ut let.s slow down and loo! at the problem first. I need to !now a great deal of information to be able to uniquely determine a seating chart. &he first thing I need to do is lay out the specifics of the problem. In the end, what do I want to ha e) &he first step to sol ing any major problem is usually to research what a solution needs to loo! li!e. In this case, a non-programmer may gi e you specifications li!e this+ RSeniors sit in the front rows, then $uniors, then Sophomores, and 3reshman sit in the bac!.S &hin!ing li!e a programmer, we need to loo! ery closely at this requirement. Is this sufficient information to determine what the seating chart should loo! li!e) -hat information does this description assume that you !now) Is anything left to arbitrary chance)

%nal >ing t&e Problem


&here are two major lines of thought going on simultaneously here. 'ne is, R-hat do I need to do with the data I am gi en)S and the other is, R*ow is the data organi"ed so that I can manipulate it)S &he choice of which to tac!le first is a style choice. # Top-!o%n approach would answer the R-hat do I need to do,S question first, and then deri e the data organi"ation from your results. # Bottom-.p approach starts from the raw data, and attempts to model the situation, and then deals with manipulation of distinct 'bjects once they are well defined. I ha e found that the (ottom-Tp approach suits the way I thin! best in most cases, and I ha e designed this example to be easier in a (ottom-Tp approach, so let.s attac! it that wayC 5et.s start with a rough s!etch of how our problem loo!s. &he final product should be a seating chart that models the Pecital *allso let.s find out a little more about the Pecital *all. Since you can.t ery well collect this data on your own right now, I.ll gi e you some statistics. Pows #-5, of arying si"e. Pow # has /9 seats Pows (-* ha e /= seats eachbut 2r. (ates sits in (-/=C Pow I has /9 seats

Pows $ and Z ha e // seats Pow 5 has /= seats. # clear starting point is to model the Pecital *all and fill it with Students. -hat are the necessary and sufficient components to include in our Pecital*all 'bject and Student 'bjects) &here are many correct ways to answer this question. I am going to ta!e a ery literal approach to my Object /odel. I am going to say this+ The (ecital4all has (o%s5 A (o% has Seats5 A Seat may or may not have a Student occupant. Aay ery close attention to the words that I use to describe the model. % ery word, including articles, in the statement has an important meaning. 5oo! for singularity s. plurality and definite s. indefinite articles. &o the right is a diagram of what I ha e described. &he arrow represents the RhasS relationship. %ach bloc! represents a Qlass we will write in $a a. #t this point we can begin to acutally start s!etching these objects in code. In %clipse create a new Aroject, and create these four classes inside that project.

5ea e the student class empty for the moment, because we ha e yet to determine what is important to it. 5et.s complete the modeling of the Pecital *all itself first. Zeeping in the (ottom-Tp perspecti e, let.s start with the simplest object first.

class Seat
% ery class Bthat is not purely staticD must ha e a Qonstructor method. # Seat is pretty straight forward. # seat starts out %mpty. (ut, we may add a student to the seat. Qomplete the Seat class as follows+

&he assignStudent() and getStudent() methods are our important #ccessor and 2utator methods. &he next le el up is slightly more complicated.

class Row
1ot e ery row has the same number of seats. So our constructor method needs a parameter telling it how long to be. *owe er, once it is initiali"ed, the row cannot change the number of seats it hashence there is no mutator method directly accessing the .rrayList$Seat& seats. I do, howe er, need to be able to pass down a student assignment.

Exercise
-hy is the code in the assignStudent() method of the >ow class so complicated) -hy can.t I say something li!e this.seats.get(seat1umber).assignStudent(student); )

class RecitalHall
&he Pecital*all class is where we do the real construction of our model. -e will build the constructor for the Pecital*all to mimic the real recital hall. I will now create the recital hall based on the data pro ided earlier in this section.

&his completes the data structure into which we will insert Students. &he last piece of data we need to model is a Student.

1odeling #omplex Data


# Student is a much more complicated piece of data than a Seat in the Pecital *all. -hen modeling data to sol e a problem it is of utmost importance to ha e a clear idea of what you need to !now, and what data is sufficient to completely fill your needs. &o determine how to best model a student for the purpose of filling in the seating chart, I need to !now a little about how the seating chart is filled inparticularly, what information determines where a particular student will sit) #nswering this question requires some researchluc!ily, I ha e already done that research for youC Students are seated in the recital hall by grade le el first, then by alphabetical order using family name first. Students, being people, ha e a lot of attributes that may or may not be rele ant to the problem at hand. 3or example, the schools information system stores arious biographical data on all students ranging from parent contact info, to student age and citi"enship status. 2ost of this data has absolutely no effect on what seat you get in 2orning 2eeting. &he only data that is rele ant to your morning meeting seat is your name, and your #rade level.

2odel the student in code accordingly+

&he Student class completes the data model. %ach class is outfitted with its inter$aceall the public methods associated with a gi en classand attributes.

Problem =
Qomplete the fillSeating=!art() method in the Pecital *all class. 0our algorithm should follow something along the lines of+ /D Sort the list of students using the ompare(o() method, 8D iterate o er the sorted list of students inserting each into the next seat empty seat in the recital hall.

Sounds easy enough, right) (onus points if you can ma!e sure that (rad (ates always gets the last seat in row (C

Week ? @ -inal Project


-rite a simple text based interacti e Rgame.S 0our game should include the following things+ # Alayer with a name B(onus for adding a bac!pac! to put Items inD, Items that exist in the world and can be Rloo!edS at B(onus for Rpic! upS alsoD, and #reas which ha e items to loo! at or interact with. 3or some inspiration, you can download an empty shell for this project that I ha e written. 0ou.ll need to fill in all the details, but it has some structure to it. 0ou are not required to use my templatethere are many ways to tac!le this problem. I do definitely suggest that you use my =ommand*arser class. I don.t expect you to be able to come up with this on your own yetC &he command parser is ery basic it handles one and two word commands, but doesn.t do any logic with processing those commands. It encapsulates a Scanner for the !eyboard, and has one major public method+ get1ext=ommand(). &he command consists of the first and last word in the line typed by the user. &he first word is assumed to be a erb, and the last word is the direct object of the erb. If there is only one word, it is assumed to be a erb with no direct object.

)ubric
#riteria
Syntax Qode wor!s and is alid $a a code. 4ata types are initiali"ed properly, and reflect proper form. Formatting Source code is formatted in a standard way. Qode is easy to read, and X,Y ha e proper indenting. Completeness Wame is playable and has at least > interconnected areas. &here are items in the areas that the player can interact with.

Point !alues
40

20

40

%ppendix IEclipse
Eclipse IDE
&here are many I4%s a ailable for de eloping $a a. I use %clipse I4% for $a a 4e elopers. &he lin! has a listing of many, many different fla ors of %clipse. 2a!e sure to grab the right oneotherwise it will be really confusingC

0ava Projects
%clipse organi"es your programs into projects. # project contains at most one executable Arogram class. &he project structure also contains all your different code files together so that they can be interdependent.

In %clipse, create a new Aroject in your wor!space by clic!ing 3ile-1ew Aroject, or clic!ing the new Aroject button on the tool bar.

Qlic! 1ext, name the project, and clic! 3inish. 0our new project is now a 3older in the Aac!age %xplorer tab. &o add items to the Aroject, right-clic! on the src directory, and select the !ind of item you want to add from the 1ew menu. &o create a ja a file that you can write code in, select Qlass.

3ill in needed information and clic! 3inish.

Writing our -irst Program

#fter creating a class in a project, you are presented with a blan! file. If you chec!ed the box for a main method, it will automatically generate the main method signature. (egin typing your code in between the X , Y after the main method signature.

Start writing code now. Pemember that you must write commands inside a method. &he second layer of X , Y indicate a method. &his program will simply print the message R*ello QomputerCS to the Qonsole. &ry running this program now.

)unning a Program in Eclipse


&o run a program in %clipse, there are two major prerequisites. 3irst, the program must be inside an %clipse Arojecteither imported from somewhere, or created by you as indicated in the pre ious sections. #nd second, the program must contain a class with a main method--public static void main(String+, args).

'nce these conditions are met, you need only clic! the green Pun button on the toolbar.

-hen the program is run, it is usually good to !now where the output is going to happenC %clipse !eeps its Qonsole within the program. (y default, the tab is in the bottom tray.

0ou can resi"e it or mo e it around as you wish.

If your program requires user input, you will type into this Qonsole as well.

Importing a Project from a 0%) file


In %clipse, open 2ile -6 1mport. Tnder General, select Existin# Projects into 7or*space.

Qlic! 8ext 6, and Select archive $ile9

(rowse to the location of your downloaded $#P file and Open. 2a!e sure that your project is chec!ed in the Arojects pane.

Qlic! 2inish. &here is a potential issue that can happen here. If project loo!s li!e this, then you need to follow these additional steps. Pight-clic! on the Aroject title, and create 1ew 3older src5 your

called

Qlic! and 4rag the root folder of your imported code to the src folder. In my example, the root folder is or#5 0our project should now loo! li!e this+ 1ow you.re ready to goC

"ource #ode -ormatting in Eclipse


&here are a number of standard accepted ways to format your code, just li!e there are se eral generally accepted ways to format your writingbloc! paragraphs s. indented paragraphs for example. 0ou may ha e noticed that I write in bloc! paragraphs. 2y code also ascribes to a particular writing style as well. In %clipse, you can set style choices and then fix your code so that it adheres to your formatting choices. 2y particular style is not the default style in %clipse. (efore turning in a Aroject, it is polite to format your code nicely. #s long as you use some generally accepted style, I will be able to read it. I will howe er, ta!e off points for code that is so poorly formatted that I ha e trouble reading it. &ry this out+ ta!e some code that you ha e downloaded from a lin! in this textthe dec! class for example. In the Aac!age %xplorer, locate the 4ec!.ja a file. Pight clic! on the file and locate (ource )* +ormat.

Qlic! 3ormat, and see what happens to my code. 0ou can set the preferences for your code formatting by going to ,indow )* -references.

In the Areferences window, follow the tree down to .ava )* /ode (tyle )* +ormatter.

0ou can edit the default style and sa e it as your own if you choose to. &he settings that I prefer to change mostly ha e to do with indentation, braces, and white spaces. 0ou can Import, my code style by downloading my style settings.

%ppendix II0ava #oncepts


1ain 1et&odmaking an executable program'
In a Aroject in your I4%, to actually run your program, you must ha e a main method. &his main method must ha e the following si#nature. 1o exceptions.

&here can only be one such method in the Aroject. 1o matter how many files you ha e in the project, only one can contain a main method. &his is where your code begins executing. #s a general rule, when I write programs that are intended to be executable, I put the main method in a class called Arogram, and only include the main method, and any static methods that the main method uses specific to this project.

Packages
In the wide world of $a a programming, there are a lot of people wor!ing. Sometimes two people might name things the same. $ust li!e websites ha e a unique TP5 and computers within a networ! ha e unique IA #ddresses, If you are going to ma!e your code publicly a ailable, then you should gi e your code a pac*a#e uri that uniquely identifies your wor!. 3or my programming classes, I use the pac!age base, org.dublins !ool to uniquely identify wor! that I do for classes. %ach class gets a pac!age within this big pac!age, and each project within a class gets a third layer. &herefore a pac!age declaration for a project in one of my classes might loo! li!e this+

&he project is titled 4eclaring 6ariables, and is used for #A Qomputer Science. &his allows me to reuse common class names, e en if I lump all of my code together. So, org.dublins !ool.ap omps i. ardgame.*rogram is a different Arogram class than org.dublins !ool.ap omps i.bigint al .*rogram is.

%ppendix III0avaDoc Documentation


)eading 0avaDoc Webpages
"ava!oc is the specially formatted documentation for $a a classes. &he entire $a a standard library is documented in absolute detail online. &he root for the $a a4oc archi e can be found on 'racle.s website. *owe er, it is often easier to locate the $a a4oc you.re loo!ing for by simply typing Rja adoc Eclass nameFS into a Woogle search. $ust ma!e sure you grab the result for the proper ersion of $a a. &he latest ersion is $a a Alatform S% L. &he page you are presented with is organi"ed into se eral parts+ /. Qlass.s inheritance hierarchy, and interface implementations

a. #t this point, it is enough to !now that any .rrayList can be substituted for any of the different types that are pointed to by blue arrows. &he red arrows indicate objects that can be substituted for an .rrayList, and, by proxy, any other target of a blue arrow. b. -e will learn more about the class hierarchy in the 3all and -inter terms. 8. Qlass signature and description a. &he signature is the actual $a a syntax that implies the abo e diagram.

b. &he description is anoften highly technicalwrite up of what the class is intended to do. #s a no ice, you may get lost in the ocabulary, but most classes that you will deal with should ha e some tidbits that you can understand. &he important stuff comes next. 7. 3ield Summary a. Parely of interest, lists all public instance ariables belonging to this type of 'bject. =. Qonstructor Summary a. #5-#0S of interest, the constructor methods are the different ways that you can initiali"e an instance of this 'bject.

b. Pecall that in the second constructor, =olle tion can mean .rrayList ma!ing this a constructor which copies an existing #rray5ist. c. 2ethod Summary

d. Arobably the most important section, this gi es a brief description of e ery public method in this class.

e. &he 2odifier and &ype shows the return type of the method in the second column. f. Qlic! on a method name to scroll down the page to the full documentation for that specific method.

Important !ocabular
A
accessor arithmetic operator assi#nment operator assi#nment statement attributes a method whose job is to grant read access to a particular field of an object, or organi"e data into a useful output. #!a [getters[ operators that are used in arithmetic expressions. single equals sign when used in an assignment statement. a statement of the form $%ariable& 0 $expression&; data used to describe an object\s state

B
boolean al#ebra boolean operator bottom-up desi#n arithmetic algebra of ariables with only two possible alues. Btrue and falseD operators that are used in boolean expressions. Qorrespond to+ #nd UU, 'r VV, and 1ot C method of problem sol ing in which the sol er starts from the most basic constituent systems and combines them together to form larger more complex systems until the final product is achie ed.

comparison operators complex data type conditional statement constructor operators whose resultant data type is boolean. a data type that is represented by a ja a class and must be initiali"ed with a constructor method. a statement bloc! initiated by the !eyword i$ that directs the flow of code down exactly one path and executes once before exiting the bloc!. a special type of method responsible for initiali"ing an instance of a class. &he constructor method has no return type--not e en oid--and has the same name as the class itself. 0ou may declare multiple constructors with different sets of parameters. a type of statements that influences the flow of code.

control statement

!
data data hidin# data structure data type information that can be stored in binary form in the computer\s memory. protecting data by ma!ing fields pri ate and allowing access only ia accessor and mutator methods. logical organi"ation of data in memory, storage, as fields in a class, or relations between classes !eyword that determines the amount of memory allocated for a particular

ariable, as well as what !ind of data may be stored in said ariable.

E
element 'o$ an array) a ariable corresponding to one location within an array type ariable. %xample+ int+, numbers 0 ? 84 34 54 2 @; : is the I7J element of numbers -- numbers+5, combining of data and methods into a single logical entity. the boolean expression which triggers the end of a loop when the it e aluates to true.

encapsulation exit condition

2 G
#lobal variable a ariable whose scope is the entire program. It\s generally poor form to use global ariables, constants are acceptable.

4 1
index 'in an array) instance 'o$ an Object : class) iteration 'noun) iteration 'process o$) iterator integer used to identify a specific element in an array. &he first index in an array is 9. an 'bject as it exists stored in memory. one run through of the statement bloc! associated with a loop. the act of going step by step through a repeating algorithm. an object responsible for wal!ing element by element through a collection.

" ;
*ey%ord a word that has special meaning to the $a a compiler.

0
loop a statement bloc! initiated by either $or, %hile, or do , %hile that directs the flow of code to repeat until an exit condition is met.

/
method method call a statement bloc! gi en a name so that the bloc! can be referenced at need. in o!ing the statement bloc! of a method by referencing the method\s name. Integer.parseInt(A529A) calls the parseIntBD method in the Integer class, gi ing it the parameter [7:=[. the practice of writing multiple methods with the same name, but different

method overloadin#

sets of parameters. mutator a method whose primary job is to change the alue of fields in an object, a!a [setters[

8 O
object model a!a T25 4iagram, a isual representation of the class structure of a project. Shows class names, attributes, and method signatures for each class as well as relational mar!ings. the direct object of an operation. In the expression Bx K yD, x and y are operands, and K is the operator a symbol that in o!es a particular action on its immediate neighbors in the statement. B%xample+ K is an operator in the statement x H 7 K :GD

operand operator

P
parameter a ariable that is passed to a method ia the method signature. &he parameter is passed-by- alue always, no changes to the ariable within the method will be retained when the method exits. refers to ariables being transferred from one scope to another ia parameters in a method call in the following fashion+ the memory address of the ariable is added to the target scope, while still remaining in the origin scope as well, allowing the ariable to be changed in either scope. &his paradigm is not a ailable in $a a. refers to ariables being transferred from one scope to another ia parameters in a method call in the following fashion+ a new ariable is created in the target scope, and is assigned the alue of the ariable in origin scope. a data type that is built into the core of the programming language and has special literal representations of its alues. BSee corresponding table for examplesD a project with a runnable main class.

pass-by-re$erence

pass-by-value

primitive data type

pro#ram

< (
return statement in ocation of the !eyword return to exit a method. If the void return type is used, return; is alid--otherwise return must be followed by a ariable or expression e aluating to the declared return type. the data type of the ariable or expression used in the return statement from a method. 4efined in the method signature. 'nly one return type is allowed per method.

return type

S
scope 'o$ a variable= method= class) refers to the statement bloc! to which a ariable, method, or class belongs. # ariable is only accessible in the statement bloc! that it is declared, and child-bloc!s of that statement bloc!. Aarent statement bloc!s, and sibling statement bloc!s will not be able to access the ariable. a ery simple straight forward program--not usually written in $a a. a (oolean ariable or expression that corresponds to the exit condition for a loop a fixed si"e collection of memory allocations all of the same data type, and referenced as a whole by one ariable name. the current alues of all attributes in a gi en instance of an 'bject. a single syntactic phrase in code usually terminated by a G a group of statements surrounded by X,Y for the purpose of flow control a method or ariable that is accessed without reference to a specific instance of a class. data type used to represent words. 5iterals are surrounded in [doublequotations[ computer programming grammar

script sentinel standard array state 'in re$erence to an Object) statement statement bloc* static 'method or variable) Strin# syntax

T
top-do%n desi#n method of problem sol ing in which the sol er starts with a complex o er iew model and iterati ely brea!s it down into smaller and smaller subsystems, until each is expressible in small easily manageable systems. the defacto con ersion of one data type into another using the syntax of BEtarget&ypeFDBE ariableFD

type cast

. >
variable a placeholder in the computer\s memory that holds a unit of data. #ll ariables must ha e an associated data type

7 ? @

A
,ritten 0y .ason /o1

Illustrations ta2en from ]ZQ4.com 3his 0oo2 is provided free of charge as a companion to my Basic .ava summer online course% 3his 0oo2 may 0e copied and redistri0uted as much as you wish# as long as you dont charge money!

Vous aimerez peut-être aussi