Library Home

Java, Java, Java: Object-Oriented Problem Solving

(4 reviews)

java java java object oriented problem solving pdf

Ralph Morelli, Trinity College

Ralph Walde, Trinity College

Copyright Year: 2016

Publisher: Ralph Morelli, Ralph Walde

Language: English

Formats Available

Conditions of use.

Attribution

Learn more about reviews.

java java java object oriented problem solving pdf

Reviewed by Onyeka Emebo, Assistant Professor, Virginia Tech on 12/28/21

The text adequately addresses areas under Object Oriented Programming using Java as a Programming Language for Introduction to Computer Science courses. It gently introduces basic concepts in computer, objects and java using problem solving... read more

Comprehensiveness rating: 5 see less

The text adequately addresses areas under Object Oriented Programming using Java as a Programming Language for Introduction to Computer Science courses. It gently introduces basic concepts in computer, objects and java using problem solving approaches and gradually builds up to more advanced Java technologies in such a simplified manner that can be easily understood. The text also provides a table of content at the beginning and a summary of points for each chapter with exercises.

Content Accuracy rating: 4

The text content is accurate, without errors and unbiased. There is however some links that needs to be updated.

Relevance/Longevity rating: 4

While the field of computer science with particular emphasis to programming as it relates to this text is constantly evolving, the approach taken by this text to teach the essentials is likely to persist. The code, tested in Java 8, should continue to work with new Java releases. Updates to the text can be done easily by the way it has been written.

Clarity rating: 5

The text is written in a clear and easy to understand manner. The objectives, explanations, examples and exercises are clear and easy to follow. The codes are well commented to aid readability.

Consistency rating: 4

The text is highly consistent in both structure and terminology. It starts each chapter with objectives and outline and concludes with summary, exercises and solutions. However, some codes within the chapters are put in figures while others are not, this could be confusing.

Modularity rating: 5

The text is divided in 17 chapters (0 - 16) and 8 appendices (A – H). Each chapter is further divided into sections and subsections. This breakdown makes it easier for instructors to apportion sections to students at different times within the course.

Organization/Structure/Flow rating: 5

The text is organized in a manner that is logical and it flows well from section to section. The structure makes navigation from chapter to chapter easier.

Interface rating: 3

I reviewed the PDF version and it looks good to a large extent. The links in the table of contents are working properly. There are clickable links within the text to different figures, sections, such as appendices, and external websites. However, there are some issues with some figure titles, e.g., figure 12, 1.10, 2.7, 2.10, 2.14, etc. are cut off. Some hyperlinks for some figures missing e.g., figure 2.8 and some figures don’t have titles.

Grammatical Errors rating: 5

The text contains no grammatical errors.

Cultural Relevance rating: 5

The text is culturally neutral. The examples are unbiased in the way it has been presented.

Reviewed by Ghaith Husari, Assistant Professor, East Tennessee State University on 4/17/20

This book covers Object-Oriented Programming under JAVA. It introduces the concepts of object-oriented programming and they are used for problem-solving. This book covers all the relevant areas of Object-Oriented Programming under Java. Also, it... read more

This book covers Object-Oriented Programming under JAVA. It introduces the concepts of object-oriented programming and they are used for problem-solving. This book covers all the relevant areas of Object-Oriented Programming under Java. Also, it covers more advanced topics such as socket programming and algorithms.

Content Accuracy rating: 5

The Object-Oriented concepts and implementation example shown in code samples are accurate and easy to learn as the code samples are aligned with the concept being discussed. Some links and URLs are out-dated but they have little to no impact on student learning. However, I would add a note that says "some of the links and URLs might not up-to-date. However, they can be found using search engines if necessary"

Programming languages get updated regularly to include new and easier functions to use. While it is impossible for a textbook to include every function, this textbook provides a great learning opportunity that allows students to build the muscle to be able to learn more about Java online. When it comes to Object-Oriented concepts, the book is extremely relevant and up-to-date

The textbook is very easy to understand and the code sample is both clear (code readability) and relevant.

Consistency rating: 5

The text and the terms it contains are consistent. Also, the textbook follows a consistent theme.

The textbook chapters are divided into sections and subsections that are shown also in the table of contents which can be used to visit each section.

The textbook consists of seventeen chapters that are organized in a logical manner. The more general concepts such as problem-solving and programing are placed at the beginning, then the chapters introduce the discuss Object-Oriented Programming come after the general chapters. The more advanced topics such as socket programming and data structures and algorithms come towards the end. This made a lot of sense to me.

Interface rating: 5

The textbook is easily accessible online and it can be downloaded to open with Edge or Adobe Reader without any problems.

No grammar issues have been noticed.

This textbook is neutral and unbiased.

Reviewed by Guanyu Tian, Assistant Professor, Fontbonne University on 6/19/18

This textbook covers Object-Oriented Programming with Java programming language pretty well. It starts with the concept of Objects and problem solving skills and then dive into Java programming language syntax. Overall, it appropriately covers all... read more

Comprehensiveness rating: 4 see less

This textbook covers Object-Oriented Programming with Java programming language pretty well. It starts with the concept of Objects and problem solving skills and then dive into Java programming language syntax. Overall, it appropriately covers all areas of the subject including the main principles of Object-Oriented Programming and Java programming language. In the later chapters, this textbook also introduces advanced topics such as concurrent programming, network/socket programming and data structures. The textbook provides table of contents at the beginning and index of terms at the end. Each chapter also provides a list of key words and a list of important concepts and technique terms.

Content Accuracy rating: 3

The content of the textbook is mostly accurate. Many URLs linked to Java documentations and APIs are not up-to-date.

Many URLs to Java references are not up-to-date and many online samples are not accessible. Nonetheless, the concepts of Object-Oriented Programming and Java programming language syntax are mostly current. Any updates to the contents of the textbook can be implemented with minimal effort.

The text is easy to understand. However, some of the texts are not displayed on adobe reader.

Consistency rating: 3

The text is consistent in terms of framework. Each chapter starts with introduction to a problem, and then discussion and design of the solution with UML diagrams; then Java is used to implement the solution(s). However, there is some level of inconsistency in terms of Java code samples. For example, some Java code examples use appropriate indentations and new lines, but some examples do not. This may confuse students.

Each chapter is divided into different sections and subsections. A student can go to each section of a chapter by clicking it in the Table of Contents.

Organization/Structure/Flow rating: 3

The topics in this text book are organized in a reasonable order. It starts with general concepts of computer and program design, then Objects and Java Programming Language, and then advanced topics in computer programming. It would be better if the textbook starts with Java programming language and then principles of Object Oriented programming.

Some of the texts are not displayed in the reviewer's adobe reader. Many diagrams and figures are poorly drawn. Overall, the interface of the book is one area that needs improvement.

No major grammar issues has been noticed.

The text of this textbook is a neutral and unbiased.

Overall, this textbook covers materials of Object-Oriented Programming with Java taught in first or second-year computer science course. However, the contents of Java programming language has not been up-to-date and the interface of the book is very poor compare to similar books the reviewer has used for learning and teaching the same materials. Some sample codes are not well written or inconsistent in terms of the use of indentation and new lines. Many URLs are obsolete and the web pages are not accessible.

Reviewed by Homer Sharafi, Adjunct Faculty Member, Northern Virginia Community College on 6/20/17

The textbook includes the material that is typically covered in a college-level CS1 course. Using an “early objects” approach and Java as the programming language, the authors go over problem-solving techniques based on object-oriented... read more

The textbook includes the material that is typically covered in a college-level CS1 course. Using an “early objects” approach and Java as the programming language, the authors go over problem-solving techniques based on object-oriented programming principles. In addition to an Index of terms towards the end of the text, each chapter summary includes the technical terms used, along with a bulleted-list of important points discussed in that chapter.

The computer science concepts and the accompanying sample code are accurate and error-free; however, the only issue is the fact that the URLs that make references to various aspects of Java, such as API documentation, JDK, and the Java Language Specification, have not been updated to reflect the fact that Sun Microsystems was acquired by Oracle back in 2010.

Like other software systems, Java is updated on a regular basis; nonetheless, the computer science concepts discussed in the textbook are based on standard undergraduate curriculum taught in a CS1 course. Therefore, any updates to the textbook would need to be with regard to the version of Java with minimal effort.

Clarity rating: 4

The authors deliver clear explanations of the computer science concepts and the accompanying Java language features.

There is a consistent theme throughout much of the text: A topic is introduced and discussed within the context of a problem. Its solution is then designed and explained using UML diagrams; finally, Java is used to illustrate how the solution is implemented on the computer.

Each chapter is divided into sections that can easily be identified within the table of contents. Therefore, it’s fairly easy for a student to pick and choose a section in a chapter and work on the other sections later. Throughout each chapter, there are self-study exercises to incrementally test understanding of the covered material. Solutions to those self-study exercises are then provided towards the end of the chapter. In addition, each chapter includes end-of-chapter exercises that can be used to assess one’s understanding of the computer science concepts as well as the various features of Java.

The book consists of seventeen chapters; however, a typical CS1 course would need the material in the first ten chapters only, and those chapters are set up in a logical manner, allowing one to go through the material sequentially. Depending on how fast he first ten chapters are covered during the course of a semester, an instructor may choose from the last seven chapters in the text to introduce more advanced topics in computer science and/or Java.

Interface rating: 1

The textbook can be accessed online or opened using Acrobat Reader with no problem. There are no issues, as long as navigation is done one page after another manually. However, when browsing through the table of contents (TOC) or the Index, the entries are not set up using any live links. That is, you cannot click on a page number associated with an item within the TOC or the Index to go directly to that page.

Grammatical Errors rating: 3

This reviewer did not come across any such issues, while going through the text.

This is a computing textbook, where the contents are presented using technical terms. Culturally, the textbook is completely neutral and unbiased in terms of how the material is presented.

Table of Contents

Ancillary Material

About the Book

We have designed this third edition of Java, Java, Java to be suitable for a typical Introduction to Computer Science (CS1) course or for a slightly more advanced Java as a Second Language course. This edition retains the “objects first” approach to programming and problem solving that was characteristic of the first two editions. Throughout the text we emphasize careful coverage of Java language features, introductory programming concepts, and object-oriented design principles.

The third edition retains many of the features of the first two editions, including:

The In the Laboratory sections from the first two editions have been moved onto the book's Companion Web Site. Table 1 shows the Table of Contents for the third edition.

About the Contributors

Ralph Morelli, Professor of Computer Science Emeritus. Morelli has been teaching at Trinity College since 1985, the same year the computer science major was first offered. More recently, he was one of the Principal Investigators (PIs) for the Humanitarian Free and Open Source Software (HFOSS) project, an NSF-funded effort to get undergraduates engaged in building free and open source software that benefits the public.  In summer 2011 a team of Trinity HFOSS students and faculty traveled to Haiti to build an open source mobile application that helps manage beneficiaries for a humanitarian aid organization. Currently Morelli is the PI of the Mobile CSP project, an NSF-funded effort to train high school teachers in CT and elsewhere to teach the emerging Advanced Placement CS Principles course that is being created by the College Board. The main goal of this NSF initiative is to increase access to computer science among underrepresented groups, including girls, African Americans, and Hispanic Americans.  The Mobile CSP course teaches students to create mobile apps to serve their community.  In summer 2014, a group of 20 Mobile CSP students spent their summer building mobile apps for the city of Hartford. 

Ralph Walde.  Dr. Walde has given Trinity 28 years of distinguished service, first as a Professor of Mathematics and now as a Professor of Computer Science. He was instrumental in helping to establish and nourish computing at Trinity and was one of the founding members of the Computer Science Department.

Contribute to this Page

Academia.edu no longer supports Internet Explorer.

To browse Academia.edu and the wider internet faster and more securely, please take a few seconds to  upgrade your browser .

Enter the email address you signed up with and we'll email you a reset link.

paper cover thumbnail

Java, Java, Java Object-Oriented Problem Solving

Profile image of Paolo scientifico

We have designed this third edition of Java, Java, Java to be suitable for a typical Introduction to Computer Science (CS1) course or for a slightly more advanced Java as a Second Language course. This edition retains the “objects first” approach to programming and problem solving that was characteristic of the first two editions. Throughout the text we emphasize careful coverage of Java language features, introductory programming concepts, and object-oriented design principles.

Related Papers

cs.potsdam.edu

java java java object oriented problem solving pdf

An integrated development environment (IDE) monitors all the changes that a user makes to source code modules and responds accordingly by flagging errors, by reparsing, by rechecking, or by recompiling modules and by adjusting visualizations or other information derived from a module. A module manager is the central component of the IDE that is responsible for this behavior.

Franco Raimondi

We address the problem of verifying planning domains as used in model-based planning, for example in space missions. We propose a methodology for testing flight rules of planning domains which is self-contained, in the sense that flight rules are verified using a planner and no external tools are required. We review and analyse coverage conditions for requirements-based testing, and we reason in detail on" Unique First Cause"(UFC) coverage for test suites.

Vivek Jadli

