

Introduction to Object-Oriented Programming with Java I: Foundations and Syntax Basics
Learn the foundational basics of the Java programming language.

Choose your session:
About this course.
This course provides an introduction to the Java programming language. It gives students a foundational overview and history of Java, and students will learn about the language’s basic syntax. At the end, they will be able to develop interactive console programs with basic data processing and formatting capabilities.
At a glance
- Institution: GTx
- Subject: Computer Science
- Level: Introductory
- Prerequisites: None
- Language: English
- Video Transcript: English
- Professional Certificate in Introduction to Object-Oriented Programming with Java
What you'll learn
- Learn the history of Java
- Learn the basic elements of a Java program
- Learn how to execute Java programs
- Understand the motivation behind object-oriented programming
- Understand how to think of solutions in terms of classes and objects
- Understand how whitespace, commenting, errors, variables, types, expressions, and casting manifest in Java
- Learn how to create objects of existing classes
- Learn how to invoke methods of existing classes
- Create objects and invoke methods of the String class
- Learn how to take inputs from the terminal
- Learn how to specify formatting requirements for text printed to the terminal
- Learn three kinds of decision-making statements (if, if-else, switch)
- Learn three kinds of iteration statements (while, do-while, for)
- Learn how to instantiate one- and two-dimensional arrays
- Learn how to access, change, traverse, and search for data in arrays
- Explore modularity and reusability in the context of methods
- Learn how to define static methods
- Understand when and how to overload methods
- Introduction to Java
- Why Object-Oriented Programming?
- Basics of Object-Oriented Programming
- Using Predefined Classes
- Basic Console Input and Output
- Programming Decision-Making Statements
- Developing Iterations and Loops
- Creating and Using Arrays
- Writing Methods
About the instructors
Ways to take this course, interested in this course for your business or team.
Starting a Business
- Business Plans
- Real Estate
- Business Models
- Business Ideas
- Side Hustle
- Fundraising
Growing a Business
- Business Process
- Operations & Logistics
- Employee Experience & Recruiting
- Collaboration
- Business Culture
- Thought Leaders
Business News
Science & technology.
- Social Media
- Business Solutions
- Data & Recovery
Money & Finance
- Debt / Loans / Refinancing
- Cryptocurrency / Blockchain
- Buying / Investing in Business
- Personal Finance
- Health & Wellness
- Productivity
- Celebrity Entrepreneurs
- Resumes & Interviewing
- Making a Change
- Franchise Advisors
- Franchise 500 Annual Ranking
- Featured Opportunities
- Find a Franchise
- Franchise Suppliers
- Buy a Franchise
- Grow Your Franchise
- Franchise Your Business
- Franchise News
Green Entrepreneur
- Find Success
- How to Go Green
- Latest News
- New Products
Copyright © 2023 Entrepreneur Media, Inc. All rights reserved. Entrepreneur® and its related marks are registered trademarks of Entrepreneur Media Inc.
Problem Solved
Stop startup problems before they even begin. Here are 5 common mistakes that can sabotage your business--and how to avoid them.
By Rosalind Resnick • Jun 1, 2008
Opinions expressed by Entrepreneur contributors are their own.
Reprinted with permission from Getting Rich Without Going Broke: How to Use Luck, Logic and Leverage to Build Your Own Successful Business by Rosalind Resnick (©2007). All rights reserved.
Rosalind Resnick, the founder and CEO of Axxess Business Consulting, a New York City consulting firm that advises startups and small businesses, is the co-founder and former CEO of NetCreations, a two-person homebased web design firm that grew to a $58 million public company and was acquired for $111 million in cash in 2001. In this excerpt from her book Getting Rich Without Going Broke: How to Use Luck, Logic and Leverage to Build Your Own Successful Business (PageFree Publishing), Resnick shares her secrets for building a multimillion-dollar business.
Continue reading this article — and all of our other premium content with Entrepreneur+
For just $5, you can get unlimited access to all Entrepreneur’s premium content. You’ll find:
- Digestible insight on how to be a better entrepreneur and leader
- Lessons for starting and growing a business from our expert network of CEOs and founders
- Meaningful content to help you make sharper decisions
- Business and life hacks to help you stay ahead of the curve
Related Topics
Editor's pick, most popular, carnival cruise wants passengers to have fun in the sun — but do this, and you'll get burned with a new $500 fee.
The cruise line's updated contract follows a spate of unruly guest behavior across the tourism industry.
By Amanda Breen
'My Health Will Be Better': Man Eating Only McDonald's for 100 Days Vows to Lose 50 Pounds
One man has become a viral sensation on TikTok after documenting his plan to lose 100 pounds by only eating McDonald's — and it seems to be paying off.
By Emily Rella
This Tool Can Elevate Your Video Marketing and Enhance Web Conferences and Your Social Media Strategy
Save big on the Pivo Pod Lite with advanced motion tracking.
By Entrepreneur Store
New Neuroscience Reveals the Best Way to Form Powerful Habits That Stick
New research proves that willpower and rewards aren't enough to build sustainable habits. Here's what else you need.
By Leah Borski
The Viral Brand Behind Soaring Searches for 'Female Body Hair' Still Gets Up Close and Personal After Its $310 Million Sale
Georgina Gooley co-founded Billie in 2017 to meet women's shaving needs and change the narrative around body hair.
Amazon Employees Are Fighting on Slack About Returning to the Office
Amazon announced in mid-February it would ask its employees to come back to the office at least three days a week.
By Gabrielle Bienasz
Successfully copied link

Java, Java, Java: Object-Oriented Problem Solving
(4 reviews)

Ralph Morelli, Trinity College
Ralph Walde, Trinity College
Copyright Year: 2016
Publisher: Ralph Morelli, Ralph Walde
Language: English
Formats Available
Conditions of use.

Learn more about reviews.

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
- 0 Computers, Objects, and Java
- 1 Java Program Design and Development
- 2 Objects: Defining, Creating, and Using
- 3 Methods: Communicating with Objects
- 4 Input/Output: Designing the User Interface
- 5 Java Data and Operators
- 6 Control Structures
- 7 Strings and String Processing
- 8 Inheritance and Polymorphism
- 9 Arrays and Array Processing
- 10 Exceptions: When Things Go Wrong
- 11 Files and Streams
- 12 Recursive Problem Solving
- 13 Graphical User Interfaces
- 14 Threads and Concurrent Programming
- 15 Sockets and Networking
- 16 Data Structures: Lists, Stacks, and Queues
Ancillary Material
- Ancillary materials are available by contacting the author or publisher .
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:
- Early Introduction of Objects
- Emphasis on Object Oriented Design (OOD)
- Unified Modeling Language (UML) Diagrams
- Self-study Exercises with Answers
- Programming, Debugging, and Design Tips.
- From the Java Library Sections
- Object-Oriented Design Sections
- End-of-Chapter Exercises
- Companion Web Site, with Power Points and other Resources
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
- Computers & Technology
Buy new: $72.00 $72.00 $5.98 delivery: March 16 - 17 Ships from: Skoobe Books Sold by: Skoobe Books
Buy used: $3.95, sorry, there was a problem., other sellers on amazon.

Download the free Kindle app and start reading Kindle books instantly on your smartphone, tablet, or computer - no Kindle device required . Learn more
Read instantly on your browser with Kindle for Web .
Using your mobile phone camera - scan the code below and download the Kindle app.

Follow the Author


Java, Java, Java: Object-Oriented Problem Solving Paperback – January 1, 2000
- Paperback $72.00 9 Used from $0.01 2 New from $72.00
- Mass Market Paperback $40.88 2 Used from $40.88 2 New from $180.96
There is a newer edition of this item:

Enhance your purchase
- Language English
- Publisher Prentice Hall
- Publication date January 1, 2000
- Dimensions 1.5 x 10.25 x 8 inches
- ISBN-10 0130113328
- ISBN-13 978-0130113320
- See all details

Special offers and product promotions
Frequently bought together.

- This item: Java, Java, Java: Object-Oriented Problem Solving by Ralph Morelli, R.; Morelli Paperback $72.00 In stock. Usually ships within 2 to 3 days. Ships from and sold by Skoobe Books. Get it Mar 16 - 17
- Think Java: How to Think Like a Computer Scientist by Allen Downey Paperback $24.49 In Stock. Ships from and sold by Amazon.com. Get it as soon as Monday, Mar 13
Customers who bought this item also bought

Customer reviews
Customer Reviews, including Product Star Ratings help customers to learn more about the product and decide whether it is the right product for them.
To calculate the overall star rating and percentage breakdown by star, we don’t use a simple average. Instead, our system considers things like how recent a review is and if the reviewer bought the item on Amazon. It also analyzed reviews to verify trustworthiness.
- Top reviews Most recent Top reviews
Top reviews from the United States
There was a problem filtering reviews right now. please try again later..

Top reviews from other countries

- Amazon Newsletter
- About Amazon
- Accessibility
- Sustainability
- Press Center
- Investor Relations
- Amazon Devices
- Amazon Science
- Sell products on Amazon
- Sell apps on Amazon
- Supply to Amazon
- Protect & Build Your Brand
- Become an Affiliate
- Become a Delivery Driver
- Start a package delivery business
- Advertise Your Products
- Self-Publish with Us
- Host an Amazon Hub
- › See More Ways to Make Money
- Amazon Rewards Visa Signature Cards
- Amazon Store Card
- Amazon Secured Card
- Amazon Business Card
- Shop with Points
- Credit Card Marketplace
- Reload Your Balance
- Amazon Currency Converter
- Amazon and COVID-19
- Your Account
- Your Orders
- Shipping Rates & Policies
- Amazon Prime
- Returns & Replacements
- Manage Your Content and Devices
- Your Recalls and Product Safety Alerts
- Amazon Assistant
- Conditions of Use
- Privacy Notice
- Your Ads Privacy Choices

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

Due to a planned power outage on Friday, 1/14, between 8am-1pm PST, some services may be impacted.
Internet Archive Audio
- This Just In
- Grateful Dead
- Old Time Radio
- 78 RPMs and Cylinder Recordings
- Audio Books & Poetry
- Computers, Technology and Science
- Music, Arts & Culture
- News & Public Affairs
- Spirituality & Religion
- Radio News Archive
- Flickr Commons
- Occupy Wall Street Flickr
- NASA Images
- Solar System Collection
- Ames Research Center
- All Software
- Old School Emulation
- MS-DOS Games
- Historical Software
- Classic PC Games
- Software Library
- Kodi Archive and Support File
- Vintage Software
- CD-ROM Software
- CD-ROM Software Library
- Software Sites
- Tucows Software Library
- Shareware CD-ROMs
- Software Capsules Compilation
- CD-ROM Images
- ZX Spectrum
- DOOM Level CD

- Smithsonian Libraries
- FEDLINK (US)
- Lincoln Collection
- American Libraries
- Canadian Libraries
- Universal Library
- Project Gutenberg
- Children's Library
- Biodiversity Heritage Library
- Books by Language
- Additional Collections
- Prelinger Archives
- Democracy Now!
- Occupy Wall Street
- TV NSA Clip Library
- Animation & Cartoons
- Arts & Music
- Computers & Technology
- Cultural & Academic Films
- Ephemeral Films
- Sports Videos
- Videogame Videos
- Youth Media
Search the history of over 797 billion web pages on the Internet.
Mobile Apps
- Wayback Machine (iOS)
- Wayback Machine (Android)
Browser Extensions
Archive-it subscription.
- Explore the Collections
- Build Collections
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
- Donate Donate icon An illustration of a heart shape
Java, Java, Java Object-Oriented Problem Solving
Item preview, share or embed this item, flag this item for.
- Graphic Violence
- Explicit Sexual Content
- Hate Speech
- Misinformation/Disinformation
- Marketing/Phishing/Advertising
- Misleading/Inaccurate/Missing Metadata