Shakeins are a novel programming construct which, like mixins and generic classes, generates new classes from existing ones in a universal, uniform, and automatic manner: From a given class, a shakein generates a new class which has the same type as the original, but with different data and code implementation. We argue that shakeins are restricted, yet less chaotic, aspects. We further claim that shakeins are well suited for the introduction of aspect-oriented programming (AOP) into existing middleware applications. We introduce the AspectJ2EE language which, with the help of shakeins and a new deploy-time weaving mechanism, brings the blessings of AOP to the J2EE framework. A unique advantage of AspectJ2EE, which is less general (and hence less complicated) than AspectJ, is that it can be smoothly integrated into J2EE implementations without breaking their architecture.

Josep Torrellas

Proceedings of the 22nd …

Albert Zündorf

This paper proposes to use SDL block diagrams, UML class diagrams, and UML behavior diagrams like collaboration diagrams, activity diagrams, and statecharts as a visual programming language. We describe a modeling approach for flexible, autonomous ...

Volker Sander

Roscoe Bartlett

Brian Schott , Brad Hutchings

SLAAC assembled a multidisciplinary team with expertise in signal processing, design tools and adaptive architectures to develop distributed adaptive computing systems (ACS) and methodologies for Defense processing. SLAAC was organized around challenge applications that collectively guided the research, including: Synthetic Aperture Radar/Automatic Target Recognition (SAR/ATR), SONAR Beamforming, Wide-Band RF Receiver Processing Hyperspectral Image Processing, Electronic Counter Measures (ECM), and Infrared ATR. The challenges were selected to stress ACS systems in dimensions of computational density, memory bandwidth and latency, I/O bandwidth, and scalability. SLAAC had technology transitions in SAR, SONAR and ECM.

Loading Preview

Sorry, preview is currently unavailable. You can download the paper by clicking the button above.

RELATED PAPERS

Markus Stumptner

Mike Manary

Gary Leavens

jean-luc Dekeyser

RELATED TOPICS

Functional and flexible, this guide takes an objects-first approach to Java programming and problem using games and puzzles.

We have designed this third edition of Java, Java, Java to be suitable for a typical Introduction to Computer Science (CS1) course or for a slightly more advanced Java as a Second Language course. This edition retains the "objects first" approach to programming and problem solving that was characteristic of the first two editions. Throughout the text we emphasize careful coverage of Java language features, introductory programming concepts, and object-oriented design principles.

Table of Contents:

The third edition retains many of the features of the first two editions, including:

Due to a planned power outage on Friday, 1/14, between 8am-1pm PST, some services may be impacted.

Internet Archive Audio

java java java object oriented problem solving pdf

java java java object oriented problem solving pdf

java java java object oriented problem solving pdf

java java java object oriented problem solving pdf

java java java object oriented problem solving pdf

Search the history of over 800 billion web pages on the Internet.

Mobile Apps

Browser Extensions

Archive-it subscription.

Save Page Now

Capture a web page as it appears now for use as a trusted citation in the future.

Please enter a valid web address

Java, Java, Java Object-Oriented Problem Solving

Item preview, share or embed this item, flag this item for.

Creative Commons License

plus-circle Add Review comment Reviews

19,941 Views

3 Favorites

DOWNLOAD OPTIONS

For print-disabled users

IN COLLECTIONS

Uploaded by jedboom01 on July 25, 2012

SIMILAR ITEMS (based on metadata)

You are now being redirected to CONTEXT4BOOK.COM....

Logo

Java, Java, Java: Object-Oriented Problem Solving

Large book cover: Java, Java, Java: Object-Oriented Problem Solving

Java, Java, Java: Object-Oriented Problem Solving by Ralph Morelli, Ralph Walde

Publisher : Prentice-Hall 2012 ISBN/ASIN : 0131474340 Number of pages : 865

Description : Functional and flexible, this guide takes an objects-first approach to Java programming and problem using games and puzzles. Updated to cover Java version 1.5 features, such as generic types, enumerated types, and the Scanner class. Offers independent introductions to both a command-line interface and a graphical user interface (GUI).

Home page url

Download or read it online for free here: Download link (6.6MB, PDF)

Similar books

Book cover: Learning Java

free FlipHTML5 flip book maker

Popular Uses

Java, Java, Java Object-Oriented Problem Solving (Ralph Morelli Ralph Walde) (z-lib.org) - 1151083366

Description: java, java, java object-oriented problem solving (ralph morelli ralph walde) (z-lib.org) - 1151083366, keywords: java,problem solving, read the text version.

No Text Content!

SECTION 1.4 • Java Language Elements 35 As you can see in HelloWorld, this kind of comment can extend over several lines and is sometimes called a multiline comment. A second type of comment is any text that follows double slashes (//) on a line. This is known as a single-line comment because it cannot extend beyond a single line. When the compiler encounters the beginning marker (/*) of a multiline comment, it skips over everything until it finds a matching end marker (*/). One implication of this is that it is not possible to put one multiline comment inside of another. That is, one comment cannot be nested, or contained, within another comment. The following code segment illustrates the rules that govern the use of /* and */: ☛ ✟ /∗ T h i s f i r s t c o m m e n t b e g i n s a n d e n d s o n t h e s a m e l i n e . ∗/ /∗ A s e c o n d c o m m e n t s t a r t s o n t h i s l i n e . . . a n d g o e s o n . . . a n d t h i s i s t h e l a s t l i n e o f t h e s e c o n d c o m m e n t . ∗/ /∗ A t h i r d c o m m e n t s t a r t s o n t h i s l i n e . . . /∗ T h i s i s NOT a f o u r t h c o m m e n t . I t i s j u s t p a r t o f t h e t h i r d c o m m e n t . And t h i s i s t h e l a s t l i n e o f t h e t h i r d c o m m e n t . ∗/ ∗/ This i s an e r r o r because i t i s an unmatched end marker . ✡ ✠ As you can see from this example, it is impossible to begin a new comment inside an already-started comment because all text inside the first comment, including /*, is ignored by the compiler. JAVA LANGUAGE RULE Comments. Any text contained within /* and */, which may span several lines, is considered a comment and is ignored by the compiler. Inserting double slashes (//) into a line turns the rest of the line into a comment. Multiline comments are often used to create a comment block that provides useful documentation for the program. In HelloWorld, the program begins with a comment block that identifies the name of file that contains the program and its author and provides a brief description of what the program does. For single-line comments, double slashes (//) can be inserted anywhere on a line of code. The result is that the rest of the line is ignored by Single-line comment the compiler. We use single-line comments throughout the HelloWorld program to provide a running commentary of its language elements. JAVA PROGRAMMING TIP Use of Comments. A well-written program should begin with a comment block that provides the name of the program, its author, and a description of what the program does.

36 CHAPTER 1 • Java Program Design and Development 1.4.2 Program Layout Another thing to notice about the program is how neatly it is arranged on the page. This is done deliberately so that the program is easy to read and understand. In Java, program expressions and statements may be arranged any way the programmer likes. They may occur one per line, several per line, or one per several lines. But the fact that the rules governing the layout of the program are so lax makes it all the more important that we adopt a good programming style, one that will help make programs easy to read. So look at how things are presented in HelloWorld. Notice how beginning and ending braces, and , are aligned, and note how we use single-line comments to annotate ending braces. Braces are used to mark the beginning and end of different blocks of code in a Java program and it can sometimes be difficult to know which beginning and end braces are matched up. Proper indentation and the use of single-line comments make it easier to determine how the braces are matched up. Similarly, notice how indentation is used to show when one element of the program is contained within another element. Thus, the elements of the HelloWorld class are indented inside of the braces that mark the beginning and end of the class. And the statements in the main() method are indented to indicate that they belong to that method. Use of indentation in this way, to identify the program’s structure, makes the program easier to read and understand. JAVA PROGRAMMING TIP Use of Indentation. Indent the code within a block and align the block’s opening and closing braces. Use a comment to mark the end of a block of code. 1.4.3 Keywords and Identifiers The Java language contains 48 predefined keywords (Table 1.1). These are words that have special meaning in the language and whose use is reserved for special purposes. For example, the keywords used in the HelloWorld program (Fig. 1.5) are: class, extends, private, public, static, and void. Table 1.1: Java keywords. abstract default goto package this boolean do if private throw break double implements protected throws byte enum import public transient case elses instanceof return try catch extend int short void char final interface static volatile class finally long super while const float native switch continue for new synchronized

SECTION 1.4 • Java Language Elements 37 Because their use is restricted, keywords cannot be used as the names of methods, variables, or classes. However, the programmer can make up his or her own names for the classes, methods, and variables that occur in the program, provided that certain rules and conventions are followed. The names for classes, methods, and variables are called identifiers, which follow certain syntax rules: Identifier syntax JAVA LANGUAGE RULE Identifier. An identifier must begin with a capital or lowercase letter and may be followed by any number of letters, digits, underscores ( ), or dollar signs ($). An identifier may not be identical to a Java keyword. Names in Java are case sensitive, which means that two different identifiers may contain the same letters in the same order. For example, thisVar and ThisVar are two different identifiers. In addition to the syntax rule that governs identifiers, Java program- Identifier style mers follow certain style conventions in making up names for classes, variables, and methods. By convention, class names in Java begin with a capital letter and use capital letters to distinguish the individual words in the name—for example, HelloWorld and TextField. Variable and Java naming conventions method names begin with a lowercase letter but also use capital letters to distinguish the words in the name—for example, main(), greeting, greet(), getQuestion(), and getAnswer(). The advantage of this convention is that it is easy to distinguish the different elements in a program—classes, methods, variables—just by how they are written. (For more on Java style conventions, see Appendix A.). Another important style convention followed by Java programmers is to choose descriptive identifiers when naming classes, variables, and methods. This helps to make the program more readable. JAVA PROGRAMMING TIP Choice of Identifiers. To make your program more readable, choose names that describe the purpose of the class, variable, or method. 1.4.4 Data Types and Variables A computer program wouldn’t be very useful if it couldn’t manipulate different kinds of data, such as numbers and strings. The operations that one can do on a piece of data depend on the data’s type. For example, you can divide and multiply numbers, but you cannot do this with strings. Thus, every piece of data in a Java program is classified according to its data type. Broadly speaking, there are two categories of data in Java: various types of objects and eight different types of built-in primitive data types. In addition to new types of objects that are created by programmers, Java has many different types of built-in objects. Two types that we will encounter in this chapter are the String and PrintStream objects. Java’s primitive types include three integer types, three real number types, a Primitive types character type, and a boolean type with values true and false. The names

38 CHAPTER 1 • Java Program Design and Development of the primitive types are keywords like int for one integer type, double for one real number type, and boolean. As we noted in Chapter 0, a variable is a named storage location that can store a value of a particular type. Practically speaking, you can think of a variable as a special container into which you can place values, but only values of a certain type (Fig. 1.6). For example, an int variable can store values like 5 or -100. A String variable can store values like “Hello”. (Actually, this is not the full story, which is a little more complicated, but we will get to that in Chapter 2.) In the HelloWorld class, the instance variable greeting (line 8) Figure 1.6: Variables are like typed containers. stores a value of type String. In the main() method, the variable helloworld is assigned a HelloWorld object (line 16). A literal value is an actual value of some type that occurs in a program. For example, a string enclosed in double quotes, such as ”Hello, World!”, is known as a String literal. A number such as 45.2 would be an example of a literal of type double, and -72 would be an example of a literal of type int. Our HelloWorld program contains just a single literal value, the ”HelloWorld!” String. 1.4.5 Statements Executing a program A Java program is a collection of statements. A statement is a segment of code that takes some action in the program. As a program runs, we say it executes statements, meaning it carries out the actions specified by those statements. In our HelloWorld program, statements of various types occur on lines 8, 11, 15, 16, and 17. Notice that all of these lines end with a semicolon. The rule in Java is that statements must end with a semicolon. Forgetting to do so would cause a syntax error. A declaration statement is a statement that declares a variable of a particular type. In Java, a variable must be declared before it can be used in a program. Failure to do so would cause a syntax error. In its simplest form, Declaration statement a declaration statement begins with the variable’s type, which is followed by the variable’s name, and ends with a semicolon: Type VariableName ; A variable’s type is either one of the primitive types we mentioned, such as int, double, or boolean, or for objects, it is the name of the object’s class, such as String or HelloWorld. A variable’s name may be any legal identifier, as defined earlier, although the convention in Java is to begin variable names with a lowercase letter. In our HelloWorld program, an example a simple declaration statement occurs on line 15: ☛ ✟ HelloWorld hellowo rld ; ✡ ✠ This example declares a variable for an object. The variable’s name is helloworld and its type is HelloWorld, the name of the class that is being defined in our example. To take another example the following statements declare two int variables, named int1 and int2: ☛ ✟ i n t i n t 1 ; i n t i n t 2 ; ✡ ✠

1 5 ; // ( b ) A s s i g n 2 5 t o num 2 num1 = num2 ; // ( c ) C o p y num 2 ’ s v a l u e ( 2 5 ) i n t o num 1 ✡ ✠ In the first case, the value on the right hand side is the string literal ”Hello, World!”, which gets stored in greeting. Of course, greeting has to be the right type of container–in this case, a String variable. In the next case, the value on the right hand side is 50. So that is the value that gets stored in num1, assuming that num1 is an int variable. The situation after this assignment is shown in the top drawing in Figure 1.7. In the third case, the value on the right hand side is 25, which is determined by adding 10 and 15. So the value that gets assigned to num2 is 25. After this assignment we have the situation shown in the middle drawing in the figure. Of course, this assumes that num2 is an int variable. In the last case, the value on the right hand side is 25, the value that we just stored in the variable num2. So, 25 gets stored in num1. This is the bottom drawing in the accompanying figure. The last of these examples ☛ ✟ num1 = num2 ; // C o p y num 2 ’ s v a l u e i n t o num 1 ✡ ✠ can be confusing to beginning programmers, so it is worth some additional comment. In this case, there are variables on both the left and right of the assignment operator. But they have very different meaning. The variable on the right is treated as a value. If that variable is storing 25, then that is its value. In fact, whatever occurs on the right hand side of an assignment operator is treated as a value. The variable on the left hand side is treated as a memory location. It is where the value 25 will be stored as a result of executing this statement. The effect of this statement is to copy the value stored in num2 into num1, as illustrated in Figure 1.8. Figure 1.8: In the assignment num1 = num2;, num2’s value is copied into num1. Java has many other kinds of statements and we will be learning about these in subsequent examples. The following examples from the

10, the expression itself produces an int result. When comparing two numbers with the less than operator, num1 < num2, the expression itself produces a boolean type, either true or false. It is important to note that expressions cannot occur on their own. Rather they occur as part of the program’s statements. Here are some additional examples of expressions: ☛ ✟ num = 7 // An a s s i g n m e n t e x p r e s s i o n o f t y p e i n t num = square ( 7 ) // An m e t h o d c a l l e x p r e s s i o n o f t y p e i n t num == 7 // An e q u a l i t y e x p r e s s i o n o f t y p e b o o l e a n ✡ ✠ The first of these is an assignment expression. It has a value of 7, because it is assigning 7 to num. The second example is also an assignment expression, but this one has a method call, square(7), on its right hand side. (We can assume that a method named square() has been appropriately defined in the program.) A method call is just another kind of expression. In this case, it has the value 49. Note that an assignment expression can be turned into a stand-alone assignment statement by placing a semicolon after it. The third expression is an equality expression, which has the value true, assuming that the variable on its left is storing the value 7. It is

SECTION 1.4 • Java Language Elements 41 important to note the difference between the assignment operator (=) and the equality operator (==). JAVA LANGUAGE RULE Equality and Assignment. Be careful not to confuse = and ==. The symbol = is the assignment operator. It assigns the value on its right-hand side to the variable on its left-hand side. The symbol == is the equality operator. It evaluates whether the expressions on its left- and right-hand sides have the same value and returns either true or false. SELF-STUDY EXERCISES EXERCISE 1.1 What is stored in the variable num after the following two statements are executed? int num = 11; num = 23 - num; EXERCISE 1.2 Write a statement that will declare a variable of type int called num2, and store in it the sum of 711 and 712. 1.4.7 Class Definition A Java program consists of one or more class definitions. In the HelloWorld example, we are defining the HelloWorld class, but there are also three predefined classes involved in the program. These are the Object, String, and System classes all of which are defined in the Java class library. Predefined classes, such as these, can be used in any program. As the HelloWorld program’s comments indicate, a class definition has two parts: a class header and a class body. In general, a class header Class header takes the following form, some parts of which are optional (opt): ClassModifiersopt class ClassName Pedigreeopt The class header for the HelloWorld class is: ☛ ✟ pub l ic c l a s s HelloWorld ex tends O bje c t ✡ ✠ The purpose of the header is to give the class its name (HelloWorld), identify its accessibility (public as opposed to private), and describe where it fits into the Java class hierarchy (as an extension of the Object class). In this case, the header begins with the optional access modifier, public, which declares that this class can be accessed by any other classes. The next part of the declaration identifies the name of the class, HelloWorld. And the last part declares that HelloWorld is a subclass of the Object class. We call this part of the definition the class’s pedigree. As you recall from Chapter 0, the Object class is the top class of the entire Java hierarchy. By declaring that HelloWorld extends Object, we are saying that HelloWorld is a direct subclass of Object. In fact, it is not necessary to declare explicitly that HelloWorld extends Object because that is Java’s default assumption. That is, if you omit the extends clause in the class header, Java will automatically assume that the class is a subclass of Object.

42 CHAPTER 1 • Java Program Design and Development The class’s body, which is enclosed within curly brackets (), contains Class body the declaration and definition of the elements that make up the objects of the class. This is where the object’s attributes and actions are defined. 1.4.8 Declaring an Instance Variable There are generally two kinds of elements declared and defined in the class body: variables and methods. As we described in Chapter 0, an instance variable is a variable that belongs to each object, or instance, of the class. That is, each instance of a class has its own copies of the class’s instance variables. The HelloWorld class has a single instance variable, (greeting), which is declared as follows: ☛ ✟ p r i v a t e S t ri n g g r e e ti n g = ”Hello , World ! ” ; ✡ ✠ In general, an instance variable declaration has the following syntax, some parts of which are optional: Modifiersopt Type VariableName InitializerExpressionopt Thus, a variable declaration begins with optional modifiers. In declaring the greeting variable, we use the access modifier, private, to declare that greeting, which belongs to the HelloWorld class, cannot be directly accessed by other objects. The next part of the declaration is the Information hiding variable’s type. In this case, the greeting variable is a String, which means that it can store a string object. The type is followed by the name of the variable, in this case (greeting). This is the name that is used to refer to this memory location throughout the class. For example, notice that the variable is referred to on line 11 where it is used in a println() statement. The last part of the declaration is an optional initializer expression. In this example, we use it to assign an initial value, “Hello, World!,” to the greeting variable. 1.4.9 Defining an Instance Method Recall that a method is a named section of code that can be called or invoked to carry out an action or operation. In a Java class, the methods correspond to the object’s behaviors or actions. The HelloWorld program has two method definitions: the greet() method and the main() method. A method definition consists of two parts: the method header and the method body. In general, a method header takes the following form, including some parts which are optional: Modifiersopt ReturnType MethodName ( ParameterListopt) As with a variable declaration, a method definition begins with optional modifiers. For example, the definition of the greet() method on line 9 uses the access modifier, public, to declare that this method can be accessed or referred to by other classes. The main() method, whose definition begins on line 13, is a special method, and is explained in the next section.

SECTION 1.4 • Java Language Elements 43 The next part of the method header is the method’s return type. This is the type of value, if any, that the method returns. Both of the methods in HelloWorld have a return type of void. This means that they don’t return any kind of value. Void methods just execute the sequence of statements given in their bodies. For an example of a method that does return a value, take a look again at the declaration of the getQuestion() method in the Riddle class, which returns a String (Fig. 1.4). The method’s name follows the method’s return type. This is the name that is used when the method is called. For example, the greet() method is called on line 17. Following the method’s name is the method’s parameter list. A parameter is a variable that temporarily stores data values that are being passed to the method when the method is called. Some methods, such as the greet() method, do not have parameters, because they are not passed any information. For an example of a method that does have parameters, see the Riddle() constructor, which contains parameters for the riddle’s question and answer (Fig. 1.4). The last part of method definition is its body, which contains a sequence of executable statements. An executable statement is a Java statement that takes some kind of action when the program is run. For example, the statement in the greet() method, ☛ ✟ System . ou t . p ri n tl n ( g r e e ti n g ) ; // O u t p u t s t a t e m e n t ✡ ✠ prints a greeting on the console. 1.4.10 Java Application Programs The HelloWorld program is an example of a Java application program, or a Java application, for short. An application program is a stand-alone program, “stand-alone” in the sense that it does not depend on any other program, like a Web browser, for its execution. Every Java application program must contain a main() method, which is where the program begins execution when it is run. For a program that contains several classes, it is up to the programmer to decide which class should contain the main() method. We don’t have to worry about that decision for the HelloWorld, because it contains just a single class. Because of its unique role as the starting point for every Java application program, it is very important that the header for the main method be declared exactly as shown in the HelloWorld class: ☛ ✟ pub l ic s t a t i c void main ( S t ri n g a rgs [ ] ) ✡ ✠ It must be declared public so it can be accessed from outside the class that contains it. The static modifier is used to designate main() as Class method a class method. As you might recall from Chapter 0, a class method is a method that is associated directly with the class that contains it rather than with the objects of the class. A class method is not part of the class’s objects. Unlike instance methods, which are invoked through a class’s objects, a class method is called through the class itself. Thus, a class method can be called even before the program has created objects of that class.

44 CHAPTER 1 • Java Program Design and Development Because of main()’s special role as the program’s starting point, it is necessary for main() to be a class method because it is called, by the Java runtime system, before the program has created any objects. The main() method has a void return type, which means it does not return any kind of value. Finally, notice that main()’s parameter list contains a declaration of some kind of String parameter named args. This is actually an array that can be used to pass string arguments to the program when it is started up. We won’t worry about this feature until our chapter on arrays. 1.4.11 Creating and Using Objects The body of the main() method is where the HelloWorld program creates its one and only object. Recall that when it is run the HelloWorld program just prints the “Hello World!” greeting. As we noted earlier, this action happens in the greet() method. So in order to make this action happen, we need to call the greet() method. However, because the greet() method is an instance method that belongs to a HelloWorld object, we first need to create a HelloWorld instance. This is what happens in the body of the main() method (Fig. 1.5). The main() method contains three statements: ☛ ✟ HelloWorld hellowo rld ; // V a r i a b l e d e c l a r a t i o n hellowo rld = new HelloWorld ( ) ; // O b j e c t i n s t a n t i a t i o n hellowo rld . g r e e t ( ) ; // M e t h o d i n v o c a t i o n ✡ ✠ The first statement declares a variable of type HelloWorld, which is then assigned a HelloWorld object. The second statement creates a HelloWorld object. This is done by invoking the HelloWorld() constructor method. Creating an object is called object instantiation because you are creating an instance of the object. Once a HelloWorld instance is created, we can use one of its instance methods to perform some task or operation. Thus, in the third statement, we call the greet() method, which will print “Hello World!” on the console. If you look back at the HelloWorld program in Figure 1.5 you won’t Default constructor find a definition of a constructor method. This is not an error because Java will provide a default constructor if a class does not contain a constructor definition. The default constructor is a trivial constructor method, “trivial” because its body contains no statements. Here is what the default HelloWorld() constructor would look like: ☛ ✟ pub l ic HelloWorld ( ) { } // D e f a u l t c o n s t r u c t o r ✡ ✠ For most of the classes we design, we will design our own constructors, just as we did in the Riddle class (Fig. 1.4). We will use constructors to assign initial values to an object’s instance variables or to perform other kinds of tasks that are needed when an object is created. Because the HelloWorld object doesn’t require any startup tasks, we can make do with the default constructor. Interacting objects The HelloWorld program illustrates the idea that an object-oriented program is a collection of interacting objects. Although we create just a single HelloWorld object in the main() method, there are two other ob-

SECTION 1.4 • Java Language Elements 45 jects used in the program. One is the greeting, which is a String object consisting of the string “Hello, World!”. The other is the System.out object, which is a special Java system object used for printing. 1.4.12 Java JFrames Java cann run a program in a JFrame so that the output and interaction occurs in a Window (or Frame). Figure 1.9 shows a Java program named HelloWorldSwing. This program does more or less the same thing as the HelloWorld application—it displays the “Hello, World!” greeting. ☛ ✟ /∗ ∗ F i l e : H e l l o W o r l d S w i n g p r o g r a m ∗/ import j a v a x . swing . JFrame ; // I m p o r t c l a s s n a m e s import j a v a . awt . Graphics ; import j a v a . awt . Canvas ; pub l ic c l a s s HelloWorldCanvas ex tends Canvas // C l a s s h e a d e r { // S t a r t o f b o d y pub l ic void p ai n t ( Graphics g ) // T h e p a i n t m e t h o d { g . drawS tring ( ”Hello , World ! ” , 1 0 , 1 0 ) ; } // E n d o f p a i n t pub l ic s t a t i c void main ( S t ri n g [ ] a rgs ){ HelloWorldCanvas c = new HelloWorldCanvas ( ) ; JFrame f = new JFrame ( ) ; f . add ( c ) ; f . s e t S i z e ( 1 5 0 , 5 0 ) ; f . s e t V i s i b l e ( t ru e ) ; } } // E n d o f H e l l o W o r l d C a n v a s ✡ ✠ Figure 1.9: HelloWorldCanvas program. The difference is that it displays the greeting within a Window rather than directly on the console. As in the case of the HelloWorld console application program, HelloWorldCanvas consists of a class definition. It contains a single method definition, the paint() method, which contains a single executable statement: ☛ ✟ g . drawS tring ( ”Hello , World ! ” , 1 0 , 1 0 ) ; ✡ ✠ This statement displays the “Hello, World!” message directly in a Window. The drawString() method is one of the many drawing and painting methods defined in the Graphics class. Every Java Canvas comes with its own Graphics object, which is referred to here simply as g. Thus, we are using that object’s drawString() method to draw on the window. Don’t worry if this seems a bit mysterious now. We’ll explain it more fully when we take up graphics examples again.

46 CHAPTER 1 • Java Program Design and Development The HelloWorldSwing also contains some elements, such as the import statements, that we did not find in the HelloWorld application. We will now discuss those features. 1.4.13 Java Library Packages Recall that the HelloWorld application program used two pre-defined classes, the String and the System classes. Both of these classes are basic language classes in Java. The HelloWorldSwing program also uses pre-defined classes, such as JFrame and Graphics. However, these two classes are not part of Java’s basic language classes. To understand the difference between these classes, it will be necessary to talk briefly about how the Java class library is organized. A package is a collection a inter-related classes in the Java class library. For example, the java.lang package contains classes, such as Object, String, and System, that are central to the Java language. Just about all Java programs use classes in this package. The java.awt package provides classes, such as Button, TextField, and Graphics, that are used in graphical user interfaces (GUIs). The java.net package provides classes used for networking tasks, and the java.io package provides classes used for input and output operations. All Java classes belong to some package, including those that are programmer defined. To assign a class to a package, you would provide a package statement as the first statement in the file that contains the class definition. For example, the files containing the definitions of the classes in the java.lang package all begin with the following statement. ☛ ✟ package j a v a . lang ; ✡ ✠ If you omit package statement, as we do for the programs in this book, Java places such classes into an unnamed default package. Thus, for any Java class, its full name includes the name of the package that contains it. For example, the full name for the System class is java.lang.System and the full name for the String class is java.lang.String. Similarly, the full name for the Graphics class is java.awt.Graphics. In short, the full name for a Java class takes the following form: package.class In other words, the full name of any class provides its package name as a prefix. Of all the packages in the Java library, the java.lang package is the only one whose classes are available by their shorthand names to all Java programs. This means that when a program uses a class from the java.lang package, it can refer to it simply by its class name. For example, in the HelloWorld program we referred directly to the String class rather than to java.lang.String. 1.4.14 The import Statement The import statement makes Java classes available to programs under their abbreviated names. Any public class in the Java class library is available to a program by its fully qualified name. Thus, if a program was using

SECTION 1.4 • Java Language Elements 47 the Graphics class, it could always refer to it as java.awt.Graphics. However, being able to refer to Graphics by its shorthand name, makes the program a bit shorter and more readable. The import statement doesn’t actually load classes into the program. It just makes their abbreviated names available. For example, the import statements in HelloWorldSwing allow us to refer to the JFrame, Canvas, and Graphics classes by their abbreviated names (Fig. 1.9). The import statement takes two possible forms: import package.class import package.* The first form allows a specific class to be known by its abbreviated name. The second form, which uses the asterisk as a wildcard characters (’*’), allows all the classes in the specified package to be known by their short names. The import statements in HelloWorldSwing are examples of the first form. The following example, ☛ ✟ import j a v a . lang . ∗ ; ✡ ✠ allows all classes in the java.lang package to be referred to by their class names alone. In fact, this particular import statement is implicit in every Java program. 1.4.15 Qualified Names in Java In the previous subsections we have seen several examples of names in Java programs that used dot notation. A qualified name is a name that is separated into parts using Java’s dot notation. Examples include package names, such as java.awt, class names, such as javax.swing.JFrame, and even method names, such as helloworld.greet(). Just as in our natural language, the meaning of a name within a Java program depends on the context. For example, the expression helloworld.greet() refers to the greet() method, which belongs to the HelloWorld class. If we were using this expression from within that class, you wouldn’t need to qualify the name in this way. You could just refer to greet() and it would be clear from the context which method you meant. This is no different than using someone’s first name (“Kim”) when there’s only one Kim around, but using a full name (“Kim Smith”) when the first name alone would be too vague or ambiguous. One thing that complicates the use of qualified names is that they are used to refer to different kinds of things within a Java program. But this is no different, really, than in our natural language, where names (“George Washington”) can refer to people, bridges, universities, and so on. Here again, just as in our natural language, Java uses the context to understand the meaning of the name. For example, the expression java.lang.System refers to the System class in the java.lang package, whereas the expression System.out.print() refers to a method in the System.out object. How can you tell these apart? Java can tell them apart because the first one occurs as part of an import statement, so it must be referring

48 CHAPTER 1 • Java Program Design and Development to something that belongs to a package. The second expression would only be valid in a context where a method invocation is allowed. You will have to learn a bit more about the Java language before you’ll be able to completely understand these names, but the following provide some naming rules to get you started. JAVA LANGUAGE RULE Library Class Names. By convention, class names in Java begin with an uppercase letter. When referenced as part of a package, the class name is the last part of the name. For example, java.lang.System refers to the System class in the java.lang package. JAVA LANGUAGE RULE Dot Notation. Names expressed in Java’s dot notation depend for their meaning on the context in which they are used. In qualified names—that is, names of the form X.Y.Z—the last item in the name (Z) is the referent—that is, the element being referred to. The items that precede it (X.Y.) are used to qualify or clarify the referent. The fact that names are context dependent in this way certainly complicates the task of learning what’s what in a Java program. Part of learning to use Java’s built-in classes is learning where a particular object or method is defined. It is a syntax error if the Java compiler can’t find the object or method that you are referencing. JAVA DEBUGGING TIP Not Found Error. If Java cannot find the item you are referring to, it will report an “X not found” error, where X is the class, method, variable, or package being referred to. 1.5 Editing, Compiling, and Running a Java Program In this section we discuss the nuts and bolts of how to compile and run a Java program. Because we are exploring two different varieties of Java programs, console applications and Swing applications, the process differs slightly for each variety. We have already discussed some of the main language features of console and Swing applications, so in this section we focus more on features of the programming environment itself. Because we do not assume any particular programming environment in this book, our discussion will be somewhat generic. However, we do begin with a brief overview of the types of programming environments one might encounter.

SECTION 1.5 • Editing, Compiling, and Running a Java Program 49 Figure 1.10: Editing, compiling, and running HelloWorld.java. text editor javac javac generates a list of error messages syntax errors ? Editor creates the source program in a disk file. javac creates the bytecode in a disk file. appletviewer or Web browser java javac HelloWorld.class Hello.html Applet Programming Applets require an HTML file. HelloWorld.java The Java Virtual Machine loads the class file into memory and interprets and runs the bytecode. User types program into a file using a standard text editor. Correct the syntax errors N Y 1.5.1 Java Development Environments A Java programming environment typically consists of several programs that perform different tasks required to edit, compile, and run a Java program. The following description will be based on the software development environment provided by Oracle, the company that owns and maintains Java. It is currently known as the Java Platform, Standard Edition 8.0 (Java SE 8). Versions of Java SE are available for various platforms, including Linux, Windows, and macOS computers. Free downloads are available at Sun’s Web site at http://www.oracle.com/technetwork/java/. (For more details about the Java SE, see Appendix B.) In some cases, the individual programs that make up the Java SE are available in a single program development environment, known as an integrated development environment (IDE). Some examples include Eclipse, jGrasp, and Oracle’s own NetBeans IDE. Each of these provides a complete development package for editing, compiling, and running Java applications on a variety of platforms, including Linux, macOS, and Windows. Figure 1.10 illustrates the process involved in creating and running a Java program. The discussion that follows here assumes that you are us-

for free. As we have seen, a Java program consists of one or more class definitions. We will follow the convention of placing each class definition in its own file. (The rule in Java is that a source file may contain only one public class definition.) The files containing these classes’ definitions must be named ClassName.java where ClassName is the name of the public Java class contained in the file. JAVA LANGUAGE RULE File Names. A file that defines a public Java class named ClassName must be saved in a text file named ClassName.java. Otherwise an error will result. For example, in the case of our HelloWorld application program, the file must be named HelloWorld.java, and for HelloWorldSwing, it must be named HelloWorldSwing.java. Because Java is case sensitive, which means that Java pays attention to whether a letter is typed uppercase or lowercase, it would be an error if the file containing the HelloWorld class were named helloworld.java or Helloworld.java. The error in this case would be a semantic error. Java would not be able to find the HelloWorld class because it will be looking for a file named HelloWorld.java. JAVA LANGUAGE RULE Case Sensitivity. Java is case sensitive, which means that it treats helloWorld and Helloworld as different names. 1.5.3 Compiling a Program Recall that before you can run a Java source program you have to compile it into the Java bytecode, the intermediate code understood by the Java Virtual Machine (JVM). Source code for both applets and applications must be compiled. To run a Java program, whether an applet or an application, the JVM is then used to interpret and execute the bytecode. The Java SE comes in two parts, a runtime program, called the Java Runtime Environment (JRE) and a development package, called the Software Development Kit (SDK). If you are just going to run Java programs, you need only install the JRE on your computer. In order to run Java applets, browsers, such as Internet Explorer and Netscape Navigator, must contain a plugin version of the JRE. On the other hand, if you are going to be developing Java programs, you will need to install the SDK as well.

SECTION 1.5 • Editing, Compiling, and Running a Java Program 51 The Java SDK compiler is named javac. In some environments— such as within Linux or at the Windows command prompt — HelloWorld.java would be compiled by typing the following command at the system prompt: ☛ ✟ j a v a c HelloWorld . j a v a ✡ ✠ As Figure 1.10 illustrates, if the HelloWorld.java program does not contain errors, the result of this command is the creation of a Java bytecode file named HelloWorld.class—a file that has the same prefix as the source file but with the suffix .class rather than .java. By default, the bytecode file will be placed in the same directory as the source file. If javac detects errors in the Java code, a list of error messages will be printed. 1.5.4 Running a Java Application Program In order to run (or execute) a program on any computer, the program’s executable code must be loaded into the computer’s main memory. For Java environments, this means that the program’s .class file must be loaded into the computer’s memory, where it is then interpreted by the Java Virtual Machine. To run a Java program on Linux systems or at the Windows command prompt, type ☛ ✟ j a v a HelloWorld ✡ ✠ on the command line. This command loads the JVM, which will then load and interpret the application’s bytecode (HelloWorld.class). The “HelloWorld” string will be displayed on the command line. On Macintosh systems, or within an IDE, which do not typically have a command line interface, you would select the compile and run commands from a menu. Once the code is compiled, the run command will cause the JVM to be loaded and the bytecode to be interpreted. The “Hello, World!” output would appear in a text-based window that automatically pops up on your computer screen. In any case, regardless of the system you use, running the HelloWorld console application program will cause the “Hello, World!” message to be displayed on some kind of standard output device (Fig. 1.11). Figure 1.11: Compiling and Running the HelloWorld.java console application program. 1.5.5 Running a Java Swing Program When you run a Java Swing Program, there is typically no console output. You only see your output in the Window (JFrame) that your Graphics are displayed in. This makes automated testing more difficult since you need to visually inspect that the program is working correctly. When you run ☛ ✟ j a v a HelloWorldSwing ✡ ✠ A window will open, and you won’t be able to type in the console until you close the window, quit the program, or type ctl-c to send a kill signal to the Swing program. The result of running, as shown in Figure 1.12,

println(in data : int) PrintStream Figure 1.13: A UML class diagram of the PrintStream class. or methods. Because the various print() and println() methods are instance methods of a PrintStream object, we can only use them by finding a

in : InputStream System Figure 1.14: The System class. Now that we know how to use Java’s printing expert, let’s use it to “sing” a version of “Old MacDonald Had a Farm.” As you might guess, this program will simply consist of a sequence of System.out.println() statements each of which prints a line of the verse. The complete Java application program is shown in Figure 1.15. ☛ ✟ pub l ic c l a s s OldMacDonald { pub l ic s t a t i c void main ( S t ri n g a rgs [ ] ) // M a i n m e t h o d { System . ou t . p ri n tl n ( ”Old MacDonald had a farm” ) ; System . ou t . p ri n tl n ( ”E I E I O. ” ) ; System . ou t . p ri n tl n ( ”And on hi s farm he had a duck . ” ) ; System . ou t . p ri n tl n ( ”E I E I O. ” ) ; System . ou t . p ri n tl n ( ”With a quack quack here . ” ) ; System . ou t . p ri n tl n ( ”And a quack quack t h e r e . ” ) ; System . ou t . p ri n tl n ( ”Here a quack , t h e r e a quack , ” ) ; System . ou t . p ri n tl n ( ”Everywhere a quack quack . ” ) ; System . ou t . p ri n tl n ( ”Old MacDonald had a farm” ) ; System . ou t . p ri n tl n ( ”E I E I O. ” ) ; } // E n d o f m a i n } // E n d o f O l d M a c D o n a l d ✡ ✠ Figure 1.15: The OldMacDonald.java class. This example illustrates the importance of using the Java class library. If there’s a particular task we want to perform, one of the first things we

54 CHAPTER 1 • Java Program Design and Development should ask is whether there is already an “expert” in Java’s class library that performs that task. If so, we can use methods provided by the expert to perform that particular task. JAVA EFFECTIVE DESIGN Using the Java Library. Learning how to use classes and objects from the Java class library is an important part of object-oriented programming in Java. ********** SELF-STUDY EXERCISES * ** ** * * ** * * * * * * **** * ********** EXERCISE 1.3 One good way to learn how to write programs is to modify existing programs. Modify the OldMacDonald class to “sing” one more verse of the song. EXERCISE 1.4 Write a Java class that prints the design shown on the left. CHAPTER SUMMARY Technical Terms algorithm applet application program assignment statement comment compound statement (block) data type declaration statement default constructor executable statement expression identifier literal value object instantiation operator package parameter primitive data type pseudocode qualified name semantics statement stepwise refinement syntax Summary of Important Points • Good program design requires that each object and method have a well-defined role and clear definition of what information is needed for the task and what results will be produced. • Good program design is important; the sooner you start coding, the longer the program will take to finish. Good program design strives for readability, clarity, and flexibility. • Testing a program is very important and must be done with care, but it can only reveal the presence of bugs, not their absence. • An algorithm is a step-by-step process that solves some problem. Algorithms are often described in pseudocode, a hybrid language that combines English and programming language constructs. • A syntax error occurs when a statement breaks a Java syntax rules. Syntax errors are detected by the compiler. A semantic error is an error in the program’s design and cannot be detected by the compiler. • Writing Java code should follow the stepwise refinement process.

operation produces an int result. • A class definition has two parts: a class header and a class body. A class header takes the form of optional modifiers followed by the word class followed by an identifier naming the class followed, optionally, by the keyword extends and the name of the class’s superclass. • There are generally two kinds of elements declared and defined in the class body: variables and methods. • Object instantiation is the process of creating an instance of a class using the new operator in conjunction with one of the class’s constructors. • Dot notation takes the form qualifiers.elementName. The expression System.out.print("hello") uses Java dot notation to invoke the print() method of the System.out object. • A Java application program runs in stand-alone mode. A Java applet is a program that runs within the context of a Java-enabled browser. Java applets are identified in HTML documents by using the tag. • A Java source program must be stored in a file that has a .java extension. A Java bytecode file has the same name as the source file but a .class extension. It is an error in Java if the name of the source file is not identical to the name of the public Java class defined within the file. • Java programs are first compiled into bytecode and then interpreted by the Java Virtual Machine (JVM).

712; SOLUTION 1.3 The definition of the OldMacDonald class is: ☛ ✟ pub l ic c l a s s OldMacDonald { pub l ic s t a t i c void main ( S t ri n g a rgs [ ] ) // M a i n m e t h o d { System . ou t . p ri n tl n ( ”Old MacDonald had a farm” ) ; System . ou t . p ri n tl n ( ”E I E I O. ” ) ; System . ou t . p ri n tl n ( ”And on hi s farm he had a duck . ” ) ; System . ou t . p ri n tl n ( ”E I E I O. ” ) ; System . ou t . p ri n tl n ( ”With a quack quack here . ” ) ; System . ou t . p ri n tl n ( ”And a quack quack t h e r e . ” ) ; System . ou t . p ri n tl n ( ”Here a quack , t h e r e a quack , ” ) ; System . ou t . p ri n tl n ( ”Everywhere a quack quack . ” ) ; System . ou t . p ri n tl n ( ”Old MacDonald had a farm” ) ; System . ou t . p ri n tl n ( ”E I E I O. ” ) ; System . ou t . p ri n tl n ( ”Old MacDonald had a farm” ) ; System . ou t . p ri n tl n ( ”E I E I O. ” ) ; System . ou t . p ri n tl n ( ”And on hi s farm he had a pig . ” ) ; System . ou t . p ri n tl n ( ”E I E I O. ” ) ; System . ou t . p ri n tl n ( ”With an oink oink here . ” ) ; System . ou t . p ri n tl n ( ”And an oink oink t h e r e . ” ) ; System . ou t . p ri n tl n ( ”Here an oink , t h e r e an oink , ” ) ; System . ou t . p ri n tl n ( ”Everywhere an oink oink . ” ) ; System . ou t . p ri n tl n ( ”Old MacDonald had a farm” ) ; System . ou t . p ri n tl n ( ”E I E I O. ” ) ; } // E n d o f m a i n } // E n d o f O l d M a c D o n a l d ✡ ✠ SOLUTION 1.4 The definition of the Pattern class is: ☛ ✟ pub l ic c l a s s P a t t e r n { pub l ic s t a t i c void main ( S t ri n g a rgs [ ] ) // M a i n m e t h o d { System . ou t . p ri n tl n ( ”∗∗∗∗∗∗∗∗∗∗ ” ) ; System . ou t . p ri n tl n ( ”∗ ∗∗ ∗∗ ∗” ) ; System . ou t . p ri n tl n ( ”∗ ∗∗ ∗” ) ; System . ou t . p ri n tl n ( ”∗ ∗ ∗ ∗” ) ; System . ou t . p ri n tl n ( ”∗ ∗∗∗∗ ∗” ) ; System . ou t . p ri n tl n ( ”∗∗∗∗∗∗∗∗∗∗ ” ) ; } // E n d o f m a i n } // E n d o f P a t t e r n ✡ ✠

CHAPTER 1 • Exercises 57 EXERCISE 1.1 Fill in the blanks in each of the following statements. EXERCISES a. A Java class definition contains an object’s and . b. A method definition contains two parts, a and a . EXERCISE 1.2 Explain the difference between each of the following pairs of concepts. a. Application and applet. b. Single-line and multiline comment. c. Compiling and running a program. d. Source code file and bytecode file. e. Syntax and semantics. f. Syntax error and semantic error. g. Data and methods. h. Variable and method. i. Algorithm and method. j. Pseudocode and Java code. k. Method definition and method invocation. EXERCISE 1.3 For each of the following, identify it as either a syntax error or a semantic error. Justify your answers. a. Write a class header as public Class MyClass. b. Define the init() header as public vid init(). c. Print a string of five asterisks by System.out.println("***");. d. Forget the semicolon at the end of a println() statement. e. Calculate the sum of two numbers as N − M. EXERCISE 1.4 Suppose you have a Java program stored in a file named Test.java. Describe the compilation and execution process for this program, naming any other files that would be created. EXERCISE 1.5 Suppose N is 15. What numbers would be output by the following pseudocode algorithm? Suppose N is 6. What would be output by the algorithm in that case? ☛ ✟ 0 . P ri n t N. 1 . I f N equ al s 1 , s top . 2 . I f N i s even , divide i t by 2 . 3 . I f N i s odd , t r i p l e i t and add 1 . 4 . Go t o s tep 0 . ✡ ✠ EXERCISE 1.6 Suppose N is 5 and M is 3. What value would be reported by the following pseudocode algorithm? In general, what quantity does this algorithm calculate? ☛ ✟ 0 . Wri te 0 on a pie ce o f paper . 1 . I f M equ al s 0 , r e p o r t what ’ s on the paper and s top . 2 . Add N t o the qu a n ti t y w ri t t e n on the paper . 3 . S u b t r a c t 1 from M. 4 . Go t o s tep 1 . ✡ ✠

58 CHAPTER 1 • Java Program Design and Development EXERCISE 1.7 Puzzle Problem: You are given two different length ropes that have the characteristic that they both take exactly one hour to burn. However, neither rope burns at a constant rate. Some sections of the ropes burn very fast; other sections burn very slowly. All you have to work with is a box of matches and the two ropes. Describe an algorithm that uses the ropes and the matches to calculate when exactly 45 minutes have elapsed. EXERCISE 1.8 Puzzle Problem: A polar bear that lives right at the North Pole can walk due south for one hour, due east for one hour, and due north for one hour, and end up right back where it started. Is it possible to do this anywhere else on earth? Explain. EXERCISE 1.9 Puzzle Problem: Lewis Carroll, the author of Alice in Wonderland, used the following puzzle to entertain his guests: A captive queen weighing 195 pounds, her son weighing 90 pounds, and her daughter weighing 165 pounds, were trapped in a very high tower. Outside their window was a pulley and rope with a basket fastened on each end. They managed to escape by using the baskets and a 75-pound weight they found in the tower. How did they do it? The problem is that anytime the difference in weight between the two baskets is more than 15 pounds, someone might get hurt. Describe an algorithm that gets them down safely. EXERCISE 1.10 Puzzle Problem: Here’s another Carroll favorite: A farmer needs to cross a river with his fox, goose, and a bag of corn. There’s a rowboat that will hold the farmer and one other passenger. The problem is that the fox will eat the goose if they are left alone on the river bank, and the goose will eat the corn if they are left alone on the river bank. Write an algorithm that describes how he got across without losing any of his possessions. EXERCISE 1.11 Puzzle Problem: Have you heard this one? A farmer lent the mechanic next door a 40-pound weight. Unfortunately, the mechanic dropped the weight and it broke into four pieces. The good news is that, according to the mechanic, it is still possible to use the four pieces to weigh any quantity between one and 40 pounds on a balance scale. How much did each of the four pieces weigh? (Hint: You can weigh a 4-pound object on a balance by putting a 5-pound weight on one side and a 1-pound weight on the other.) EXERCISE 1.12 Suppose your little sister asks you to show her how to use a pocket calculator so that she can calculate her homework average in her science course. Describe an algorithm that she can use to find the average of 10 homework grades. EXERCISE 1.13 A Caesar cipher is a secret code in which each letter of the alphabet is shifted by N letters to the right, with the letters at the end of the alphabet wrapping around to the beginning. For example, if N is 1, when we shift each letter to the right, the word daze would be written as ebaf. Note that the z has wrapped around to the beginning of the alphabet. Describe an algorithm that can be used to create a Caesar encoded message with a shift of 5. EXERCISE 1.14 Suppose you received the message, “sxccohv duh ixq,” which you know to be a Caesar cipher. Figure out what it says and then describe an algorithm that will always find what the message said regardless of the size of the shift that was used. EXERCISE 1.15 Suppose you’re talking to your little brother on the phone and he wants you to calculate his homework average. All you have to work with is a piece of chalk and a very small chalkboard—big enough to write one four-digit number. What’s more, although your little brother knows how to read numbers, he doesn’t know how to count very well so he can’t tell you how many grades there are. All he can do is read the numbers to you. Describe an algorithm that will calculate the correct average under these conditions.

num2; EXERCISE 1.25 Write a series of statements that will declare a variable of type int called num and store in it the difference between 61 and 51. UML EXERCISES EXERCISE 1.26 Modify the UML diagram of the Riddle class to contain a method named getRiddle() that would return both the riddle’s question and answer. EXERCISE 1.27 Draw a UML class diagram representing the following class: The name of the class is Circle. It has one attribute, a radius that is represented by a double value. It has one operation, calculateArea(), which returns a double. Its attributes should be designated as private and its method as public.

printPhone() -name : String -phone : String Person Figure 1.16: The Person class. the UML diagram shown in Figure 1.17.

OBJECTIVES After studying this chapter, you will • Be familiar with using variables to store and manipulate simple data. • Be familiar with creating and using objects. • Understand the relationship between classes and objects. • Understand the difference between objects and data of primitive type. • Understand the difference between static and and instance elements of a class. • Be able to understand and design a simple class in Java. • Understand some of the basic principles of object-oriented programming. OUTLINE 2.1 Introduction 2.2 Using String Objects 2.3 Drawing Shapes with the Graphics Object (Optional) 2.4 Class Definition 2.5 Case Study: Simulating a Two-Person Game 2.6 From the Java Library: java.util.Scanner Special Topic: Alan Kay and the Smalltalk Language Chapter Summary Solutions to Self-Study Exercises Exercises Chapter 2 Objects: Using, Creating, and Defining 61

62 CHAPTER 2 • Objects: Using, Creating, and Defining 2.1 Introduction This chapter introduces some more of the basic principles of objectoriented programming. We begin by looking at some examples of creating and using objects of type String and Graphics. Then, we examine how user defined classes are used by doing a detailed walk-through of the Riddle class we saw in Chapter 1. We focus on the basic Java language elements involved. By the end of these sections, you should know how to identify the key elements that make up a Java program. We then present a detailed example of the programming development process by designing a class that models a certain two person game and implements the class. The design is represented using UML notation. 2.2 Using String Objects As we know, a Java program is a collection of interacting objects, where each object is a module that encapsulates a portion of the program’s attributes and actions. Objects belong to classes, which serve as templates or blueprints for creating objects. Think again of the cookie cutter analogy. A class is like a cookie cutter. Just as a cookie cutter is used to shape and create individual cookies, a class definition is used to shape and create individual objects. Programming in Java is primarily a matter of designing and defining class definitions, which are then used to construct objects. The objects perform the program’s desired actions. To push the cookie cutter analogy a little further, designing and defining a class is like building the cookie cutter. Obviously, very few of us would bake cookies if we first had to design and build the cookie cutters. We’d be better off using a pre-built cookie cutter. By the same token, rather than designing our own classes, it will be easier to get into “baking” programs if we begin by using some predefined Java classes. The Java library contains many pre-defined classes that we will use in our programs. So let’s begin our study of programming by using two of these classes, the String and Graphics classes. 2.2.1 Creating and Combining Strings Strings are very useful objects in Java and in all computer programs. They Figure 2.1: A partial representation of the String class. are used for inputting and outputting all types of data. Therefore, it essential that we learn how to create and use String objects. Figure 2.1 provides an overview of a very small part of Java’s String class. In addition to the two String() constructor methods, which are used to create strings, it lists several useful instance methods that can be used to manipulate strings. The String class also has two instance variables. One stores the String’s value, which is a string of characters such as “Hello98”, and the other stores the String’s count, which is the number of characters in its string value. Recall from Chapter 0 that in order to get things done in a program we send messages to objects. The messages must correspond to the object’s instance methods. Sending a message to an object is a matter of calling one of its instance methods. In effect, we use an object’s methods to get the

SECTION 2.2 • Using String Objects 63 object to perform certain actions for us. For example, if we have a String, named str and we want to find out how many characters it contains, we can call its length() method, using the expression str.length(). If we want to print str’s length, we can embed this expression in a print statement: ☛ ✟ System . ou t . p ri n tl n ( s t r . len g th ( ) ) ; // P r i n t s t r ’ s l e n g t h ✡ ✠ In general, to use an object’s instance method, we refer to the method in Dot notation dot notation by first naming the object and then the method: objectName.methodName() ; The objectName refers to a particular object, and the methodName() refers to one of its instance methods. As this example makes clear, instance methods belong to objects, and in order to use a method, you must first have an object that has that method. So, to use one of the String methods in a program, we must first create a String object. To create a String object in a program, we first declare a String variable. ☛ ✟ S t ri n g s t r ; // D e c l a r e a S t r i n g v a r i a b l e n am e d s t r ✡ ✠ We then create a String object by using Figure 2.2: A String object stores a sequence of characters and a count giving the number of characters. the new keyword in conjunction with one of the String() constructors. We assign the new object to the variable we declared: ☛ ✟ s t r = new S t ri n g ( ” Hello ” ) ; // C r e a t e a S t r i n g o b j e c t ✡ ✠ This example will create a String that contains, as its value, the word ”Hello” that is passed in by the constructor. The String object that this creates is shown in Figure 2.2. We can also use a constructor with an empty parameter list. Note that in this case we combine the variable declaration and the object creation into one statement: ☛ ✟ S t ri n g s t r 2 = new S t ri n g ( ) ; // C r e a t e a S t r i n g ✡ ✠ This example will create a String object that contains the empty string as its value. The empty string has the literal value ”” – that is, a pair of double quotes that contain no characters. Because the empty string has no characters, the count variable stores a zero (Fig. 2.3). Figure 2.3: The empty string has a value of ”” and a its length is 0. Note that we use a constructor to assign an initial value to a variable of type String (or of a type equal to any other class). This differs from how we assign an initial value to variables of primitive type, for which we use a simple assignment operator. This difference is related to an important difference in the way Java treats these two types of variables. Variables of primitive type are names for memory locations where values of primitive type are stored. As soon as they are declared they are assigned a default value of that primitive type. The default value for int is 0 and

s2 ) ; ✡ ✠ Another useful String method is the equals() method. This is a boolean method, which is used to compare two Strings. If both Strings have the same characters, in the same order, it will return true.

s6 ) ; } // m a i n ( ) } // S t r i n g P u n s c l a s s ✡ ✠ Figure 2.4: A program that prints silly string puns.