plus-circle Add Review comment Reviews
19,985 Views
3 Favorites
DOWNLOAD OPTIONS
For print-disabled users
IN COLLECTIONS
Uploaded by jedboom01 on July 25, 2012
SIMILAR ITEMS (based on metadata)
- Title Java, Java, Java: Object-Oriented Problem Solving
- Author(s) R. Morelli and R. Walde
- Publisher: Prentice Hall, 3 edition (2006); eBook (Creative Commons edition, Trinity College, June 25, 2017)
- License(s): CC BY 3.0 , CC BY 4.0
- Paperback 862 pages
- eBook PDF (865 page, 6.3 MB), ePub, Daisy, Kindle, etc.
- Language: English
- ISBN-10: 0131474340
- ISBN-13: 978-0131474345
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:
- Computers, Objects, and Java
- Java Program Design and Development
- Objects: Defining, Creating, and Using
- Methods: Communicating with Objects
- Input/Output: Designing the User Interface
- Java Data and Operators
- Control Structures
- Strings and String Processing
- Inheritance and Polymorphism
- Arrays and Array Processing
- Exceptions: When Things Go Wrong
- Files and Streams
- Recursive Problem Solving
- Graphical User Interfaces
- Threads and Concurrent Programming
- Sockets and Networking
- Data Structures: Lists, Stacks, and Queues
The third edition retains many of the features of the first two editions, including:
- Early Introduction of Objects
- Emphasis on Object Oriented Design (OOD)
- Unified Modeling Language (UML) Diagrams
- Self-study Exercises with Answers
- Programming, Debugging, and Design Tips.
- From the Java Library Sections
- Object-Oriented Design Sections
- End-of-Chapter Exercises
- Companion Web Site, with Power Points and other Resources
- Amazon (Object Oriented Programming with JAVA)
- Introduction to Java, Basic Java
- Object-Oriented Analysis, Design, and Programming (OOA/OOD/OOP)
- Computer Programming
- Algorithms and Data Structures
- Java Programming and Java EE (J2EE)
- Java, Java, Java: Object-Oriented Problem Solving (R. Morelli and R. Walde)
- The Mirror Site (1) - PDF (865 page, 6.3 MB), ePub, Kindle, etc.
- Object Oriented Programming with Java (David J. Eck, et al)
- Object Oriented Programming in Java (Rick Halterman)
- Introduction to Programming in Java: An Interdisciplinary Approach
- IT Research Library
- Books by O'Reilly®
- Pro Certificates Studies
- Careers and Job Interviews
- Project Management
- Search Engines
- Developer Tools
- Bargin Computer Books
- Free IT Magazines
- About This Site

- Try the new Google Books
- Advanced Book Search
- Barnes&Noble.com
- Books-A-Million
- Find in a library
- All sellers »

Get Textbooks on Google Play
Rent and save from the world's largest eBookstore. Read, highlight, and take notes, across web, tablet, and phone.
Go to Google Play Now »
From inside the book
What people are saying - write a review, other editions - view all, common terms and phrases, about the author (2003).
Ralph A. Morelli is an Associate Professor and Chair of the Computer Science Department at Trinity College in Hartford, CT. He has written and co-authored books and articles on expert systems, artificial intelligence, the Web and educational software. He is the membership chair of the Northeast Region of the Small College Computing Conference, as well as a member of the Association for Computing Machinery and Computer Professionals for Social Responsibility. He is a recipient of two National Science Foundation Research Opportunity Awards.
Bibliographic information