” . ” ) ; ✡ ✠ 2.3 Drawing Shapes with a Graphics Object (Optional) All of the instance methods of the String class that we examined return values. The length() method return an int value, and the concat() method returned a String. It is also very common for classes to define instance methods that perform actions but do not return a value. The Graphics object, g, that appears in Chapter 1’s HelloWorldSwing is one example. The program is reproduced in Figure 2.5 ☛ ✟ /∗ ∗ F i l e : H e l l o W o r l d S w i n g p r o g r a m ∗/ import j a v a x . swing . JFrame ; // I m p o r t c l a s s n a m e s import j a v a . awt . Graphics ; import j a v a . awt . Canvas ; pub l ic c l a s s HelloWorldCanvas ex tends Canvas // C l a s s h e a d e r { // S t a r t o f b o d y pub l ic void p ai n t ( Graphics g ) // T h e p a i n t m e t h o d { g . drawS tring ( ”Hello , World ! ” , 1 0 , 1 0 ) ; } // E n d o f p a i n t pub l ic s t a t i c void main ( S t ri n g [ ] a rgs ){ HelloWorldCanvas c = new HelloWorldCanvas ( ) ; JFrame f = new JFrame ( ) ; f . add ( c ) ; f . s e t S i z e ( 1 5 0 , 5 0 ) ; f . s e t V i s i b l e ( t ru e ) ; } } // E n d o f H e l l o W o r l d C a n v a s ✡ ✠ Figure 2.5: HelloWorldCanvas program source code.

SECTION 2.3 • Drawing Shapes with a Graphics Object (Optional) 67 At this point we will not worry about the language features that enable the paint() method to draw on the Java Swing window. We will focus instead on the information needed to make good use of the g.drawString() method. The first thing you should know is that, when the paint() method is executed, its parameter, g, refers to an instance of the Graphics class. Unlike our other examples involving variables that refer to objects, in this case there is no need to use a constructor to create an object of type Graphics. We can assume g already refers to such an object. We already know that the statement ☛ ✟ g . drawS tring ( ”Hello , World ! ” , 1 0 , 1 0 ) ; ✡ ✠ displays the String “Hello, World!” in the program window. More generally, if str is a literal String value or a reference to a String object and x and y are literal int values or int variables then ☛ ✟ g . drawS tring ( s t r , x , y ) ✡ ✠ displays the String str from left to right in the program window beginning at a point which is x pixels from the left edge of the window and y pixels down from the top edge of the window. In a graphics window, the point with coordinates (0,0) is at the top-left corner. The horizontal axis grows positively from left to right. The vertical axis grows positively from top to bottom (Fig. 2.6). Figure 2.6: Coordinate system of a Java window. (A pixel is a dot on the console window that can be set to a certain color.) Notice that increasing the value of y will cause str to be displayed lower. This is the opposite of the usual x and y coordinate system used in mathematics where increasing the y value designates a higher point. With this information about g.drawString(), we can calculate where to display any message in the program window. For example, if we wish to display the message “Welcome to Java” 25 pixels below where “Hello, World!” is displayed we could use the statements ☛ ✟ g . drawS tring ( ”Hello , World ! ” , 1 0 , 1 0 ) ; g . drawS tring ( ”Welcome t o J av a ” , 1 0 , 3 5 ) ; ✡ ✠ in the body of HelloWorldCanvas’s paint() method. The result of these statements would appear as shown in Figure 2.7. 2.3.1 Graphics Drawing Methods The Graphics class discussed in the previous section also has methods that can be used to draw geometric shapes in different colors. These methods can be used to create graphical user interfaces that are more interesting or to give a visual representation of data, such as a pie chart or a bar graph. There are two Graphics methods for drawing rectangles, fillRect() and drawRect() (Fig. 2.8). The first draws a rectangle and fills it with the current drawing color and the second just draws the outline of the rectangle. Using the Graphics object, g, each of these is called in the same way