Popular Uses
- Real Estate
- Fashion & Beauty
- Retail & Wholesale
- Featured Examples
- Embed Examples
- Learning Center
- Presentation
- Try for Free
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!
Java, Java, Java Object-Oriented Problem Solving Third Edition R. Morelli and R. Walde Trinity College Hartford, CT June 25, 2017
This work is licensed under a Creative Commons Attribution 4.0 International License (CC BY 4.0). This book was previously published by Pearson Education, Inc.
Preface to the Open Source Edition Java, Java, Java, 3e was previously published by Pearson Education, Inc. The first edition (2000) and the second edition (2003) were published by Prentice-Hall. In 2010 Pearson Education, Inc. reassigned the copyright to the authors, and we are happy now to be able to make the book available under an open source license. This PDF edition of the book is available under a Creative Commons Attribution 4.0 International License, which allows the book to be used, modified, and shared with attribution: (https://creativecommons.org/licenses/by/4.0/). – Ralph Morelli and Ralph Walde – Hartford, CT – December 30, 2016 i
Preface to the Third Edition 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: • Early Introduction of Objects • Emphasis on Object Oriented Design (OOD) • Unified Modeling Language (UML) Diagrams • Self-study Exercises with Answers • Programming, Debugging, and Design Tips. • From the Java Library Sections • Object-Oriented Design Sections • End-of-Chapter Exercises • Companion Web Site, with Power Points and other Resources 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. What’s New in the Third Edition The third edition has the following substantive changes: • Although the book retains its emphasis on a “running example” that is revisited in several chapters, the CyberPet examples have been replaced with a collection of games and puzzle examples. The CyberPet examples from earlier editions will be available on the Companion Web Site. iii
iv Table 1: Table of Contents for the Third Edition. Chapter Topic Chapter 0 Computers, Objects, and Java (revised) Chapter 1 Java Program Design and Development Chapter 2 Objects: Defining, Creating, and Using Chapter 3 Methods: Communicating with Objects (revised) Chapter 4 Input/Output: Designing the User Interface (new) Chapter 5 Java Data and Operators Chapter 6 Control Structures Chapter 7 Strings and String Processing Chapter 8 Inheritance and Polymorphism (new) Chapter 9 Arrays and Array Processing Chapter 10 Exceptions: When Things Go Wrong Chapter 11 Files and Streams Chapter 12 Recursive Problem Solving Chapter 13 Graphical User Interfaces Chapter 14 Threads and Concurrent Programming Chapter 15 Sockets and Networking (expanded) Chapter 16 Data Structures: Lists, Stacks, and Queues (revised and expanded) • Chapters 0 (Computers, Objects, and Java) and 1 (Java Program Design and Development) have been substantially reorganized and rewritten. The new presentation is designed to reduce the pace with which new concepts are introduced. The treatment of objectoriented (OO) and UML concepts has also been simplified, and some of the more challenging OO topics, such as polymorphism, have been moved to a new Chapter 8. • The new Java 1.5 Scanner class is introduced in Chapter 2 and is used to perform simple input operations. • Chapter 4 (Input/Output: Designing the User Interface) has been completely written. Rather than relying primarily on applet interfaces, as in the second edition, this new chapter provides independent introductions to both a command-line interface and a graphical user interface (GUI). Instructors can choose the type of interface that best suits their teaching style. The command-line interface is based on the BufferedReader class and is used throughout the rest of the text. The GUI is designed to work with either graphical applications or applets. Both approaches are carefully presented to highlight the fundamentals of user-interface design. The chapter concludes with an optional section that introduces file I/O using the new Scanner class. • Much of the discussion of inheritance and polymorphism, which was previously woven through the first five chapters in the second edition, has been integrated into a new Chapter 8. • An optional graphics track is woven throughout the text. Beginning with simple examples in Chapters 1 and 2, this track also includes
. One problem with this approach was that many students failed to get the big picture. They could understand loops, if-else constructs, and arithmetic expressions, but they had difficulty decomposing a programming problem into a well-organized Java program. Also, it seemed that this procedural approach failed to take advantage of the strengths of Java’s object orientation. Why teach an object-oriented language if you’re going to treat it like C or Pascal? I was reminded of a similar situation that existed when Pascal was the predominant CS1 language. Back then the main hurdle for beginners was procedural abstraction — learning the basic mechanisms of procedure call
it is easy to “work around” or completely ignore OO features and treat the language like C. In Java there are good opportunities for motivating the discussion of object orientation. For example, it’s almost impossible to discuss GUI-based Java applications without discussing inheritance and polymorphism. Thus rather than using contrived examples of OO concepts, instructors can use some of Java’s basic features — the class library, Swing and GUI components — to motivate these discussions in a natural way. Organization of the Text The book is still organized into three main parts. Part I (Chapters 0-4) introduces the basic concepts of object orientation and the basic features of the Java language. Part II (Chapters 5-9) focuses on remaining language elements, including data types, control structures, string and array processing, and inheritance and polymorphism. Part III (Chapters 10-16) covers advanced topics, including exceptions, file I/O, recursion, GUIs, threads and concurrent programming, sockets and networking, data structures, servlets, and Java Server Pages. The first two parts make up the topics that are typically covered in an introductory CS1 course. The chapters in Part III are self-contained and can be selectively added to the end of a CS1 course if time permits. The first part (Chapters 0 through 4) introduces the basic concepts of object orientation, including objects, classes, methods, parameter passing, information hiding, and a little taste of inheritance, and polymorphism. The primary focus in these chapters is on introducing the basic idea that an object-oriented program is a collection of objects that communicate and cooperate with each other to solve problems. Java language elements are introduced as needed to reinforce this idea. Students are given the basic building blocks for constructing Java programs from scratch. Although the programs in the first few chapters have limited functionality in terms of control structures and data types, the priority is placed
vii Table 2: A one-semester course. Weeks Topics Chapters 1 Object Orientation, UML Chapter 0 Program Design and Development Chapter 1 2-3 Objects and Class Definitions Chapter 2 Methods and Parameters Chapter 3 Selection structure (if-else) 4 User Interfaces and I/O Chapter 4 5 Data Types and Operators Chapter 5 6–7 Control Structures (Loops) Chapter 6 Structured Programming 8 String Processing (loops) Chapter 7 9 Inheritance and Polymorphism Chapter 8 10 Array Processing Chapter 9 11 Recursion Chapter 12 12 Advanced Topic (Exceptions) Chapter 10 13 Advanced Topic (GUIs) Chapter 11 Advanced Topic (Threads) Chapter 15 on how objects are constructed and how they interact with each other through method calls and parameter passing. The second part (Chapters 5 through 9) focuses on the remaining language elements, including data types and operators (Chapter 5), control structures (Chapter 6), strings (Chapter 7), and arrays (Chapter 9). It also provides thorough coverage of inheritance and polymorphism, the primary mechanisms of object orientation: (Chapter 8). Part three (Chapters 10 through 16) covers a variety of advanced topics (Table 1). Topics from these chapters can be used selectively depending on instructor and student interest. Throughout the book, key concepts are introduced through simple, easy-to-grasp examples. Many of the concepts are used to create a set of games, which are used as a running example throughout the text. Our pedagogical approach focuses on design. Rather than starting of with language details, programming examples are carefully developed with an emphasis on the principles of object-oriented design. Table2 provides an example syllabus from our one-semester CS1 course. Our semester is 13 weeks (plus one reading week during which classes do not meet). We pick and choose from among the advanced topics during the last two weeks of the course, depending on the interests and skill levels of the students. Ralph Morelli June 25, 2017
Contents 0 Computers, Objects, and Java 1 0.1 Welcome . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 0.2 What Is a Computer? . . . . . . . . . . . . . . . . . . . . . . . 2 0.3 Networks, the Internet and the World Wide Web . . . . . . . 4 0.4 Why Study Programming? . . . . . . . . . . . . . . . . . . . . 6 0.5 Programming Languages . . . . . . . . . . . . . . . . . . . . 7 0.6 Why Java? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 0.7 What Is Object-Oriented Programming? . . . . . . . . . . . . 11 1 Java Program Design and Development 23 1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 1.2 Designing Good Programs . . . . . . . . . . . . . . . . . . . . 24 1.3 Designing a Riddle Program . . . . . . . . . . . . . . . . . . . 26 1.4 Java Language Elements . . . . . . . . . . . . . . . . . . . . . 34 1.5 Editing, Compiling, and Running a Java Program . . . . . . 48 1.6 From the Java Library: System and PrintStream . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 2 Objects: Using, Creating, and Defining 61 2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 2.2 Using String Objects . . . . . . . . . . . . . . . . . . . . . . 62 2.3 Drawing Shapes with a Graphics Object (Optional) . . . . 66 2.4 Class Definition . . . . . . . . . . . . . . . . . . . . . . . . . . 69 2.5 CASE STUDY: Simulating a Two-Person Game . . . . . . . . 76 2.6 From the Java Library: java.util.Scanner. . . . . . . . . 90 3 Methods: Communicating with Objects 101 3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 3.2 Passing Information to an Object . . . . . . . . . . . . . . . . 102 3.3 Constructor Methods . . . . . . . . . . . . . . . . . . . . . . . 109 3.4 Retrieving Information from an Object . . . . . . . . . . . . . 114 3.5 Passing a Value and Passing a Reference . . . . . . . . . . . . 118 3.6 Flow of Control: Control Structures . . . . . . . . . . . . . . . 121 3.7 Testing an Improved OneRowNim . . . . . . . . . . . . . . . . 130 3.8 From the Java Library java.lang.Object . . . . . . . . . 135 3.9 Object-Oriented Design: Inheritance and Polymorphism . . 136 3.10 Drawing Lines and Defining Graphical Methods (Optional) 138 4 Input/Output: Designing the User Interface 149 4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 ix
Action . . . . . . . . . . 237 6 Control Structures 241 6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 6.2 Flow of Control: Repetition Structures . . . . . . . . . . . . . 242 6.3 Counting Loops . . . . . . . . . . . . . . . . . . . . . . . . . . 243 6.4 Example: Car Loan . . . . . . . . . . . . . . . . . . . . . . . . 252 6.5 Graphics Example: Drawing a Checkerboard . . . . . . . . . 255 6.6 Conditional Loops . . . . . . . . . . . . . . . . . . . . . . . . 259 6.7 Example: Computing Averages . . . . . . . . . . . . . . . . . 266 6.8 Example: Data Validation . . . . . . . . . . . . . . . . . . . . 270 6.9 Principles of Loop Design . . . . . . . . . . . . . . . . . . . . 270 6.10 The switch Multiway Selection Structure . . . . . . . . . . . 273 6.11 OBJECT-ORIENTED DESIGN: Structured Programming . . . . . . . . . . . . . . . . . . . . . 277 7 Strings and String Processing 297 7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298 7.2 String Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298 7.3 Finding Things Within a String . . . . . . . . . . . . . . . . . 304 7.4 Example: Keyword Search . . . . . . . . . . . . . . . . . . . . 306 7.5 From the Java Library: java.lang.StringBuffer . . . . . . . . . 308 7.6 Retrieving Parts of Strings . . . . . . . . . . . . . . . . . . . . 310 7.7 Example: Processing Names and Passwords . . . . . . . . . 312 7.8 Processing Each Character in a String . . . . . . . . . . . . 313 7.9 Comparing Strings . . . . . . . . . . . . . . . . . . . . . . . . 317 7.10 From the Java Library: java.util.StringTokenizer . . . . . . . . . . . . . . . . . . . . . 323 7.11 Handling Text in a Graphics Context (Optional) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 8 Inheritance and Polymorphism 337 8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 8.2 Java’s Inheritance Mechanism . . . . . . . . . . . . . . . . . . 338
CONTENTS xi 8.3 Abstract Classes, Interfaces, and Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . 347 8.4 Example: A Toggle Button . . . . . . . . . . . . . . . . . . . . 353 8.5 Example: The Cipher Class Hierarchy . . . . . . . . . . . . . 357 8.6 Case Study: A Two Player Game Hierarchy . . . . . . . . . . 363 8.7 Principles Of Object-Oriented Design . . . . . . . . . . . . . 384 9 Arrays and Array Processing 393 9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394 9.2 One-Dimensional Arrays . . . . . . . . . . . . . . . . . . . . . 394 9.3 Simple Array Examples . . . . . . . . . . . . . . . . . . . . . 401 9.4 Example: Counting Frequencies of Letters . . . . . . . . . . . 403 9.5 Array Algorithms: Sorting . . . . . . . . . . . . . . . . . . . . 406 9.6 Array Algorithms: Searching . . . . . . . . . . . . . . . . . . 414 9.7 Two-Dimensional Arrays . . . . . . . . . . . . . . . . . . . . . 417 9.8 Multidimensional Arrays (Optional) . . . . . . . . . . . . . . 426 9.9 OBJECT-ORIENTED DESIGN: Polymorphic Sorting (Optional) . . . . . . . . . . . . . . . . . 428 9.10 From the Java Library: java.util.Vector . . . . . . . . . . . . . 430 9.11 Case Study: An N-Player Computer Game . . . . . . . . . . 431 9.12 A GUI-Based Game (Optional Graphics) . . . . . . . . . . . . 437 10 Exceptions: When Things Go Wrong 459 10.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460 10.2 Handling Exceptional Conditions . . . . . . . . . . . . . . . . 460 10.3 Java’s Exception Hierarchy . . . . . . . . . . . . . . . . . . . 462 10.4 Handling Exceptions Within a Program . . . . . . . . . . . . 466 10.5 Error Handling and Robust Program Design . . . . . . . . . . . . . . . . . . . . . . . . . . 477 10.6 Creating and Throwing Your Own Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487 10.7 From the Java Library: JOptionPane . . . . . . . . . . . . . 489 11 Files and Streams: Input/Output Techniques 499 11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500 11.2 Streams and Files . . . . . . . . . . . . . . . . . . . . . . . . . 500 11.3 CASE STUDY: Reading and Writing Text Files . . . . . . . . 505 11.4 The File Class . . . . . . . . . . . . . . . . . . . . . . . . . . 518 11.5 Example: Reading and Writing Binary Files . . . . . . . . . . 521 11.6 Object Serialization: Reading and Writing Objects . . . . . . 530 11.7 From the Java Library javax.swing.JFileChooser . . . . . . . . . . . . . . . . 535 11.8 Using File Data in Programs . . . . . . . . . . . . . . . . . . . 536 12 Recursive Problem Solving 545 12.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546 12.2 Recursive Definition . . . . . . . . . . . . . . . . . . . . . . . 549 12.3 Recursive String Methods . . . . . . . . . . . . . . . . . . . . 551 12.4 Recursive Array Processing . . . . . . . . . . . . . . . . . . . 563 12.5 Example: Drawing (Recursive) Fractals . . . . . . . . . . . . 569
xii CONTENTS 12.6 OBJECT-ORIENTED DESIGN: Tail Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . 573 12.7 OBJECT-ORIENTED DESIGN: Recursion or Iteration? . . . . . . . . . . . . . . . . . . . . . . 574 12.8 From the Java Library: javax.swing.JComboBox . . . . . . . . . . . . . . . . . . . . . 577 13 Graphical User Interfaces 591 13.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592 13.2 Java GUIs: From AWT to Swing . . . . . . . . . . . . . . . . . 592 13.3 The Swing Component Set . . . . . . . . . . . . . . . . . . . . 595 13.4 OBJECT-ORIENTED DESIGN: Model-View-Controller Architecture . . . . . . . . . . . . . . 596 13.5 The Java Event Model . . . . . . . . . . . . . . . . . . . . . . 598 13.6 CASE STUDY: Designing a Basic GUI . . . . . . . . . . . . . 602 13.7 Containers and Layout Managers . . . . . . . . . . . . . . . . 614 13.8 Checkboxes, Radio Buttons, and Borders . . . . . . . . . . . 620 13.9 Menus and Scroll Panes . . . . . . . . . . . . . . . . . . . . . 629 14 Threads and Concurrent Programming 643 14.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644 14.2 What Is a Thread? . . . . . . . . . . . . . . . . . . . . . . . . . 644 14.3 From the Java Library: java.lang.Thread . . . . . . . . . 648 14.4 Thread States and Life Cycle . . . . . . . . . . . . . . . . . . . 654 14.5 Using Threads to Improve Interface Responsiveness . . . . . . . . . . . . . . . . 656 14.6 CASE STUDY: Cooperating Threads . . . . . . . . . . . . . . 664 14.7 CASE STUDY: The Game of Pong . . . . . . . . . . . . . . . . 679 15 Sockets and Networking 693 15.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694 15.2 An Overview of Networks . . . . . . . . . . . . . . . . . . . . 694 15.3 Using Multimedia Network Resources for a Graphical Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700 15.4 From the Java Library: java.net.URL . . . . . . . . . . . . 701 15.5 The Slide Show Program . . . . . . . . . . . . . . . . . . . . . 704 15.6 Adding Text Network Resources for an Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . 708 15.7 Client/Server Communication via Sockets . . . . . . . . . . 719 15.8 CASE STUDY: Generic Client/Server Classes . . . . . . . . . 724 15.9 Playing One Row Nim Over the Network . . . . . . . . . . . 732 15.10Java Network Security Restrictions . . . . . . . . . . . . . . . 741 15.11Java Servlets and Java Server Pages . . . . . . . . . . . . . . . 742 16 Data Structures: Lists, Stacks, and Queues 757 16.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758 16.2 The Linked List Data Structure . . . . . . . . . . . . . . . . . 758 16.3 OBJECT-ORIENTED DESIGN: The List Abstract Data Type (ADT) . . . . . . . . . . . . . . . 770 16.4 The Stack ADT . . . . . . . . . . . . . . . . . . . . . . . . . . . 776 16.5 The Queue ADT . . . . . . . . . . . . . . . . . . . . . . . . . . 778
CONTENTS xiii 16.6 From the Java Library: The Java Collections Framework and Generic Types . . . . . . . . . . . . . . . . . . . . . . . . 782 16.7 Using the Set and Map Interfaces . . . . . . . . . . . . . . . 785 16.8 The Binary Search Tree Data Structure . . . . . . . . . . . . . 789 A Coding Conventions 801 B The Java Development Kit 809 C The ASCII and Unicode Character Sets 819 D Java Keywords 821 E Operator Precedence Hierarchy 823 F Java Inner Classes 825 G Java Autoboxing and Enumeration 831 H Java and UML Resources 837
xiv CONTENTS
OBJECTIVES After studying this chapter, you will • Understand basic computer terminology that will be used throughout the book. • Become familiar with the notion of programming. • Understand why Java is a good introductory programming language. • Become familiar with Java objects and classes. • Know some of the principles of the object-oriented programming approach. OUTLINE 0.1 Welcome 0.2 What Is a Computer? Special Topic: Processors Then and Now 0.3 Networks, the Internet and the World Wide Web 0.4 Why Study Programming? 0.5 Programming Languages 0.6 Why Java? 0.7 What Is Object-Oriented Programming? Chapter Summary Exercises Chapter 0 Computers, Objects, and Java 1
2 CHAPTER 0 • Computers, Objects, and Java 0.1 Welcome Welcome to Java, Java, Java, a book that introduces you to object-oriented programming using the Java language. When considering the purpose of this text, three important questions might come to mind: Why study programming? Why study Java? What is object-oriented programming? This chapter will address these questions. First, we provide a brief introduction to computers and the Internet and World Wide Web (WWW). Then, we address why someone would study programming and we examine types of programming languages. We introduce the Java programming language and conclude the chapter by exploring object-oriented programming principles and how Java is an object-oriented programming language. 0.2 What Is a Computer? A computer is a machine that performs calculations and processes information. A computer works under the control of a computer program, a set of instructions that tell a computer what to do. Hardware refers to the electronic and mechanical components of a computer. Software refers to the programs that control the hardware. A general-purpose computer of the sort that we will be programming can store many different programs in its memory. That is what gives it the ability to perform a wide variety of functions, from word processing to browsing the Internet. This is in contrast to a special-purpose computer, such as the one that resides in your microwave oven or the one that controls your digital watch or calculator. These types of computers contain control programs that are fixed and cannot be changed. A computer’s hardware is organized into several main subsystems or components (Fig. 1). Figure 1: A diagram of the main functional components in a computer system. The arrows indicate the flow of information between various components. Secondary Storage Main Memory Input Devices Keyboard Mouse Optical Scanner Output Devices Printer Monitor Audio Speakers Central Processing Unit (CPU) Disk Drive CD-ROM DVD • Output devices provide a means by which information held in the computer can be displayed in some understandable or usable form. Common output devices include printers, monitors, and audio speakers.
SECTION 0.2 • What Is a Computer? 3 • Input devices bring data and information into the computer. Some of the more common input devices are the keyboard, mouse, microphone, and scanner. • Primary memory or main memory of a computer is used to store both data and programs. This type of memory, which is often called RAM, short for Random Access Memory, is built entirely out of electronic components—integrated circuit chips—which makes it extremely fast. A computer’s main memory is volatile, which means that any information stored in it is lost when the computer’s power is turned off. In a sense, main memory acts as the computer’s scratch pad, storing both programs and data temporarily while a program is running. • Secondary storage devices are used for long-term or permanent storage of relatively large amounts of information. These devices include hard drives or magnetic disks, compact disks (CDs), digital video disks (DVDs), and magnetic tapes. All of these devices are non-volatile, meaning that they retain information when the computer’s power is turned off. Compared to a computer’s primary memory, these devices are relatively slow. • The central processing unit (CPU) is the computer’s main engine. The CPU is the computer’s microprocessor, such as the Intel Pentium processor, which serves as the foundation for most Windows PCs, or the Power-PC processor, which serves as the foundation for Macintosh computers. The CPU is designed to perform the fetch-execute cycle, Fetch-execute cycle whereby it repeatedly gets the next machine instruction from memory and executes it. Under the direction of computer programs (software), the CPU issues signals that control the other components that make up the computer system. One portion of the CPU, known as the arithmeticlogic unit (ALU), performs all calculations, such as addition and subtraction, and all logical comparisons, such as when one piece of data is compared to another to determine if they are equal. There are two main types of software: • Application software refers to programs designed to provide a particular task or service, such as word processors, computer games, spreadsheet programs, and Web browsers. • System software includes programs that perform the basic operations that make a computer usable. For example, an important piece of system software is the operating system, which contains programs that manage the data stored on the computer’s disks. An operating system assists application software in performing tasks that are considered primitive or low-level, such as managing the computer’s memory and its input and output devices. Another important thing that the operating system does is to serve as an interface between the user and the hardware. The operating system determines how the user will interact with the system, or conversely, how the system will look and feel to the user. For example, in command-line systems, such as Unix and DOS (short for Disk Operating System), a program is run by typing its name on the command line. By contrast, in
4 CHAPTER 0 • Computers, Objects, and Java graphically based systems, such as Windows and Macintosh, a program is run by clicking on its icon with the mouse. Thus, this “point-and-click” interface has a totally different “look and feel” but does the same thing. Special Topic: Processors Then and Now To give you some idea of how rapidly computer hardware technology has advanced, let’s compare the first digital processor with one of today’s models. The ENIAC (which stood for Electronic Numerical Integrator and Calculator) was developed in 1946 at the University of Pennsylvania primarily for calculating ballistic trajectories for the U.S. Army. ENIAC occupied more than 640 square feet of floor space and weighed nearly 30 tons. Instead of the integrated circuits or chip technology used in today’s computers, ENIAC’s digital technology was based on over 17,000 vacuum tubes. ENIAC, which could perform around 300 multiplications per second, ran more than 500 times faster than other computing machines of that day and age. To program the ENIAC, you would have to manipulate hundreds of cables and switches. It took two or three days for a team of several programmers, most of whom were young women, to set up a single program that would then run for a few seconds. One of today’s most advanced and powerful processors for desktop computers is Intel’s Pentium IV processor. This chip contains 42 million transistors and runs at speeds over 3 GHz (3 gigahertz or 3 billion cycles per second). The Pentium processor is small enough to fit in a space the size of your pinky finger’s fingernail. Despite its size, it executes millions of instructions per second, thereby enabling it to support a huge range of multimedia applications, including three-dimensional graphics, streaming audio and video, and speech recognition applications. To write programs for the Pentium, you can choose from a wide range of high-level programming languages, including the Java language. 0.3 Networks, the Internet and the World Wide Web Most personal computers contain software that enables them to be connected to various-sized networks of computers. Networks allow many individual users to share costly computer resources, such as a high-speed printer or a large disk drive or application server that is used to store and distribute both data and programs to the computers on the network. Networks can range in size from local area networks (LANs), which connect computers and peripherals over a relatively small area, such as within a lab or a building, through wide area networks (WANs), which can span large geographic areas, such as cities and nations. Client/server computing Application servers are just one example of client/server computing, a computing approach made possible by networks. According to this approach, certain computers on the network are set up as servers, which provide certain well-defined services to client computers. For example, one computer in a network may be set up as the email server, with the responsi-
SECTION 0.3 • Networks, the Internet and the World Wide Web 5 bility of sending, receiving, and storing mail for all users on the network. To access their email on the email server, individual users employ client application software that resides on their desktop computers, such as Outlook Express or Eudora or Pine. Similarly, another server may be set up as a Web server, with the responsibility of storing and serving up Web pages for all the users on the network. Users can run Web browsers, another type of client software, to access Web pages on the server. Java is particularly well suited for these types of networked or distributed applications, where part of the application software resides on a server and part resides on the client computer. The Internet (with a capital I) is a network of networks whose geographical area covers the entire globe. The World Wide Web (WWW) is another example of distributed, client/server computing. The WWW is not a separate physical network. Rather it is a subset of the Internet that uses the HyperText Transfer Protocol (HTTP). A protocol is a set of rules and conventions that govern how communication takes place between two computers. HTTP is a multimedia protocol, which means that it supports the transmission of text, graphics, sound, and other forms of information. Certain computers within a network run special software that enables them to play the role of HTTP (or Web) servers. They store Web documents and are capable of handling requests for documents from client browser applications. The servers and clients can be located anywhere on the Internet. The documents stored on Web servers are encoded in a special textbased language known as HyperText Markup Language, or HTML. Web browsers, such as Netscape’s Navigator and Microsoft’s Internet Explorer, are designed to interpret documents coded in this language. The language itself is very simple. Its basic elements are known as tags, which consist of certain keywords or other text contained within angle brackets, . For example, if you wanted to italicize text on a Web page, you would enclose it between the and tags. Thus, the following HTML code ☛ ✟ $ $ I t a l i c fon t $ $ can be used f o r $ $emphasis$ $ . ✡ ✠ would be displayed by the Web browser as Italic font can be used for emphasis. When you use a Web browser to surf the Internet, you repeatedly instruct your browser to go to a certain location and retrieve a page that is encoded in HTML. For example, if you typed the following URL (Uniform Resource Locator) ☛ ✟ h t tp : //www. p r e n h all . com/m o r elli/index . html ✡ ✠ into your browser, the browser would send a message to the Web server www located in the prenhall.com domain—the prenhall portion of this address specifies Prentice Hall and the com portion specifies the commercial domain of the Internet—requesting that the document named index.html in the morelli directory be retrieved and sent back to your
6 CHAPTER 0 • Computers, Objects, and Java Figure 2: WWW: The client’s browser requests a page from a Web server. When the HTML document is returned, it is interpreted and displayed by the browser. Display Internet Send a document Request a document HTML document Server Client HTTP software Text yyyy yyyy yyyy yyyy yy yy Browser software computer (Fig. 2). The beauty of the Web is that it is possible to embed text, sound, video, and graphics within an HTML document, making it possible to download a wide range of multimedia resources through this (relatively) simple mechanism. The Web has begun to change business, entertainment, commerce, and education. The fact that it is possible to download computer games and other application software from the Web is changing the way software and other digital products are purchased and distributed. Similarly, as noted earlier, many businesses have begun to organize their information systems into intranets—private networks that implement the HTTP protocol. Currently, one of the biggest areas of development on the Web is commerce. As consumers become more comfortable that credit-card information can be securely transmitted over the Web (as it can over a telephone), the Web will explode as a marketing medium as powerful, perhaps, as television is today. Because Java has been designed to support secure, distributed, networked applications, it is ideally suited to be used as the language for these types of applications. 0.4 Why Study Programming? A computer program is a set of instructions that directs the computer’s behavior. Computer programming is the art and science of designing and writing programs. Years ago it was widely believed that entrance into the computer age would require practically everyone to learn how to program. But this did not prove to be true. Today’s computers come with so much easy-to-use software that knowing how to use a computer no longer requires programming skills. Another reason to study programming might be to enter into a career as a computer scientist. However, although programming is one of its primary tools, computer science is a broad and varied discipline, which ranges from engineering subjects, such as processor design, to mathematical subjects, such as performance analysis. There are many computer scientists who do little or no programming as part of their everyday work. If you plan to major or minor in computer science, you will certainly learn to program, but good careers in the computing field are available to programmers and nonprogrammers alike.
b ) / 2 ✡ ✠ The problem is that computers cannot directly understand such expressions. In order for a computer to run a program, the program must first be translated into the computer’s machine language, which is the language understood by its CPU or microprocessor. Each type of microprocessor has its own particular machine language. That’s why when you buy software it runs either on a Macintosh, which uses the Power-PC chip, or on a Windows machine, which uses the Pentium chip, but not on both. When a Platform independence program can run on just one type of chip, it is known as platform dependent. In general, machine languages are based on the binary code, a twovalued system that is well suited for electronic devices. In a binary representation scheme, everything is represented as a sequence of 1’s and 0’s, which corresponds closely to the computer’s electronic “on” and “off” states. For example, in binary code, the number 13 would be repre-
directly. Source code translators come in two varieties. An interpreter translates a single line of source code directly into machine language and executes the code before going on to the next line of source code. A compiler translates the entire source code program into executable object code, which means that the object code can then be run directly without further translation. There are advantages and disadvantages to both approaches. Interpreted programs generally run less efficiently than compiled programs,
, and Pascal are compiled. As we will see in the next section, Java programs use both compilation and interpretation in their translation process. 0.6 Why Java? Originally named “Oak” after a tree outside the office of its developer, James Goslin, Java is a relatively young programming language. It was initially designed by Sun Microsystems in 1991 as a language for embedding programs into electronic consumer devices, such as microwave ovens and home security systems. However, the tremendous popularity of the Internet and the World Wide Web (WWW) led Sun to recast Java as a language for embedding programs into Web-based applications. As you recall, the Internet is a global computer network, and the WWW is that portion of the network that provides multimedia access to a vast range of information. Java has become one of the most important languages for Web and Internet applications. Java has also generated significant interest in the business community, where it is has proved to have tremendous commercial potential. In addition to being a useful tool for helping businesses to promote their products and services over the Internet, Java is also a good language for distributing software and providing services to employees and clients on private corporate networks or intranets. Because of its original intended role as a language for programming microprocessors embedded in consumer appliances, Java has been designed with a number of interesting features: • Java is object oriented. Object-oriented languages divide programs into separate modules, called objects, that encapsulate the program’s data and operations. Thus, object-oriented programming (OOP) and object-oriented design (OOD) refer to a particular way of organizing pro- Object-oriented Languages
language, in which object-oriented features were grafted onto the C language, Java was designed from scratch as an object-oriented language. • Java is robust, meaning that errors in Java programs don’t cause system crashes as often as errors in other programming languages. Certain features of the language enable many potential errors to be detected before a program is run. Platform independence • Java is platform independent. A platform, in this context, is just a particular kind of computer system, such as a Macintosh or Windows system. Java’s trademark is “Write once, run anywhere.” This means that a Java program can be run without changes on different kinds of computers. This is not true for other high-level programming languages. This portability – the ability to run on virtually any platform – is one reason that Java is well suited for WWW applications. • Java is a distributed language, which means that its programs can be designed to run on computer networks. In addition to the language itself, Java comes with an extensive collection of code libraries—software that has been designed to be used directly for particular types of applications—that make it particularly easy to build software systems for the Internet and the WWW. This is one of the reasons why Java is so well suited for supporting applications on corporate networks. • Java is a secure language. Designed to be used on networks, Java contains features that protect against untrusted code—code that might introduce a virus or corrupt your system in some way. For example, once they are downloaded into your browser, Web-based Java programs are prevented from reading and writing information from and to your desktop computer. Despite this list of attractive features, perhaps the best reason for choosing Java as an introductory programming language is its potential for bringing fun and excitement into learning how to program. There are few other languages in which a beginning programmer can write a computer game or a graphically based application that can be distributed on a Web page to just about any computer in the world. The simplicity of Java’s design and its easily accessible libraries bring such accomplishments within reach of the most novice programmers. For example, we will work on projects throughout the text that involve games and puzzles. We start out in Chapter 2 by designing very simple games that involve storing and retrieving data. As we learn more sophisticated programming techniques, we gradually build more complexity into the games and puzzles. For example, we learn how to create interactive, two-person games in Chapter 4. In Chapter 8, we develop some games and puzzles that are played on virtual game boards. Finally, in Chapter 14 we learn how to introduce games with multiple players on different computers. To get a look at where we are headed you might want to visit the authors’ companion Web site: ☛ ✟ h t tp : //www. c s . t r i n c o l l . edu/ ˜ram/ j j j / ✡ ✠
SECTION 0.7 • What Is Object-Oriented Programming? 11 0.7 What Is Object-Oriented Programming? Java is an object-oriented (OO) language, and this book takes an objectoriented approach to programming. So before beginning our discussion of Java, it is important that we introduce some of the underlying concepts involved in object-oriented programming. We need to talk about what an object is, how objects are grouped into classes, how classes are related to each other, and how objects use messages to interact with and communicate with each other. 0.7.1 Basic Object-Oriented Programming Metaphor: Interacting Objects A Java program, and any object-oriented program, is a collection of interacting objects that models a collection of real-world Figure 4: A model of a kitchen. objects. Think of the model that a kitchen designer might use to layout your new kitchen (Fig. 4). It will contain objects that represent the various kitchen appliances and cabinets. Each object in the model is a simplified version of the corresponding real object. For example, a rectangle might be used to represent the refrigerator. A kitchen model is mostly static. It doesn’t change. Once put into place, its various objects just stand there in a certain relation to each other. By contrast, a computer program is dynamic. It changes. It does things and performs certain actions. The objects in a computer program communicate with each other and they change over time. In this respect, the objects that make up our computer programs are very anthropomorphic, a big word that means “like people.” If we are eating together and I want you to pass me the salt, I say, “Please pass me the salt,” and you invariably comply. Similarly, when you (Student X) put your ATM card into an ATM machine, the ATM object asks the bank’s database object “Give me Student X’s bank account object” and the database invariably complies. If you tell the ATM you want to withdraw $100 dollars it tells your bank account object to deduct $100 from your current balance. And so it goes. Both you and your bank account are changed objects as a result of the transaction. 0.7.2 What is an Object? So what is an object? Just as in the real world, an object is any thing whatsoever. An object can be a physical thing, such as a Car, or a mental thing, such as an Idea. It can be a natural thing, such as an Animal, or an artificial, human-made thing, such as a ATM. A program that manages an ATM would involve BankAccounts and Customer objects. A chess program would involve a Board object and ChessPiece objects. Throughout this text, we will use the notation shown in Figure 5 to depict objects and to illustrate object-oriented concepts. The notation is known as the Unified Modeling Language, or UML for short, and it is a standard in the object-oriented programming community. As the diagram shows, an object is represented by a rectangle whose label consists of the object’s (optional) id and its type. An object’s id is the name by which it is referred to in the computer program. In this case we show a ATM object, who’s id is not given, and a ChessPiece object, named pawn1. An object’s label is always underlined.
12 CHAPTER 0 • Computers, Objects, and Java Figure 5: In UML, objects are represented by rectangles that are labeled with a two-part label of the form id:Type. The object’s label is always underlined. 0.7.3 Attributes and Values Just as with real objects, the objects in our programs have certain characteristic attributes. For example, an ATM object would have a current amount of cash that it could dispense. A ChessPiece object might have a pair of row and column attributes that specify its position on the chess board. Notice that an object’s attributes are themselves objects. The ATM’s cash attribute and the chess piece’s row and column attributes are Numbers. Figure 6 shows two ATM objects and their respective attributes. As you can see, an object’s attributes are listed in a second partition of the UML diagram. Notice that each attribute has a value. So the lobby:ATM has a $8650.0 in cash, while the drivethru:ATM has only $150.0 in cash. Figure 6: A second partition of an object diagram is used to display the object’s attributes and their values. We sometimes refer to the collection of an object’s attributes and values as its state. For example, the current state of the lobby:ATM is $8650.0 in cash. Of course, this is a gross simplification of an ATM’s state, which would also include many other attributes. But, hopefully, you see the point. 0.7.4 Actions and Messages In addition to their attributes, objects also have characteristic actions or behaviors. As we have already said, objects in programs are dynamic. They do things or have things done to them. In fact, programming in Java is largely a matter of getting objects to perform certain actions for us. For example, in a chess program the ChessPieces have the ability to moveTo() a new position on the chess board. Similarly, when a customer pushes the “Current Balance” button on an ATM machine, this is telling the ATM to report() the customer’s current bank balance. (Note how we use parentheses to distinguish actions from objects and attributes.) The actions that are associated with an object can be used to send messages to the objects and to retrieve information from objects. A message is the passing of information or data from one object to another. Figure 7 illustrates how this works. In UML, messages are represented by arrows.
SECTION 0.7 • What Is Object-Oriented Programming? 13 Figure 7: Messages in UML are represented by labeled arrows. In this example, we are telling a pawn to move from its current position to row 3 column 4. In this example, we are telling pawn1:ChessPiece to moveTo(3,4). The numbers 3 and 4 in this case are arguments that tell the pawn what square to move to. (A chess board has 8 rows and 8 columns and each square is identified by its row and column coordinates.) In general, an argument is a data value that specializes the content of a message in some way. In this example we are telling the pawn to move forward by 1 row. If we wanted the pawn to move forward by 2 rows, we would send the message moveTo(4,4). The diagram in Figure 8 depicts a sequence of messages representing an idealized ATM transaction. First, an ATM customer asks the ATM machine to report his current balance. The ATM machine in turn asks the customer’s bank account to report the customer’s balance. The ATM receives the value $528.52 from the bank account and passes it along to the customer. In this case, the message does not involve an argument. But it does involve a result. A result is information or data that is returned to the object that sent the message. Figure 8: This UML diagram illustrates an ATM transaction in which a customer asks the ATM machine for his current balance. The ATM gets this information from an object representing the customer’s bank account and passes it to the customer. Obviously, in order to respond to a message, an object has to know how to perform the action that is requested. The pawn has to know how to move to a designated square. The ATM has to know how to find out the customer’s current balance. Indeed, an object can only respond to messages that are associated with its characteristic actions and behaviors. You can’t tell an ATM to move forward 2 squares. And you can’t ask a chess piece to tell you your current bank balance. Responding to a message or performing an action sometimes causes a change in an object’s state. For example, after performing moveTo(3, 4), the pawn will be on a different square. Its position will have changed. On the other hand, some messages (or actions) leave the object’s state unchanged. Reporting the customer’s bank account balance doesn’t change the balance. 0.7.5 What is a Class? A class is a template for an object. A class encapsulates the attributes and actions that characterize a certain type of object. In an object-oriented program, classes serve as blueprints or templates for the objects that the pro-
14 CHAPTER 0 • Computers, Objects, and Java Figure 9: A UML diagram of the Rectangle class. gram uses. We say that an object is an instance of a class. A good analogy here is to think of a class as a cookie cutter and its objects, or instances, as individual cookies. Just as we use the cookie cutter to stamp out cookies of a certain type, in an object-oriented program, we use a definition of a class to create objects of a certain type. Writing an object-oriented program is largely a matter of designing classes and writing definitions for those classes in Java. Designing a class is a matter of specifying all of the attributes and behaviors that are characteristic of that type of object. For example, suppose we are writing a drawing program. One type of object we would need for our program is a rectangle. A Rectangle object has two fundamental attributes, a length and a width. Given these attributes, we can define characteristic rectangle actions, such as the ability to calculate its area and the ability to draw itself. Identifying an object’s attributes and actions is the kind of design activity that goes into developing an object-oriented program. Figure 9 shows a UML diagram of our Rectangle class. Like the symbol for an object, a UML class symbol has up to three partitions. Unlike the UML object symbol, the label for a UML class gives just the class’s name and it is not underlined. The second partition lists the class’s attributes and the third partition lists the classes actions. Our rectangle has four attributes. The first two, x and y, determine a rectangles position on a two-dimensional graph. The second two, length and width, determine a rectangle’s dimensions. Note that the attributes have no values. This is because the class represents a general type of rectangle. It specifies what all rectangles have in common, without representing any particular rectangle. Like a cookie cutter for a cookie, a class gives the general shape of an object. The content is not included. 0.7.6 Variables and Methods Up to this point we have been using the terms attribute and action to describe an object’s features. We will continue to use this terminology when talking in general about objects or when talking about an object or class represented by a UML diagram. However, when talking about a programming language, the more common way to describe an object’s features are to talk about its variables and methods. A variable, which corresponds to an attribute, is a named memory location that can store a certain type of value. You can think of a variable as a special container that can only hold objects of a certain type. For example, as Figure 9 shows, Rectangle’s length and width are
SECTION 0.7 • What Is Object-Oriented Programming? 15 variables that can store a certain type of numeric value known as an int. An int value is a whole number, such as 76 or -5. A method, which corresponds to an action or a behavior, is a named chunk of code that can be called upon or invoked to perform a certain pre-defined set of actions. For example, in our Rectangle object, the calculateArea() method can be called upon to calculate the rectangle’s area. It would do this, of course, by multiplying the rectangle’s length by its width. Similarly, the draw() method can be invoked to draw a picture of the rectangle. It would take the actions necessary to draw a rectangle on the console. 0.7.7 Instance versus Class Variables and Methods Variables and methods can be associated either with objects or their classes. An instance variable (or instance method) is a variable (or method) that belongs to an object. By contrast, a class variable (or class method) is a variable (or method) that is associated with the class itself. An example will help make this distinction clear. An instance variable will have different values for different instances. For example, individual Rectangles will have different values for their length, width, x, and y variables. So these are examples of instance variables. The calculateArea() method is an example of an instance method because it uses the instance’s current length and width values in its calculation. Similarly, the draw() method is an instance method, because it uses the object’s length and width to draw the object’s shape. An example of a class variable would be a variable in the Rectangle class that is used to keep track of how many individual Rectangles have been created. (Our drawing program might need this information to help manage its memory resources.) Suppose we name this variable nRectangles and suppose we add 1 to it each time a new Rectangle instance is created. An example of a method that is associated with the class is a special method known as a constructor. This is a method used to create an object. It is used to create an instance of a class. Calling a constructor to create an object is like pressing the cookie cutter into the cookie dough: the result is an individual cookie (object). Figure 10 illustrates these concepts. Note that class variables are underlined in the UML diagram. We have modified the Rectangle class to include its constructor method, which is named Rectangle(). Note that it takes four arguments, representing the values that we want to give as the rectangle’s x, y, length and width respectively. Note also how the Rectangle class’s nRectangles variable has a value of 2, representing that two Rectangle instances have been created. These are shown as members of the Rectangle class. It won’t be obvious to you at this point, but nRectangles is a value that has to be associated with the Rectangle class, not with its instances. To see this let’s imagine what happens when a new Rectangle instance is created. Figure 11 illustrates the process. When the Rectangle() constructor is invoked, its arguments (100, 50, 25, 10) are used by the Rectangle class to create a Rectangle object located at x=100, y=50 and with a length of 25 and width of 10. The constructor method also increases
16 CHAPTER 0 • Computers, Objects, and Java Figure 10: The Rectangle class and two of its instances. Note that the class variable, nRectangles, is underlined to distinguish it from length and width, the instance variables. the value of nRectangles by 1 as a way of keeping count of how many objects it has created. Figure 11: Constructing a Rectangle instance. 0.7.8 Class Hierarchy and Inheritance How are classes related to each other? In Java, and in any other objectoriented language, classes are organized in a class hierarchy. A class hierarchy is like an upside-down tree. At the very top of the hierarchy is the most general class. In Java, the most general class is the Object class. The classes below Object in the hierarchy are known as its subclasses. Since all of the objects we use in our programs belong to some class or other, this is like saying that all objects are Objects. Figure 12 illustrates the concept of a class hierarchy using the classes that we have described in this section. Notice that the Object class occurs at the top of the hierarchy. It is the most general class. It has features that are common to all Java objects. As you move down the hierarchy, the classes become more and more specialized. A Rectangle is an Object but it contains attributes – length and width – that are common to all rectangles but not to other objects in the hierarchy. For example, an ATM object does not necessarily have a length and a width. Notice that we have added a Square class to the hierarchy. A Square is a special type of Rectangle, namely one who’s length equals its width. To introduce some important terminology associated with this kind of Superclass and subclass hierarchy, we say that the Rectangle class is a subclass of the Object
SECTION 0.7 • What Is Object-Oriented Programming? 17 Figure 12: A hierarchy of Java classes. class. The Square class is a subclass of both Rectangle and Object. Classes that occur above a given class in the hierarchy are said to be its superclasses. Thus Rectangle class is superclass of the Square class. The Object class is also a superclass of Square. In general, we say that a subclass extends a superclass, meaning that it adds additional elements (attributes and/or methods) to those contained in its superclasses. We saw this in the case of the Square class. It adds the feature that its length and width are always equal. Another important concept associated with a class hierarchy is the no- Class inheritance tion of class inheritance, whereby a subclass inherits elements (attributes and/or methods) from its superclasses. To take an example from the natural world, think of the sort of inheritance that occurs between a horse and a mammal. A horse is a mammal. So horses inherit the characteristic of being warm blooded by virtue of also being mammals. (This is different from the kind of individual inheritance whereby you inherit your mother’s blue eyes and your father’s black hair.) To illustrate how inheritance works, lets go back to our chess program. There are several different types of ChessPieces. There are Pawns, and Knights, and Queens and Kings. Figure 13 illustrates the chess piece hierarchy. A pair of attributes that all chess pieces have in common is their row and column position on the chess board. Because all chess pieces have these attributes in common, they are located at the top of the ChessPiece hierarchy and inherited by all ChessPiece subclasses. Of course, the row and column attributes are given different values in each ChessPiece object. One of the actions that all chess pieces have in common is that they can moveTo() a given square on the chess board. But different types of chess pieces have different ways of moving. For example, a Bishop can only move along diagonals on the chess board, whereas a Rook can only move along a row or column on the chess board. So, clearly, we can’t describe a moveTo() method that will work for all ChessPieces. This is why we put the moveTo() method in all of the ChessPiece subclasses. The ChessPiece class also has a moveTo() method, but note that its name is italicized. This indicates that it cannot be completely defined at that level. Finally, note that in chess, the king has certain special attributes and actions. Thus only the king can be put in check. This means that the king is under attack and in danger of being captured, thereby ending the game. Similarly, only the king has the ability to castle. This is special move that
18 CHAPTER 0 • Computers, Objects, and Java Figure 13: The ChessPiece hierarchy. a king can make together with one of its rooks under certain conditions. Thus, the reason we show the inCheck attribute and castle() action in the King class is because these are characteristics that particular to Kings. In this way, a class hierarchy represents a specialization of classes as you move from top to bottom. The most general class, ChessPiece, is at the top of the hierarchy. Its attributes and methods are passed on to (inherited by) its subclasses. However, in addition to the attributes and methods they inherit from their superclasses, the subclasses define their own special attributes and methods. Each of the subclasses, Pawn, Bishop, and so on, represents some kind of specialization of the superclass. In this example, each of the subclasses have their own distinctive ways of moving. And the King subclass has unique attributes and actions (inCheck and castle(). 0.7.9 Principles of Object-Oriented Design As we have discussed, an object-oriented program is composed of many objects communicating with each other. The process of designing an object-oriented program to solve some problem or other involves several important principles: • Divide-and-Conquer Principle. Generally, the first step in designing a program is to divide the overall problem into a number of objects that will interact with each other to solve the problem. Thus, an objectoriented program employs a division of labor much as we do in organizing many of our real-world tasks. This divide-and-conquer approach is an important problem-solving strategy. • Encapsulation Principle. Once the objects are identified, the next step involves deciding, for each object, what attributes it has and what actions it will take. The goal here is to encapsulate within each object
SECTION 0.7 • What Is Object-Oriented Programming? 19 the expertise needed to carry out its role in the program. Each object is a self-contained module with a clear responsibility and the tools (attributes and actions) necessary to carry out its role. Just as a dentist encapsulates the expertise needed to diagnose and treat a tooth ache, a well-designed object contains the information and methods needed to perform its role. • Interface Principle. In order for objects to work cooperatively and efficiently, we have to clarify exactly how they should interact, or interface, with one another. An object’s interface should be designed to limit the way the object can be used by other objects. Think of how the different interfaces presented by a digital and analog watch determine how the watches are used. In a digital watch, time is displayed in discrete units, and buttons are used to set the time in hours, minutes and seconds. In an analog watch, the time is displayed by hands on a clock face, and time is set, less precisely, by turning a small wheel. • Information Hiding Principle. In order to enable objects to work together cooperatively, certain details of their individual design and performance should be hidden from other objects. To use the watch analogy again, in order to use a watch we needn’t know how its time keeping mechanism works. That level of detail is hidden from us. Hiding such implementation details protects the watch’s mechanism, while not limiting its usefulness. • Generality Principle. To make objects as generally useful as possible, we design them not for a particular task but rather for a particular kind of task. This principle underlies the use of software libraries. As we will see, Java comes with an extensive library of classes that specialize in performing certain kinds of input and output operations. For example, rather than having to write our own method to print a message on the console, we can use a library object to handle our printing tasks. • Extensibility Principle. One of the strengths of the object-oriented approach is the ability to extend an object’s behavior to handle new tasks. This also has its analogue in the everyday world. If a company needs sales agents to specialize in hardware orders, it would be more economical to extend the skills of its current sales agents instead of training a novice from scratch. In the same way, in the object-oriented approach, an object whose role is to input data might be specialized to input numeric data. • Abstraction Principle. Abstraction is the ability to focus on the important features of an object when trying to work with large amounts of information. For example, if we are trying to design a floor plan for a kitchen, we can focus on the shapes and relative sizes of the appliances and ignore attributes such as color, style, and manufacturer. The objects we design in our Java programs will be abstractions in this sense because they ignore many of the attributes that characterize the real objects and focus only on those attributes that are essential for solving a particular problem. These, then, are the principles that will guide our discussion as we learn how to design and write object-oriented Java programs.
20 CHAPTER 0 • Computers, Objects, and Java CHAPTER SUMMARY Technical Terms action (behavior) argument attribute class class inheritance class hierarchy class method class variable compiler computer program constructor high-level language instance instance method instance variable interpreter method message object object code object oriented result source code subclass superclass Unified Modeling Language (UML) variable Summary of Important Points • A computer system generally consists of input/output devices, primary and secondary memory, and a central processing unit. A computer can only run programs in its own machine language, which is based on the binary code. Special programs known as compilers and interpreters translate source code programs written in a high-level language, such as Java, into machine language object code programs. • Application software refers to programs designed to provide a particular task or service; systems software assists the user in using application software. • The client/server model is a form of distributed computing in which part of the software for a task is stored on a server and part on client computers. • HyperText Markup Language (HTML) is the language used to encode WWW documents. • A Java program is a set of interacting objects. This is the basic metaphor of object-oriented programming. • An object in a Java program encapsulates the program’s attributes (or variables) and actions (or methods). A variable is a named memory location where data of appropriate type can be stored. A method is a named section of code that can be called (or invoked) when needed. • An object’s methods are used to pass messages to it. • A class is an abstract template that defines the characteristics and behaviors of all objects of a certain type. • An object is an instance of a class. An object has instance methods and instance variables. A class method (or class variable) is a method (or variable) that is associated with the class itself, not with its instances. • A constructor is a special method that is used to construct objects. • Java classes are organized into a class hierarchy, with the Object class at the top of the hierarchy. For a given class, classes that occur below it in the hierarchy are called its subclasses, while classes that occur above it are called its superclasses. • Classes inherit attributes and methods from their superclasses. This is known as class inheritance. • The main principles of the object-oriented programming approach are as follows: • Divide and Conquer: Successful problem solving involves breaking a complex problem into objects.
CHAPTER 0 • Exercises 21 • Encapsulation and Modularity: Each object should be assigned a clear role. • Public Interface: Each object should present a clear public interface that determines how other objects will use it. • Information Hiding: Each object should shield its users from unnecessary details of how it performs its role. • Generality: Objects should be designed to be as general as possible. • Extensibility: Objects should be designed so that their functionality can be extended to carry out more specialized tasks. • Abstraction is the ability to group a large quantity of information into a single chunk so it can be managed as a single entity. EXERCISE 0.1 Fill in the blanks in each of the following statements. EXERCISES a. Dividing a problem or a task into parts is an example of the principle. b. Designing a class so that it shields certain parts of an object from other objects is an example of the principle. c. Java programs that can run without change on a wide variety of computers is an example of . d. The fact that social security numbers are divided into three parts is an example of the principle. e. To say that a program is robust means that . f. An is a separate module that encapsulates a Java program’s attributes and actions. EXERCISE 0.2 Explain the difference between each of the following pairs of concepts. a. hardware and software b. systems and application software c. compiler and interpreter d. machine language and high-level language e. general-purpose and special-purpose computer f. primary and secondary memory g. the CPU and the ALU h. the Internet and the WWW i. a client and a server j. HTTP and HTML k. source and object code EXERCISE 0.3 Fill in the blanks in each of the following statements. a. A is a set of instructions that directs a computer’s behavior. b. A disk drive would be an example of a device. c. A mouse is an example of an device. d. A monitor is an example of an device. e. The computer’s functions like a scratch pad. f. Java is an example of a programming language. g. The Internet is a network of .
22 CHAPTER 0 • Computers, Objects, and Java h. The protocol used by the World Wide Web is the protocol. i. Web documents are written in code. j. A is a networked computer that is used to store data for other computers on the network. EXERCISE 0.4 Identify the component of computer hardware that is responsible for the following functions. a. executing the fetch-execute cycle b. arithmetic operations c. executing instructions d. storing programs while they are executing e. storing programs and data when the computer is off EXERCISE 0.5 Explain why a typical piece of software, such as a word processor, cannot run on both a Macintosh and a Windows machine. EXERCISE 0.6 What advantages do you see in platform independence? What are the disadvantages? EXERCISE 0.7 In what sense is a person’s name an abstraction? In what sense is any word of the English language an abstraction? EXERCISE 0.8 Analyze the process of writing a research paper in terms of the divide-and-conquer and encapsulation principles. EXERCISE 0.9 Analyze your car by using object-oriented design principles. In other words, pick one of your car’s systems, such as the braking system, and analyze it in terms of the divide-and-conquer, encapsulation, information-hiding, and interface principles. EXERCISE 0.10 Make an object oriented analysis of the interaction between, a student, librarian, and a library database when a student checks a book out of a college library.
OBJECTIVES After studying this chapter, you will • Know the basic steps involved in program development. • Understand some of the basic elements of the Java language. • Know how to use simple output operations in a Java program. • Be able to distinguish between different types of errors in a program. • Understand how a Java program is translated into machine language. • Understand the difference between a Java console application and a Java Swing application. • Know how to edit, compile, and run Java programs. OUTLINE 1.1 Introduction 1.2 Designing Good Programs 1.3 Designing a Riddle Program Special Topic: Grace Hopper and the First Computer Bug 1.4 Java Language Elements 1.5 Editing, Compiling, and Running a Java Program 1.6 From the Java Library: System and PrintStream 1.7 From the Java Library: System and PrintStream Chapter Summary Solutions to Self-Study Exercises Exercises Chapter 1 Java Program Design and Development 23
24 CHAPTER 1 • Java Program Design and Development 1.1 Introduction This chapter introduces some of the basic concepts and techniques involved in Java program design and development. We begin by identifying the main steps in designing an object-oriented program. The steps are illustrated by designing a program that “asks” and “answers” riddles. As an example of a riddle, consider the question “What is black and white and read all over?” The answer, of course, is a newspaper. Following the design phase, we then focus on the steps involved in coding a Java program, including the process of editing, compiling, and running a program. Because Java programs can be text based applications or window based graphical applications, we describe how the coding process differs for these two varieties. Next we begin to familiarize ourselves with Java’s extensive class library by studying its PrintStream and System classes. These classes contain objects and methods that enable us to print output from a program. By the end of the chapter you will be able to design and write a Java application that “sings” your favorite song. 1.2 Designing Good Programs Programming is not simply a question of typing Java code. Rather, it involves a considerable amount of planning and careful designing. Badly designed programs rarely work correctly. Even though it is tempting for novice programmers to start entering code almost immediately, one of the first rules of programming is JAVA PROGRAMMING TIP The sooner you begin to type code, the longer the program will take to finish, because careful design of the program must precede coding. This is particularly true of object-oriented programs. In other words, the more thought and care you put into designing a program, the more likely you are to end up with one that works correctly. The following subsections provide a brief overview of the program development process. 1.2.1 The Software Engineering Life Cycle Software engineering is the process of designing and writing software. The software life cycle refers to the different phases involved in the design and development of a computer program. Our presentation of examples in the book will focus on four phases of the overall life cycle. In the specification phase we provide a statement of the problem and a detailed description of what the program will do. In the design phase we describe the details of the various classes, methods, and data that will be used in the program. The implementation phase refers to the actual coding of the program into Java. In the testing phase we test the program’s performance to make sure it is correct, recoding it or redesigning it as necessary. Figure 1.1 gives a more detailed overview of the program development process, focusing most of the attention on the design phase of the software
SECTION 1.2 • Designing Good Programs 25 life cycle. It shows that designing an object-oriented program is a matter of asking the right questions about the classes, data, and methods that make up the program. Overall, the program development process can be viewed as one that repeatedly applies the divide-and-conquer principle. That is, most programming problems can be repeatedly divided until you have a collection of relatively easy-to-solve subproblems, each of which can be handled by an object. In this way the program is divided into a collection of interact- Divide and conquer ing objects. For each object we design a class. During class design, each object is divided further into its variables and methods. Problem Specification What exactly is the problem? How will the program be used? How will the program behave? Data Design What types of instance variables are needed? Should they be public or private? Algorithm Design What information is needed? What control structures are needed? Problem Decomposition What objects will be used and how will they interact with each other? The problem is divided into objects. For each object we design a class. Program Development Process The object's role decomposes into tasks. Each task can be assigned to a method. Method design involves designing an algorithm. Errors may require recoding or redesigning. Coding into Java Stepwise refinement Fixing syntax errors Testing, Debugging, Revising Designing test data and test cases Fixing semantic errors Class Design What role or roles will the object perform? What variables (attributes) will it need? What methods (behaviors) will it use? What interface will it present? What information will it hide? Method Design What task will the method perform? What information will it need? What algorithm will it use? What result will it produce? Figure 1.1: An overview of the program development process. When should we stop subdividing? How much of a task should be assigned to a single object or a single method? The answers to these and similar questions are not easy. Good answers require the kind of judgment that comes through experience, and frequently there is more than one good way to design a solution. Here again, as we learn more about
26 CHAPTER 1 • Java Program Design and Development object-oriented programming, we’ll learn more about how to make these design decisions. 1.3 Designing a Riddle Program The first step in the program-development process is making sure you understand the problem (Fig. 1.1). Thus, we begin by developing a detailed specification, which should address three basic questions: • What exactly is the problem to be solved? • How will the program be used? • How should the program behave? In the real world, the problem specification is often arrived at through an extensive discussion between the customer and the developer. In an introductory programming course, the specification is usually assigned by the instructor. To help make these ideas a little clearer, let’s design an object-oriented solution to a simple problem. Problem Specification. Design a class that will represent a riddle with a given question and answer. The definition of this class should make it possible to store different riddles and to retrieve a riddle’s question and answer independently. 1.3.1 Problem Decomposition Most problems are too big and too complex to be tackled all at once. So Divide and conquer the next step in the design process is to divide the problem into parts that make the solution more manageable. In the object-oriented approach, a problem is divided into objects, where each object will handle one specific aspect of the program’s overall job. In effect, each object will become an expert or specialist in some aspect of the program’s overall behavior. Note that there is some ambiguity here about how far we should go in decomposing a given program. This ambiguity is part of the design process. How much we should decompose the program before its parts become “simple to solve” depends on the problem we’re trying to solve and on the problem solver. One useful design guideline for trying to decide what objects are needed is the following: JAVA EFFECTIVE DESIGN Looking for Nouns. Choosing a program’s objects is often a matter of looking for nouns in the problem specification. Again, there’s some ambiguity involved in this guideline. For example, the key noun in our current problem is riddle, so our solution will involve an object that serves as a model for a riddle. The main task of this Java object will be simply to represent a riddle. Two other nouns in the specification are question and answer. Fortunately, Java has built-in String
SECTION 1.3 • Designing a Riddle Program 27 objects that represent strings of characters such as words or sentences. We can use two String objects for the riddle’s question and answer. Thus, for this simple problem, we need only design one new type of object—a riddle—whose primary role will be to represent a riddle’s question and answer. Don’t worry too much if our design decisions seem somewhat mysterious at this stage. A good understanding of object-oriented design can come only after much design experience, but this is a good place to start. 1.3.2 Object Design Once we have divided a problem into a set of cooperating objects, designing a Java program is primarily a matter of designing and creating the objects themselves. In our example, this means we must now design the features of our riddle object. For each object, we must answer the following basic design questions: • What role will the object perform in the program? • What data or information will it need? • What actions will it take? • What interface will it present to other objects? • What information will it hide from other objects? For our riddle object, the answers to these questions are shown in Figure 1.2. Note that although we talk about “designing an object,” we are really talking about designing the object’s class. A class defines the collection of objects that belong to it. The class can be considered the object’s type. This is the same as for real-world objects. Thus, Seabiscuit is a horse—that is, Seabiscuit is an object of type horse. Similarly, an individual riddle, such as the newspaper riddle, is a riddle. That is, it is an object of type Riddle. The following discussion shows how we arrived at the decisions for the design specifications for the Riddle class, illustrated in Figure 1.2. • Class Name: Riddle • Role: To store and retrieve a question and answer • Attributes (Information) • question: A variable to store a riddle’s question (private) • answer: A variable to store a riddle’s answer (private) • Behaviors • Riddle(): A method to set a riddle’s question and answer • getQuestion(): A method to return a riddle’s question • getAnswer(): A method to return a riddle’s answer Figure 1.2: Design specification for the Riddle class. The role of the Riddle object is to model an ordinary riddle. Because What is the object’s role? a riddle is defined in terms of its question and answer, our Riddle object will need some way to store these two pieces of information. As we learned in Chapter 0, an instance variable is a named memory location that belongs to an object. The fact that the memory location is named, makes it easy to retrieve the data stored there by invoking the variable’s name. For example, to print a riddle’s question we would say something like “print question,” and whatever is stored in question would be retrieved and printed.
28 CHAPTER 1 • Java Program Design and Development In general, instance variables are used to store the information that an What information will the object object needs to perform its role. They correspond to what we have been need? calling the object’s attributes. Deciding on these variables provides the answer to the question, “What information does the object need?” Next we decide what actions a Riddle object will take. A useful design guideline for actions of objects is the following: JAVA EFFECTIVE DESIGN Looking for Verbs. Choosing the behavior of an object is often a matter of looking for verbs in the problem specification. What actions will the object take? For this problem, the key verbs are set and retrieve. As specified in Figure 1.2, each Riddle object should provide some means of setting the values of its question and answer variables and a means of retrieving each value separately. Each of the actions we have identified will be encapsulated in a Java method. As you recall from Chapter 0, a method is a named section of code that can be invoked, or called upon, to perform a particular action. In the object-oriented approach, calling a method (method invocation) is the means by which interaction occurs among objects. Calling a method is like sending a message between objects. For example, when we want to get a riddle’s answer, we would invoke the getAnswer() method. This is like sending the message “Give me your answer.” One special method, known as a constructor, is invoked when an object is first created. We will use the Riddle() constructor to give specific values to riddle’s question and answer variables. In designing an object, we must decide which methods should be made What interface will it present, and available to other objects. This determines what interface the object should what information will it hide? present and what information it should hide from other objects. In general, those methods that will be used to communicate with an object are designated as part of the object’s interface. Except for its interface, all other information maintained by each riddle should be kept “hidden” from other objects. For example, it is not necessary for other objects to know where a riddle object stores its question and answer. The fact that they are stored in variables named question and answer, rather than variables named ques and ans, is irrelevant to other objects. JAVA EFFECTIVE DESIGN Object Interface. An object’s interface should consist of just those methods needed to communicate with or to use the object. JAVA EFFECTIVE DESIGN Information Hiding. An object should hide most of the details of its implementation.
). The figure shows that the Riddle class has two hidden (or private) variables for storing data and three visible (or public) methods that represent the operations that it can perform. 1.3.3 Data, Methods, and Algorithms Among the details that must be worked out in designing a riddle object is deciding what type of data, methods, and algorithms we need. There are two basic questions involved: • What type of data will be used to represent the information needed by the riddle? • How will each method carry out its task? Like other programming languages, Java supports a wide range of different types of data, some simple and some complex. Obviously a riddle’s What type of data will be used? question and answer should be represented by text. As we noted earlier, Java has a String type, which is designed to store text, which can be considered a string of characters. In designing a method, you have to decide what the method will do. In How will each method carry out its order to carry out its task, a method will need certain information, which task? it may store in variables. Plus, it will have to carry out a sequence of individual actions to perform the task. This is called its algorithm, which is a step-by-step description of the solution to a problem. And, finally, you must decide what result the method will produce. Thus, as in designing objects, it is important to ask the right questions: • What specific task will the method perform? • What information will it need to perform its task? • What algorithm will the method use? • What result will the method produce? Methods can be thought of as using an algorithm to complete a required action. The algorithm required for the Riddle() constructor is very simple but also typical of constructors for many classes. It takes two strings and assigns the first to the question instance variable and then assigns the second to the answer instance variable. The algorithms for the other two methods for the Riddle class are even simpler. They are referred to as get methods that merely return or produce the value that is currently stored in an instance variable. Not all methods are so simple to design, and not all algorithms are so simple. Even when programming a simple arithmetic problem, the steps Algorithm design involved in the algorithm will not always be as obvious as they are when doing the calculation by hand. For example, suppose the problem were to calculate the sum of a list of numbers. If we were telling our classmate how to do this problem, we might just say, “add up all the numbers and report their total.” But this description is far too vague to be used in a program. By contrast, here’s an algorithm that a program could use: 1. Set the initial value of the sum to 0.
30 CHAPTER 1 • Java Program Design and Development 2. If there are no more numbers to total, go to step 5. 3. Add the next number to the sum. 4. Go to step 2. 5. Report the sum. Note that each step in this algorithm is simple and easy to follow. It would be relatively easy to translate it into Java. Because English is somewhat imprecise as an algorithmic language, programmers frequently write alPseudocode gorithms in the programming language itself or in pseudocode, a hybrid language that combines English and programming language structures without being too fussy about programming language syntax. For example, the preceding algorithm might be expressed in pseudocode as follows: ☛ ✟ sum = 0 while ( more numbers remain ) add nex t number to sum p ri n t the sum ✡ ✠ Of course, it is unlikely that an experienced programmer would take the trouble to write out pseudocode for such a simple algorithm. But many programming problems are quite complex and require careful design to minimize the number of errors that the program contains. In such situations, pseudocode could be useful. Another important part of designing an algorithm is to trace it—that is, to step through it line by line—on some sample data. For example, we might test the list-summing algorithm by tracing it on the list of numbers shown in the margin. Sum List of Numbers 0 54 30 20 54 30 20 84 20 104 - Initially, the sum starts out at 0 and the list of numbers contains 54, 30, and 20. On each iteration through the algorithm, the sum increases by the amount of the next number, and the list diminishes in size. The algorithm stops with the correct total left under the sum column. While this trace didn’t turn up any errors, it is frequently possible to find flaws in an algorithm by tracing it in this way. 1.3.4 Coding into Java Once a sufficiently detailed design has been developed, it is time to start generating Java code. The wrong way to do this would be to type the entire program and then compile and run it. This generally leads to dozens of errors that can be both demoralizing and difficult to fix. The right way to code is to use the principle of stepwise refinement. Stepwise refinement The program is coded in small stages, and after each stage the code is compiled and tested. For example, you could write the code for a single method and test that method before moving on to another part of the program. In this way, small errors are caught before moving on to the next stage. The code for the Riddle class is shown in Figure 1.4. Even though we have not yet begun learning the details of the Java language, you can easily pick out the key parts in this program: the instance variables question and answer of type String, which are used to store the riddle’s data; the Riddle() constructor and the getQuestion() and
SECTION 1.3 • Designing a Riddle Program 31 ☛ ✟ /∗ ∗ F i l e : R i d d l e . j a v a ∗ A u t h o r : J a v a , J a v a , J a v a ∗ D e s c r i p t i o n : D e f i n e s a s i m p l e r i d d l e . ∗/ pub l ic c l a s s Riddle ex tends O bje c t // C l a s s h e a d e r { // B e g i n c l a s s b o d y 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 m e t h o d { que s ti on = q ; answer = a ; } // R i d d l e ( ) 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 // E n d c l a s s b o d y ✡ ✠ Figure 1.4: The Riddle class definition. getAnswer() methods make up the interface. The specific language details needed to understand each of these elements will be covered in this and the following chapter. 1.3.5 Syntax and Semantics Writing Java code requires that you know its syntax and semantics. A language’s syntax is the set of rules that determines whether a partic- Syntax ular statement is correctly formulated. As an example of a syntax rule, consider the following two English statements: ☛ ✟ The r ai n in Spain f a l l s mainly on the pl ai n . // V a l i d Spain r ai n the mainly in on the f a l l s pl ai n . // I n v a l i d ✡ ✠ The first sentence follows the rules of English syntax (grammar), and it means that it rains a lot on the Spanish plain. The second sentence does not follow English syntax, and, as a result, it is rendered meaningless. An example of a Java syntax rule is that a Java statement must end with a semicolon. However, unlike in English, where one can still be understood even when one breaks a syntax rule, in a programming language the syntax rules are very strict. If you break even the slightest syntax rule—for ex-
width ; ✡ ✠
width, the compiler won’t detect an error in this statement. Thus, the computer will still execute this statement and compute the incorrect area. Semantic errors can only be discovered by testing the program and they are sometimes very hard to detect. Just because a program appears to run correctly on one test doesn’t guarantee that it contains no semantic errors. It might just mean that it has not been adequately tested. Fixing semantic errors is known as debugging a program, and when subtle errors occur it can be the most frustrating part of the whole program development process. The various examples presented will occasionally provide hints and suggestions on how to track down bugs, or errors, in your code. One point to remember when you are trying to find a very subtle bug is that no matter how convinced you are that your code is correct and that the bug must be caused by some kind of error in the computer, the error is almost certainly caused by your code! 1.3.7 Writing Readable Programs Becoming a proficient programmer goes beyond simply writing a program that produces correct output. It also involves developing good pro- Programming style gramming style, which includes how readable and understandable your code is. Our goal is to help you develop a programming style that satisfies the following principles: • Readability. Programs should be easy to read and understand. Comments should be used to document and explain the program’s code. • Clarity. Programs should employ well-known constructs and standard conventions and should avoid programming tricks and unnecessarily obscure or complex code. • Flexibility. Programs should be designed and written so that they are easy to modify. Special Topic: Grace Hopper and the First Computer Bug Rear Admiral Grace Murray Hopper (1906–1992) was a pioneer computer programmer and one of the original developers of the COBOL programming language, which stands for COmmon Business-Oriented Language. Among her many achievements and distinctions, Admiral Hopper also had a role in coining the term computer bug. In August 1945, she and a group of other programmers were working on the Mark I, an electro-mechanical computer developed at Harvard that was one of the ancestors of today’s electronic computers. After several hours of trying to figure out why the machine was malfunctioning, someone located and removed a two-inch moth from one of the computer’s circuits. From then on whenever anything went wrong with a computer, Admiral Hopper and others would say “it had bugs in it.” The first bug itself is still taped to Admiral Hopper’s 1945 log book, which is now in the collection of the Naval Surface Weapons Center.
34 CHAPTER 1 • Java Program Design and Development In 1991, Admiral Hopper was awarded the National Medal of Technology by President George Bush. To commemorate and honor Admiral Hopper’s many contributions, the U.S. Navy recently named a warship after her. For more information on Admiral Hopper, see the Web site at ☛ ✟ h t tp : //www. chip s . navy . mil/ ✡ ✠ 1.4 Java Language Elements In this section we will introduce some of the key elements of the Java language by describing the details of a small program. We will look at how a program is organized and what the various parts do. Our intent is to introduce important language elements, many of which will be explained in greater detail in later sections. The program we will study is a Java version of the traditional HelloWorld program—”traditional” because practically every introductory programming text begins with it. When it is run, the HelloWorld program (Fig. 1.5) just displays the greeting “Hello, World!” on the console. ☛ ✟ 1 /∗ 2 ∗ F i l e : H e l l o W o r l d . j a v a 3 ∗ A u t h o r : J a v a J a v a J a v a 4 ∗ D e s c r i p t i o n : P r i n t s H e l l o , W o r l d ! g r e e t i n g . 5 ∗/ 6 pub l ic c l a s s HelloWorld ex tends O bje c t // C l a s s h e a d e r 7 { // S t a r t c l a s s b o d y 8 p r i v a t e S t ri n g g r e e ti n g = ”Hello , World ! ” ; 9 pub l ic void g r e e t ( ) // M e t h o d d e f i n i t i o n 10 { // S t a r t m e t h o d b o d y 11 System . out . 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 12 } // g r e e t ( ) // E n d m e t h o d b o d y 13 pub l ic s t a t i c void main ( S t ri n g a rgs [ ] ) // M e t h o d h e a d e r 14 { 15 HelloWorld hellowo rld ; // d e c l a r e 16 hellowo rld = new HelloWorld ( ) ; // c r e a t e 17 hellowo rld . g r e e t ( ) ; // M e t h o d c a l l 18 } // m a i n ( ) 19 } // H e l l o W o r l d // E n d c l a s s b o d y ✡ ✠ Figure 1.5: The HelloWorld application program. 1.4.1 Comments The first thing to notice about the HelloWorld program is the use of comments. A comment is a non-executable portion of a program that is used to document the program. Because comments are not executable instructions they are just ignored by the compiler. Their sole purpose is to make the program easier for the programmer to read and understand. The HelloWorld program contains examples of two types of Java comments. Any text contained within /* and */ is considered a comment.