68 CHAPTER 2 • Objects: Using, Creating, and Defining Figure 2.7: “Hello, World!” is drawn at coordinate (10, 10) and “Welcome to Java” at (10, 35) on the JFrame. as the drawString() method from the previous example. Each of these methods takes four int arguments, which specify the rectangle’s location Figure 2.8: Some of the drawing methods in the Graphics class. and size. Thus, a call to fillRect() would take the form ☛ ✟ g . f i l l R e c t ( x , y , width , hei gh t ) ; ✡ ✠ where x and y arguments specify the location of the upper left corner of the rectangle as being x pixels from the left edge of the window and y pixels down from the top edge of the window. The width and height arguments specify the width and height of the rectangle in pixels. The drawRect() method also takes the same four arguments. A Graphics object stores a single color for use in drawing shapes or displaying strings with drawString(). If we wish to draw an interesting scene in the JFrame, we need to understand how to use colors. For a given Graphics object, such as g, the setColor() method will set its color for all subsequent drawing commands. The setColor() method takes, as an argument, an object of type Color. All we need to know about the Color class is that it is contained in the java.awt package and that it contains 13 constant Color objects corresponding to 13 common colors. Table 2.1 lists the 13 Color constants. Each name corresponds to the color it will represent in the program. Color.black Color.green Color.red Color.blue Color.lightGreen Color.white Color.cyan Color.magenta Color.yellow Color.darkGray Color.orange Color.gray Color.pink Table 2.1: Predefined color constants in the Color class. To demonstrate how the new Graphics methods can be used for creating more interesting graphical programs, let’s develop a plan for displaying the two messages, “Hello, World!” and “Welcome to Java.”, on an JFrame, but this time we will draw the first inside a colored rectangle and the second inside a colored oval. For the rectangle, let’s use the

SECTION 2.4 • Class Definition 69 drawRect() method to create its border. We can choose some arbitrary colors, say, cyan for filling the rectangle, blue for its border, and black for the string itself. In order to have the message visible we should fill a rectangle with the color cyan first, then draw the border of the rectangle in blue and, finally, display the message in black. Drawing and filling a Graphics oval is very similar to drawing and filling a rectangle. Notice in Figure 2.8 that the fillOval() and drawOval() methods take the same four arguments as the corresponding rectangle methods. An oval is inscribed within an enclosing rectangle. The x and y arguments give the coordinates of the enclosing rectangle’s top left point. And the width and height arguments give the enclosing rectangles dimensions. All that remains is to choose the location and dimensions of the rectangles. We could specify one rectangle as having its upper left corner 25 pixels to the right of the left edge of the JFrame and 25 pixels down from the top edge. A medium sized rectangle could have a width of 140 pixels and a height of 40 pixels. The statement ☛ ✟ g . f i l l R e c t ( 2 5 , 2 5 , 1 4 0 , 4 0 ) ; ✡ ✠ will fill this rectangle with whatever color happens to be g’s current color. A location 25 pixels to the right of the left edge of the rectangle and 25 pixels down from the top edge of the rectangle would have coordinates x = 50 and y = 50. Thus, the statement ☛ ✟ g . drawS tring ( ”Hello , World ! ” , 5 0 , 5 0 ) ; ✡ ✠ will display “Hello, World!” inside the rectangle. We can use similar planning to locate the oval and its enclosed message. Thus, we now have sufficient information to finish the paint() method for accomplishing our plan. The completed program is displayed in Figure 2.9. Note how we repeatedly use the g.setColor() method to change g’s current color before drawing each element of our picture. Figure 2.10 shows what this program looks like. To experiment with this Java Swing application, download its sourcecode from the book’s Web site and compile and run it on your computer. Additional drawing capabilities will be explored throughout the text in sections that can either be covered or skipped. 2.4 Class Definition To program in Java the main thing you do is write class definitions for the The class as template various objects that will make up the program. A class definition encapsulates its objects’ data and behavior. Once a class has been defined, it serves as a template, or blueprint, for creating individual objects or instances of the class. A class definition contains two types of elements: variables and methods. Variables are used to store the object’s information. Methods are used Variables and methods

70 CHAPTER 2 • Objects: Using, Creating, and Defining ☛ ✟ import j a v a . awt . ∗ ; import j a v a x . swing . JFrame ; pub l ic c l a s s HelloWorldGraphic ex tends Canvas { // c a l l e d a f t e r s e t V i s i b l e ( t r u e ) pub l ic void p ai n t ( Graphics g ) { g . s e t C ol o r ( Color . cyan ) ; // S e t c o l o r g . f i l l R e c t ( 2 5 , 2 5 , 1 4 0 , 4 0 ) ; // F i l l r e c t a n g l e g . s e t C ol o r ( Color . blue ) ; // S e t c o l o r g . drawRect ( 2 5 , 2 5 , 1 4 0 , 4 0 ) ; // O u t l i n e r e c t a n g l e g . s e t C ol o r ( Color . bl ack ) ; // S e t c o l o r g . drawS tring ( ”Hello , World ! ” , 5 0 , 5 0 ) ; // D i s p l a y s t r i n g g . s e t C ol o r ( Color . yellow ) ; g . f i l l O v a l ( 2 5 , 7 5 , 1 4 0 , 4 0 ) ; // F i l l o v a l g . s e t C ol o r ( Color . red ) ; g . drawOval ( 2 5 , 7 5 , 1 4 0 , 4 0 ) ; // O u t l i n e o v a l g . s e t C ol o r ( Color . bl ack ) ; g . drawS tring ( ”Welcome t o J av a ” , 5 0 , 1 0 0 ) ; } // p a i n t ( ) // t h e p r o g r a m pub l ic s t a t i c void main ( S t ri n g [ ] a rgs ){ HelloWorldCanvas c = new HelloWorldCanvas ( ) ; JFrame f = new JFrame ( ) ; f . add ( c ) ; f . s e t S i z e ( 1 5 0 , 5 0 ) ; f . s e t V i s i b l e ( t ru e ) ; } } // H e l l o W o r l d G r a p h i c ✡ ✠ Figure 2.9: The HelloWorldGraphic class is a Java Swing program that shows how to use color and drawing methods. to process the information. To design an object you need to answer five basic questions: 1. What role will the object perform in the program? 2. What data or information will it need? 3. What actions will it take? 4. What interface will it present to other objects? 5. What information will it hide from other objects? Figure 2.11: The Riddle class. 2.4.1 The Riddle Class Recall our definition of the Riddle class from Chapter 1, which is summarized in the UML diagram in Figure 2.11. A Riddle has two attributes, question and answer. Each of these variables stores a string of characters, which Java treats as data of type String. The Riddle class contains three methods. The Riddle() constructor method assigns initial values (q and a) to its question and answer variables. The getQuestion() and getAnswer() methods return the data stored in question ands answer respectively.

). These designations follow two important object-oriented design conventions, whose justification will become apparent as we discuss the Riddle class: JAVA EFFECTIVE DESIGN Private Variables. Instance variables are usually declared private so that they cannot be directly accessed by other objects. JAVA EFFECTIVE DESIGN Public Methods. An object’s public methods can be used by other objects to interact with the object. The public methods and variables of an object make up its interface. Figure 2.12 shows the Java class definition that corresponds to the design given in the UML diagram. It contains the two private instance variables and defines the three public methods listed in the UML diagram. In a Java class definition, access to a class element, such as a variable or a method, is controlled by labeling it with either the private, or public access modifier. An access modifier is a declaration that controls Access modifier access to a class or one of its elements. Note also that the Riddle class itself is declared public. This lets other classes have access to the class and to its public variables and methods. Recall that a class is like a blueprint or a cookie cutter. The Riddle class defines the type of information (attributes) that each individual Riddle has, but it doesn’t contain any actual values. It defines the methods (operations) that each Riddle can perform, but it doesn’t actually perform the methods. In short, a class serves as a template, providing a detailed blueprint of the objects (or instances) of that class. Class as blueprint