Personal Usage and not for publication
Related publications.
Items related to Java, Java, Java: Object-Oriented Problem Solving
Isbn 13: 9780131474345, java, java, java: object-oriented problem solving, morelli, ralph ; walde, ralph.

This specific ISBN edition is currently not available.
- About this title
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). Features coverage of Unified Modeling Language (UML), the industry-standard, object-oriented design tool. Illustrates key aspects of Java with a collection of game and puzzle examples. Instructor and Student resources available online. For introductory computer programming students or professionals interested in learning Java.
"synopsis" may belong to another edition of this title.
The topics covered and the approach taken in this book are suitable for a typical depthfirst Introduction to Computer Science (CS1) course or for a slightly more advanced Java as a Second Language course. The book is also useful to professional programmers making the transition to Java and object-oriented programming.
The book takes an "objects first" approach to programming and problem solving. It assumes no previous programming experience and requires no prior knowledge of Java or object-oriented programming. Why Start with Objects?
Java, Java, Java takes an "objects early" approach to teaching Java, with the assumption that teaching beginners the "big picture" early gives them more time to master the principles of object-oriented programming.
The first time I taught Java in our CS1 course I followed the same approach I had been taking in teaching C and C++ - namely, start with the basic language features and structured programming concepts and then, somewhere around midterm, introduce object orientation. This approach was familiar, for it was one taken in most of the textbooks then available in both Java and C++.
One problem with this approach was that many students failed to get the big picture. They could understand loops, if-else constructs, and arithmetic expressions, but they had difficulty decomposing a programming problem into a well organized Java program. Also, it seemed that this procedural approach failed to take advantage of the strengths of Java's object orientation. Why teach an object-oriented language if you're going to treat it like C or Pascal?
I was reminded of a similar situation that existed when Pascal was the predominant CS1 language. Back then the main hurdle for beginners was procedural abstraction - learning the basic mechanisms of procedure call and parameter passing and learning how to design programs as a collection procedures. Oh! Pascal!, my favorite introductory text, was typical of a "procedures early" approach. It covered procedures and parameters in Chapter 2, right after covering the assignment and I/O constructs in Chapter 1. It then covered program design and organization in Chapter 3. It didn't get into loops, if-else, and other structured programming concepts until chapter 4 and beyond.
Presently, the main hurdle for beginners is object abstraction. Beginning programmers must be able to see a program as a collection of interacting objects and must learn how to decompose programming problems into well designed objects. Object orientation subsumes both procedural abstraction and structured programming concepts from the Pascal days. Teaching "objects early" takes a top-down approach to these three important concepts. The sooner you begin to introduce objects and classes, the better the chances that students will master the important principles of object orientation.
Object Orientation (OO) is a fundamental problem solving and design concept, not just another language detail that should be relegated to the middle or the end of the book (or course). If OO concepts are introduced late, it is much too easy to skip over them when push comes to shove in the course.
Java is a good language for introducing object orientation. Its object model is better organized than C++. In C++ it is easy to "work around" or completely ignore OO features and treat the language like C. In Java there are good opportunities for motivating the discussion of object orientation. For example, it's almost impossible to discuss applets without discussing inheritance and polymorphism. Thus rather than using contrived examples of 00 concepts, instructors can use some of Java's basic features applets, the class library, GUI components - to motivate these discussions in a natural way. Key Features
In addition to its objects early approach, this book has several other important features.
The CyberPet Example. Throughout the text a CyberPet class is used as a running example to motivate and illustrate important concepts. The CyberPet is introduced in Chapter 2, as a way of "anthropomorphizing" the basic features of objects. Thus individual CyberPets belong to a class (definition), have a certain state (instance variables), and are capable of certain behaviors like eating and sleeping (instance methods). Method calls are used to command the CyberPets to eat and sleep. In Chapter 3 the emphasis is on defining and using methods and parameters to promote communication with Cyberpets. In subsequent chapters, concepts such as inheritance, randomness, animation, and threads are illustrated in terms of the CyberPet. Some of the lab and programming exercises are also centered around extending the behavior and sophistication of the CyberPet.
Applets and GUIs. Applets and GUIs are first introduced in Chapter 4 and then used throughout the rest of the text. Clearly, applets are a "turn on" for introductory students and can be used as a good motivating factor. Plus, event-driven programming and Graphical User Interfaces (GUIs) are what students ought now to be learning in CS1. We are j long past the days when command-line interfaces were the norm in applications programming. Another nice thing about Java applets is that they are fundamentally object oriented. To understand them fully; students need to understand basic OO concepts. That's why applets are not introduced until Chapter 4, where they provide an excellent way to motivate the discussion of inheritance and polymorphism.
Companion Web Site. The text is designed to be used in conjunction with a companion Web site that includes many useful resources, including the Java code and Java documentation (in HTML) for all the examples in the text, additional lab and programming assignments, on-line quizzes that can be scored automatically, and PowerPoint class notes. Problem Solving Approach. A pedagogical, problem solving approach is taken throughout the text. There are total of 13 fully developed case studies, as well as numerous other examples that illustrate the problem solving process. Marginal notes in the text repeatedly emphasize the basic elements of object-oriented problem solving: What objects do we need? What methods and data do we need? What algorithm should we use? And so on. Self-study Exercises. The book contains more than 200 self-study exercises, with answers provided at the back of each chapter. End-of-Chapter Exercises. Over 400 end-of-chapter exercises are provided, including "Challenge" exercises at the end of most sets. The answers are provided in an Instructor's Manual, which is available to adopters. Programming, Debugging and Design Tips. The book contains nearly 400 separately identified "tips" (Programming Tips, Debugging Tips, Effective Design Principles, and Java Language Rules) that provide useful programming and design information in a nutshell. Laboratory Sections. Each chapter concludes with a laboratory exercise, so the text can easily be used to support lab-based CS1 courses (such as ours). For CS1 courses that are not lab-based, these sections can still be read as preparation for a programming assignment. For each lab in the text, the companion Web site contains additional resources and handouts, as well as a repository of alternative lab assignments. From the Library Sections. Each chapter includes a section that introduces one or more of the library classes from the Java API (Application Programming Interface). In the early chapters these sections provide a way of introducing tools, such as I/O classes and methods, needed to write simple programs. In subsequent chapters, some of these sections introduce useful but optional topics, such as the NumberFormat class used to format numeric output. Others introduce basic GUI (Graphical User Interface) components that are used in program examples and the laboratory sections. Object-Oriented Design Sections. Each chapter includes a section on Object-Oriented Design which is used to underscore and amplify important principles such as inheritance, polymorphism, and information hiding. Java Language Summary. Those chapters that introduce language features contain Java Language Summary sections that summarize the feature's essential syntax and semantics. Organization of the Text
The book is organized into three main parts. The first part (Chapters 0 through 4) introduces the basic concepts of object orientation, including objects, classes, methods, parameter passing, information hiding, inheritance, and polymorphism. Although the primary focus in these chapters is on object orientation, rather than Java language details, each of these chapters has a Java Language Summary section that summarizes the language elements introduced.
In Chapters 1 to 3 students are given the basic building blocks for constructing a Java program from scratch. Although the programs at this stage have limited functionality in terms of control structures and data types, the priority is placed on how objects are constructed and how they interact with each other through method calls and parameter passing.
Offers an emphasis on design and problem solving through instruction and examples Emphasizes OO design concepts such as inheritance and information hiding early on and presents them as an essential component of using an OO language Features GUI elements and applets to captivate and maintain the reader's interest while introducing them to real-world examples Incorporates action learning tools such as "In the Laboratory" sections, "CyberPet" examples, and drop-in boxes on effective design, programming and debugging tips, and Java language rules Covers advanced features of the Java: GUIs, graphics and drawing; exceptions; recursive problem solving; threads and concurrent programming; files, streams, and input/output techniques; sockets and networking; and data structures Includes a Companion Website-with extensive supplementary resources such as a Study Guide, Power Point slides, Java code-and a CD-ROM that includes the Java code for all the examples in the text, and Java 2 SDK, Standard Edition, Borland JBuilder 3, University Edition, and NetBeans
"About this title" may belong to another edition of this title.
Convert currency
Shipping: US$ 3.95 Within U.S.A.
Add to Basket
Other Popular Editions of the Same Title
Featured edition.
ISBN 10: ISBN 13: 9780130113320 Publisher: Prentice Hall, 2000 Softcover
Prenti..., 2002 Softcover
Customers who bought this item also bought
Top search results from the abebooks marketplace.
Book Description Condition: new. Seller Inventory # Hafa_fresh_0131474340
More information about this seller | Contact this seller
Book Description Paperback. Condition: new. new. Seller Inventory # think0131474340
Book Description Paperback. Condition: new. new. Seller Inventory # Holz_New_0131474340
Book Description Condition: new. Seller Inventory # newport0131474340
Book Description Condition: new. Seller Inventory # NewCamp0131474340
Book Description Paperback. Condition: new. new. Seller Inventory # GoldenDragon0131474340
Book Description Paperback. Condition: new. new. Seller Inventory # Wizard0131474340
Book Description Condition: new. Seller Inventory # NewButterFly0131474340
Book Description Condition: new. Seller Inventory # 0131474340
Book Description Condition: new. Seller Inventory # newMercantile_0131474340
There are more copies of this book

IMAGES
VIDEO
COMMENTS
The six steps of problem solving involve problem definition, problem analysis, developing possible solutions, selecting a solution, implementing the solution and evaluating the outcome. Problem solving models are used to address issues that...
Learn the foundational basics of the Java programming language. Learn the foundational basics of the Java programming language. This course provides an introduction to the Java programming language. It gives students a foundational overview...
Stop startup problems before they even begin. Here are 5 common mistakes that can sabotage your business--and how to avoid them. Signing out of account, Standby... Stop startup problems before they even begin. Here are 5 common mistakes tha...
Java, Java, Java: Object-Oriented Problem Solving. (4 reviews). Ralph Morelli, Trinity College. Ralph Walde, Trinity College. Copyright Year
Java, Java, Java. Object-Oriented Problem Solving. Third Edition. R. Morelli and R. Walde. Trinity College. Hartford, CT. June 25, 2017
Book details · ISBN-10. 0131474340 · ISBN-13. 978-0131474345 · Edition. 3rd · Publisher. Prentice Hall · Publication date. January 1, 2006 · Language. English.
Java, Java, Java: Object-Oriented Problem Solving [Morelli, R.; Morelli, Ralph] on Amazon.com. *FREE* shipping on qualifying offers. Java, Java, Java:
Java, Java, Java. Object-Oriented Problem Solving. Third Edition. R. Morelli and R. Walde. Trinity College. Hartford, CT. June 25, 2017
Description: Functional and flexible, this guide takes an objects-first approach to Java programming and
Java, Java, Java Object-Oriented Problem Solving Third Edition R. Morelli and R. Walde Trinity College Hartford, CT February 5, 2012.
Functional and flexible, this book takes an objects-first approach to Java programming and problem using games and puzzles. Throughout the text we emphasize
The author takes an objects early approach to teaching Java, with the assumption that teaching beginners
Check Pages 1-50 of Java, Java, Java Object-Oriented Problem Solving (Ralph Morelli Ralph Walde) (z-lib.org) - 1151083366 in the flip PDF
AbeBooks.com: Java, Java, Java: Object-Oriented Problem Solving (9780131474345) by Morelli, Ralph; Walde, Ralph and a great selection of similar New