72 CHAPTER 2 • Objects: Using, Creating, and Defining ☛ ✟ pub l ic c l a s s Riddle { p r i v a t e S t ri n g que s ti on ; // I n s t a n c e v a r i a b l e s p r i v a t e S t ri n g answer ; pub l ic Riddle ( S t ri n g q , S t ri n g a ) // C o n s t r u c t o r { que s ti on = q ; answer = a ; } // R i d d l e c o n s t r u c t o r pub l ic S t ri n g ge tQues tion ( ) // I n s t a n c e m e t h o d { r e tu rn que s ti on ; } // g e t Q u e s t i o n ( ) pub l ic S t ri n g getAnswer ( ) // I n s t a n c e m e t h o d { r e tu rn answer ; } // g e t A n s w e r ( ) } // R i d d l e c l a s s ✡ ✠ Figure 2.12: Definition of the Riddle class. 2.4.2 The RiddleUser Class Now that we have defined the Riddle class, we can test that it works correctly by creating Riddle objects and “asking” them to tell us their riddles. To do this we need to define a main() method, which can be defined either within the Riddle class itself or in a second class named something like RiddleUser. User interface One advantage of using a second class is that it gets us in the habit of thinking about the need for a separate class to serve as a user interface, with a separate set of tasks from the Riddle class. A user interface is an object or class that handles the interaction between a program’s user and the rest of the program’s computational tasks. This concept is illustrated in Figure 2.13. Note that we use the general term computational object to distinguish the rest of the program’s computations from the user interface. Obviously, the exact nature of the computation will vary from program to program, just as will the details of the user interface. The computation done by our Riddle class is just the storing and displaying of a riddle’s question and answer. Figure 2.13: The user interfaces handles interaction between the user and the rest of the program. By separating user interface tasks from riddle tasks this design employs the divide-and-conquer principle: the RiddleUser class will create Riddle objects and handle interactions with the user, and the Riddle class will handle the storing and transmission of riddle information. Thus, as shown in Figure 2.14, this particular Java program will involve interaction between two types of objects: a RiddleUser and one or more Riddles. Note that we characterize the relationship between Riddle and RiddleUser with a one-way arrow labeled “Uses.” This is because the RiddleUser will create an instance of Riddle and use its methods to display (for the user) a riddle. Because almost all of our programs will involve some form of a user interface, we can generalize this design approach and follow it throughout the book. One way to think about this approach is as a division of labor

SECTION 2.4 • Class Definition 73 Figure 2.14: This UML class diagram represents an association between the RiddleUser and Riddle classes. The RiddleUser class will use one or more objects of the Riddle class. between a user interface class and a second computational class, which performs whatever computations are needed by the particular program. In this case the computations are the simple Riddle methods that we have defined. In subsequent programs the computations will become more complex, which will make all the more clear that they should be separated from the user interface. 2.4.3 Object Instantiation: Creating Riddle Instances Figure 2.15 shows the complete definition of the RiddleUser class, which serves as a very simple user interface. It creates two Riddle objects, named riddle1 and riddle2. It then asks each object to request each riddle’s question and answer and displays them on the console. ☛ ✟ pub l ic c l a s s RiddleUser { pub l ic s t a t i c void main ( S t ri n g argv [ ] ) { Riddle ri d dl e 1 = new Riddle ( ”What i s bl ack and whi te and red a l l over ? ” , ”An embarrassed zebra . ” ) ; Riddle ri d dl e 2 = new Riddle ( ”What i s bl ack and whi te and read a l l over ? ” , ”A newspaper . ” ) ; System . ou t . p ri n tl n ( ”Here a re two ri d dl e s : ” ) ; System . ou t . p ri n tl n ( ri d dl e 1 . ge tQues tion ( ) ) ; System . ou t . p ri n tl n ( ri d dl e 2 . ge tQues tion ( ) ) ; System . ou t . p ri n tl n ( ”The answer t o the f i r s t ri d dl e i s : ” ) ; System . ou t . p ri n tl n ( ri d dl e 1 . getAnswer ( ) ) ; System . ou t . p ri n tl n ( ”The answer t o the second i s : ” ) ; System . ou t . p ri n tl n ( ri d dl e 2 . getAnswer ( ) ) ; } // m a i n ( ) } // R i d d l e U s e r ✡ ✠ Figure 2.15: The RiddleUser class.

74 CHAPTER 2 • Objects: Using, Creating, and Defining Let’s now discuss the statements that make up RiddleUser’s main() method. The following statements use the Riddle() constructor to create, or instantiate, two instances of the Riddle class: ☛ ✟ Riddle ri d dl e 1 = new Riddle ( ”What i s bl ack and white and red a l l over ? ” , ”An embarrassed zebra . ” ) ; Riddle ri d dl e 2 = new Riddle ( ”What i s bl ack and white and read a l l over ? ” , ”A newspaper . ” ) ; ✡ ✠ Note how the constructor gives each object a pair of Strings that serve as the values of their two instance variables. Each object has its own question and its own answer, and each object has its own unique name, riddle1 and riddle2. 2.4.4 Interacting with Riddles Once we have created Riddle instances with values assigned to their question and answer instance variables, we can ask each riddle to tell us either of its values. The following expression is an example of a method call: ☛ ✟ ri d dl e 1 . ge tQues tion ( ) ✡ ✠ Method call Calling (or invoking) a method is a means of executing its code. The above method call just gets the String value that is stored in the question instance variable of riddle1. JAVA PROGRAMMING TIP Method Call versus Method Definition. Don’t confuse method calls with method definitions. The definition specifies the method’s actions. The method call takes those actions. If we want to display the value of riddle1’s question, we can embed this method call within a println() statement ☛ ✟ System . ou t . p ri n tl n ( ri d dl e 1 . ge tQues tion ( ) ) ; ✡ ✠ This tells the System.out object to execute its println() method, which displays the string given to it by riddle1 on the console. Thus, the output produced by this statement will be ☛ ✟ What i s bl ack and white and red a l l over ? ✡ ✠ 2.4.5 Define, Create, Use As our Riddle example illustrates, writing a Java program is a matter of three basic steps: • Define one or more classes (class definition).

SECTION 2.4 • Class Definition 75 • Create objects as instances of the classes (object instantiation). • Use the objects to do tasks (object use). The Java class definition determines what information will be stored in each object and what methods each object can perform. Instantiation creates an instance and associates a name with it in the program. The object’s methods can then be called as a way of getting the object to perform certain tasks.

76 CHAPTER 2 • Objects: Using, Creating, and Defining SELF-STUDY EXERCISES EXERCISE 2.2 Identify the following elements in the Riddle class (Fig. 2.12): • The name of the class. • The names of two instance variables. • The names of three methods. EXERCISE 2.3 Identify the following elements in the RiddleUser class (Fig. 2.15): • The names of two Riddle instances. • All six method calls of the Riddle objects in the program. • Two examples of qualified names. 2.5 CASE STUDY: Simulating a Two-Person Game In this section, we will design and write the definition for a class that keeps track of the details of a well known, two-person game. We will focus on details of designing the definition of a class in the Java language. Our objective is to understand what the program is doing and how it works without necessarily understanding why it works the way it does. We will get to “why” later in the book. The game we will consider is played by two persons with a row of sticks or coins or other objects. The players alternate turns. A player must remove one, two, or three sticks from the row on his or her turn. The player who removes the last stick from the row loses. The game can be played with any number of sticks but starting with twenty one sticks is quite common. This game is sometimes referred to as the game of ”Nim”, but there is a similar game involving multiple rows of sticks that is more frequently given that name. Thus we will refer to this game as ”One Row Nim”. 2.5.1 Designing a OneRowNim class Problem Specification Let’s design a class named OneRowNim that simulates the game of One Row Nim with a row of sticks. An object constructed with this class should manage data that corresponds to having some specified number of sticks when the game begins. It should keep track of whose turn it is and it should allow a player to diminish the number of sticks remaining by one, two, or three. Finally, a OneRowNim object should be able to decide when the game is over and which player has won. Problem Decomposition Let’s design OneRowNim so that it can be used in with different kinds of user interfaces. One user interface could manage a game played by two persons who alternately designate their moves to the computer. Another user interface could let a human player play against moves made by the

SECTION 2.5 • CASE STUDY: Simulating a Two-Person Game 77 computer. In either of these cases we could have a human player designate a move by typing from the keyboard after being prompted in a console window or, alternatively, by inputting a number into a text field or selecting a radio button on a window. In this chapter, we will be concerned only with designing an object for managing the game. We will design user interfaces for the game in subsequent chapters. Class Design: OneRowNim As we saw in the Riddle example, class definitions can usually be broken down into two parts: (1) the information or attributes that the object needs which must be stored in variables, and (2) the behavior or actions the object can take which are defined in methods. In this chapter, we will focus on choosing appropriate instance variables and on designing methods as blocks of reusable code. Recall that a parameter is a variable that temporarily stores data values that are being passed to a method when that method is called. In this chapter, we will restrict our design to methods that do not have parameters and do not return values. We will return to the problem of designing changes to this class in the next chapter after an in-depth discussion of method parameters and return values. The OneRowNim object should manage two pieces of information that What data do we need? vary as the game is played. One is the number of sticks remaining in the row and the other is which player has the next turn. Clearly, the number of sticks remaining corresponds to a positive integer that can be stored in a variable of type int. One suitable name for such a variable is nSticks. For this chapter, let us assume that the game starts with 7 sticks, rather than 21, to simplify discussion of the program. Data designating which player takes the next turn could be stored in different ways. One way to do this is to think of the players as player one and player two and store a 1 or 2 in an int variable. Let’s use player as the name for such a variable and assume that player one has the first turn. The values of these two variable for a particular OneRowNim object at a particular time describes the object’s state. An object’s state at the beginning of a game is a 7 stored in nSticks and 1 stored in player. After player one removes, say, two sticks on the first turn, the values 5 and 2 will be stored in the two variables. Method Decomposition Now that we have decided what information the OneRowNim object should manage, we need to decide what actions it should be able to perform. We should think of methods that would be needed to communicate with a user interface that is both prompting some human players as well as receiving moves from them. Clearly, methods are needed for taking a What methods do we need? turn in the game. If a message to a OneRowNim object has no argument to indicate the number of sticks taken, there will need to be three methods corresponding to taking one, two, or three sticks. The method names takeOne(), takeTwo(), and takeThree() are descriptive of this action. Each of these methods will be responsible for reducing the value of nSticks as well as changing the value of player.

) and will thereby form the interface for a OneRowNim object. These will be the methods that other objects will use to interact with it. Similarly, we have followed the convention of designating an object’s instance variables—the OneRowNim’s instance variables—be kept hidden from other objects, and so we have designated them as private(−). 2.5.2 Defining the OneRowNim Class Given our design of the OneRowNim class as described in Figure 2.16, the next step in building our simulation is to begin writing the Java class definition. The Class Header We need a class header, which will give the class a name and will specify its relationship to other classes. Like all classes that are designed to create objects that could be used by other objects or classes, the class OneRowNim should be preceded by the public modifier. Because the class OneRowNim has not been described as having any relationship to any other Java class, its header can omit the extends clause so it will be a direct subclass of Object (Figure 2.17). Thus, the class header for Figure 2.17: By default, OneRowNim is a subclass of Object. OneRowNim will look like: ☛ ✟ pub l ic c l a s s OneRowNim // C l a s s h e a d e r { // B e g i n n i n g o f c l a s s b o d y } // E n d o f c l a s s b o d y ✡ ✠ The Class’s Instance Variables Variables and methods The body of a class definition consists of two parts: the class-level variables and the method definitions. A class-level variable is a variable whose definition applies to the entire class in which it is defined. Instance variables, which were introduced in Chapter 1, are one kind of class-level variable. In general, a class definition will take the form shown in Figure 2.18. Although Java does not impose any particular order on variable and method declarations, in this book we’ll define the class’s class-level variables at the beginning of the class definition, followed by method definiClass-level vs. local variables tions. Class-level variables are distinguished from local variables. A local variable is a variable that is defined within a method. Examples would be the variables q and a that were defined in the Riddle(String q, String a) constructor (Fig. 2.12). As we will see better in Chapter 3, Java handles each type of variable differently. A declaration for a variable at class level must follow the rules for declaring variables that were described in Section 1.4.8 with the added

SECTION 2.5 • CASE STUDY: Simulating a Two-Person Game 79 ☛ ✟ pub l ic c l a s s ClassName { // I n s t a n c e a n d c l a s s v a r i a b l e s V a ri a bl eD e cl a r a ti o n 1 V a ri a bl eD e cl a r a ti o n 2 . . . // I n s t a n c e a n d c l a s s m e t h o d s Me thodDe fini tion1 Me thodDe fini tion2 . . . } // E n d o f c l a s s ✡ ✠ Figure 2.18: A template for constructing a Java class definition. restriction that they should be modified by one of the access modifiers public, private, or protected. The rules associated with these access modifiers are: • A private class-level variable cannot be accessed outside the class in which it is declared. • A public class-level variable can be referenced and, hence, modified by any other class. • A protected class-level variable can only be accessed by subclasses of the class in which it is declared or by other classes that belong to the same package. When a class, instance variable, or method is defined, you can declare it public, protected, or private. Or you can leave its access unspecified, in which case Java’s default accessibility will apply. Java determines accessibility in a top-down manner. Instance variables and methods are contained in classes, which are contained in packages. To determine whether a instance variable or method is accessible, Java starts by determining whether its containing package is accessible, and then whether its containing class is accessible. Access to classes, instance variables, and methods is defined according to the rules shown in Table 2.2. TABLE 2.2 Java’s accessibility rules. Element Modifier Rule Class public Accessible if its package is accessible. by default Accessible only within its package. Instance variable public Accessible to all other objects. or protected Accessible to its subclasses and to instance method other classes in its package. private Accessible only within the class. by default Accessible only within the package. Recall the distinction we made in Chapter 0 between class variables and instance variables. A class variable is associated with the class it-

80 CHAPTER 2 • Objects: Using, Creating, and Defining self, whereas an instance variable is associated with each of the class’s instances. In other words, each object contains its own copy of the class’s instance variables, but only the class itself contains the single copy of a class variable. To designate a variable as a class variable it must be declared static. The Riddle class that we considered earlier has the following two examples of valid declarations of instance variables: ☛ ✟ p r i v a t e S t ri n g que s ti on ; p r i v a t e S t ri n g answer ; ✡ ✠ Class Level Variables for OneRowNim Let’s now consider how to declare the class level variables for the OneRowNim class. The UML class diagram for OneRowNim in Figure 2.16 contains all the information we need. The variables nSticks and player will store data for playing one game of One Row Nim, so they should clearly be private instance variables. They both will store integer values, so they should be declared as variables of type int. Because we wish to start a game of One Row Nim using 7 sticks with player one making the first move, we will assign 7 as the initial value for nSticks and 1 as the initial value for player. If we add the declarations for our instance variable declarations to the class header for the OneRowNim class, we get the following: ☛ ✟ pub l ic c l a s s OneRowNim { p r i v a t e i n t n S ti c k s = 7 ; p r i v a t e i n t pl aye r = 1 ; // M e t h o d d e f i n i t i o n s g o h e r e } // OneRowNim ✡ ✠ To summarize, despite its apparent simplicity, a class level variable declaration actually accomplishes five tasks: 1. Sets aside a portion of the object’s memory that can be used to store a certain type of data. 2. Specifies the type of data that can be stored in that location. 3. Associates an identifier (or name) with that location. 4. Determines which objects have access to the variable’s name. 5. Assigns an initial value to the location. OneRowNim’s Methods Designing and defining methods is a form of abstraction. By defining a certain sequence of actions as a method, you encapsulate those actions under a single name that can be invoked whenever needed. Instead of having to list the entire sequence again each time you want it performed, you simply call it by name. As you recall from Chapter 1, a method definition consists of two parts, the method header and the method body.

SECTION 2.5 • CASE STUDY: Simulating a Two-Person Game 81 The method header declares the name of the method and other general information about the method. The method body contains the executable statements that the method performs. ☛ ✟ pub l ic void methodName ( ) // M e t h o d h e a d e r { // B e g i n n i n g o f m e t h o d b o d y } // E n d o f m e t h o d b o d y ✡ ✠ The Method Header The method header follows a general format that consists of one or more MethodModifiers, the method’s ResultType, the MethodName, and the method’s FormalParameterList, which is enclosed in parentheses. The following table illustrates the method header form, and includes several examples of method headers that we have already encountered. The method body follows the method header. MethodModifiersopt ResultType MethodName (FormalParameterList) public static void main (String argv[]) public void paint (Graphics g) public Riddle (String q, String a) public String getQuestion () public String getAnswer () The rules on method access are the same as the rules on instance variable access: private methods are accessible only within the class itself, protected methods are accessible only to subclasses of the class in which the method is defined and to other classes in the same package, and public methods are accessible to all other classes. JAVA EFFECTIVE DESIGN Public versus Private Methods. If a method is used to communicate with an object, or if it passes information to or from an object, it should be declared public. If a method is intended to be used solely for internal operations within the object, it should be declared private. These methods are sometimes called utility methods or helper methods. Recall the distinction from Chapter 0 between instance methods and class methods. Methods declared at the class level are assumed to be instance methods unless they are also declared static. The static modifier is used to declare that a class method or variable is associated with the class itself, rather than with its instances. Just as for static variables, methods that are declared static are associated with the class and are therefore called class methods. As its name implies, an instance method can only be used in association with an object (or instance) of a class. Most of the class-level methods we declare will be instance methods. Class methods are used only rarely in Java and mainly in situations where it

82 CHAPTER 2 • Objects: Using, Creating, and Defining is necessary to perform some kind calculation before objects of the class are created. We will see examples of class methods when we discuss the Math class, which has such methods as sqrt(N) to calculate the square root of N. JAVA PROGRAMMING TIP Class versus Instance Methods. If a method is designed to be used by an object, it is referred to as an instance method. No modifier is needed to designate an instance method. Class methods, which are used infrequently compared to instance methods, must be declared static. All four of the methods in the OneRowNim class are instance methods (Fig. 2.19). They all perform actions associated with a particular instance ☛ ✟ pub l ic c l a s s OneRowNim { p r i v a t e i n t n S ti c k s = 7 ; // S t a r t w i t h 7 s t i c k s . p r i v a t e i n t pl aye r = 1 ; // P l a y e r 1 p l a y s f i r s t . pub l ic void takeOne ( ) { } // M e t h o d b o d i e s n e e d pub l ic void takeTwo ( ) { } // t o b e d e f i n e d . pub l ic void takeTh ree ( ) { } pub l ic void r e p o r t ( ) { } } // OneRowNim c l a s s ✡ ✠ Figure 2.19: The Instance variables and method headers for the OneRowNim class. of OneRowNim. That is, they are all used to manage a particular One Row Nim game. Moreover, all four methods should be declared public, because they are designed for communicating with other objects rather than for performing internal calculations. Three of the methods are described as changing the values of the instance variables nSticks and player and the fourth, report(), writes information to the console. All four methods will receive no data when being called and will not return any values. Thus they should all have void as a return type and should all have empty parameter lists. Given these design decisions, we now can add method headers to our class definition of OneRowNim, in Figure 2.19. The figure displays the class header, instance variable declarations, and method headers. The Method Body Designing a method is an application The body of a method definition is a block of Java statements enclosed of the encapsulation principle. by braces, , which are executed in sequence when the method is called. The description of the action required of the takeOne() method is typical of many methods that change the state of an object. The body of the takeOne() method should use a series of assignment statements to reduce the value stored in nSticks by one and change the value in

pl aye r ) ; ✡ ✠ This completes the method bodies of the OneRowNim class. The completed class definition is shown in Figure 2.20. We will discuss alternative methods for this class in the next chapter. In Chapter 4, we will develop several One Row Nim user interface classes that will facilitate a user indicating certain moves to make.

pl aye r ) ; } // r e p o r t ( ) } // O neR owNim 1 c l a s s ✡ ✠ Figure 2.20: The OneRowNim class definition. 2.5.3 Testing the OneRowNim Class Recall our define, create, and use mantra from Section 2.4.5. Now that we have defined the OneRowNim class, we can test whether it works correctly by creating OneRowNim objects and using them to perform the actions associated with the game. At this point, we can test OneRowNim by defining a main() method. Following the design we used in the riddle example, we will locate the main() method in separate, user interface class, named OneRowNimTester. The body of main() should declare a variable of type OneRowNim and create an object for it to refer to. The variable can have any name, but a name like game would be consistent with it recording moves in a single game. To test the OneRowNim class, we should make a typical series of moves. For example, three moves taking 3, 3, and 1 sticks respectively would be one way that the 7 sticks could be removed. Also, executing the report() method before the first move and after each move should display the current state of the game in the console window so that we can determine whether it is working correctly. The following pseudocode outlines an appropriate sequence of statements in a main() method:

java java java object oriented problem solving pdf

Personal Usage and not for publication

Related publications.

IMAGES

  1. 9780130113320: Java, Java, Java: Object-Oriented Problem Solving

    java java java object oriented problem solving pdf

  2. Object Oriented Programming

    java java java object oriented problem solving pdf

  3. Java Java!

    java java java object oriented problem solving pdf

  4. Thinking in Java, 3rd Edition

    java java java object oriented problem solving pdf

  5. Java

    java java java object oriented problem solving pdf

  6. Java, Java, Java Object-Oriented Problem Solving by Ralph Morelli (2002, Paperback) for sale

    java java java object oriented problem solving pdf

VIDEO

  1. Buncombe News Update

  2. J2SE013-Introduction to Java Variable

  3. 50-- JAVA || BASICS OF EXCEPTIONS

  4. Java Object Oriented Programming 19

  5. Java Basics Part 1

  6. #java02 Variable in Java

COMMENTS

  1. Java, Java, Java

    Java, Java, Java. Object-Oriented Problem Solving. Third Edition. R. Morelli and R. Walde. Trinity College. Hartford, CT. June 25, 2017

  2. Java, Java, Java: Object-Oriented Problem Solving

    Java, Java, Java: Object-Oriented Problem Solving. (4 reviews). Ralph Morelli, Trinity College. Ralph Walde, Trinity College. Copyright Year

  3. Java, Java, Java

    Java, Java, Java. Object-Oriented Problem Solving. Third Edition. R. Morelli and R. Walde. Trinity College. Hartford, CT. June 25, 2017

  4. Java, Java, Java Object-Oriented Problem Solving

    Download Free PDF ... Java, Java, Java Object-Oriented Problem Solving ... edition retains the “objects first” approach to programming and problem solving

  5. Java, Java, Java: Object-Oriented Problem Solving

    eBook PDF (865 page, 6.3 MB), ePub, Daisy, Kindle, etc. Language: English; ISBN-10: 0131474340; ISBN-13: 978-0131474345; Share This:

  6. Java, Java, Java Object-Oriented Problem Solving : R. Morelli and R

    Java, Java, Java Object-Oriented Problem Solving Third Edition R. Morelli and R. Walde Trinity College Hartford, CT February 5, 2012.

  7. Java, Java, Java: Object-Oriented Problem Solving

    Java, Java, Java: Object-Oriented Problem Solving [Morelli, Ralph, Walde, Ralph] on Amazon.com. *FREE* shipping on qualifying offers. Java, Java, Java:

  8. Java Java Java Object Oriented Problem Solving

    Getting the books Java Java Java Object Oriented Problem Solving now is not type of inspiring means. You could not unaccompanied going afterward books

  9. Object-Oriented Problem Solving

    Java, Java, Java: Object-Oriented Problem Solving ... Description: Functional and flexible, this guide takes an objects-first approach to Java programming and

  10. Java, Java, Java Object-Oriented Problem Solving (Ralph Morelli

    Check Pages 51-100 of Java, Java, Java Object-Oriented Problem Solving (Ralph Morelli Ralph Walde) (z-lib.org) - 1151083366 in the flip PDF