210
Study Guide Programming in Java By Joshua Hester

files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Study Guide

Programming in JavaBy

Joshua Hester

Page 2: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

About the Author

Joshua Hester is a content developer for Kaplan IT Learning and acertified trainer for Microsoft and Certified Internet Webmaster pro-grams. He has written, talked, taught, and breathed code for morethan 15 years. After mastering BASIC with a Commodore 64 andpushing his website development on people throughout college, hehas now evolved into Java Structs, the Microsoft 4 Framework, andother Web 2.0 technologies.

Mr. Hester is a certified Project Management Professional, LinuxProfessional, and Microsoft Office Specialist; he also holds certifica-tions for A+, Linux+, Network+, and i-Net+. He earned a bachelor of arts in English from Colgate University and is currently pursuinga masters of education in instructional technology from KaplanUniversity. Besides looking for more certifications, he’s an avid runner and gamer and enjoys biking, hiking, and solving the oddlogic puzzle.

Copyright © 2013 by Penn Foster, Inc.

All rights reserved. No part of the material protected by this copyright may bereproduced or utilized in any form or by any means, electronic or mechanical,including photocopying, recording, or by any information storage and retrieval system, without permission in writing from the copyright owner.

Requests for permission to make copies of any part of the work should be mailed to Copyright Permissions, Penn Foster, 925 Oak Street, Scranton,Pennsylvania 18515.

Printed in the United States of America

All terms mentioned in this text that are known to be trademarks or service marks have been appropriately capitalized. Use of a term in this text should not beregarded as affecting the validity of any trademark or service mark.

Page 3: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

INSTRUCTIONS TO STUDENTS 1

LESSON ASSIGNMENTS 5

LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7

GRADED PROJECT—LESSON 1 29

LESSON 2: DATA TYPES AND PROGRAM CONTROL 33

GRADED PROJECT—LESSON 2 71

LESSON 3: OBJECT-ORIENTED PROGRAMMING 79

GRADED PROJECT—LESSON 3 133

LESSON 4: ADVANCED PROGRAMMING LOGIC 141

GRADED PROJECT—LESSON 4 165

LESSON 5: GRAPHICAL USER INTERFACE DESIGN 169

GRADED PROJECT—LESSON 5 195

SELF-CHECK ANSWERS 201

iii

Co

nt

en

ts

Co

nt

en

ts

Page 4: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

1

Ins

tru

ctio

ns

Ins

tru

ctio

ns

YOUR COURSE

Like watching a nimble artisan, you can’t learn Java by mereobservation. You must practice. This course will introduceJava development by immersion. Each lesson builds uponthe previous one, layering concepts and growing skills—notthrough passive interpretation, but by writing real-worldapplications. The first few lessons will gently inch you intothe rich development world of Java, but by the end of thecourse, you’ll have a fully functional application and theassociated skillset to create many more.

The textbook for the course is Java: A Beginner’s Guide, FifthEdition, by Herbert Schildt. This study guide accompanies thetextbook by providing reading assignments, additionalresources, insights and highlights, and step-by-step activitiesand self-check questions to build skills and test your progress.The answers to the self-check questions are at the end of thestudy guide. The textbook also includes Try This activitiesand Self-Test questions in each chapter to provide additionalpractice.

The course is divided into five lessons, each with assignmentsand a graded project. The first three lessons will provide afoundation for using the Java language, while the last twowill move into specific Java frameworks. With the exceptionof the first graded project, each subsequent graded projectwill build upon the other. The final graded project is thesummary for the course, requiring you to apply your learnedJava knowledge and skills to an application built from theground up.

PREREQUISITES

This course assumes that you understand computer components, are familiar with text editor applications, haveexperience with programming languages other than Java, andhave had some exposure with object-oriented programmingand design. If these prerequisites are a bit rusty, then youmight find Oracle’s Java Tutorials (http://docs.oracle.com/javase/tutorial/index.html) a helpful supplement to thetextbook and study guide.

Page 5: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

When you complete this course, you’ll be able to

■ Write, compile, and run Java code

■ Implement common coding algorithms in Java

■ Create applications with object-oriented design principles

■ Use Java I/O and multithreading in applications

■ Create applets and Swing-based applications

YOUR TEXTBOOK

The textbook is Java: A Beginner’s Guide, Fifth Edition, byHerbert Schildt. It contains a thorough introduction to Javadevelopment and is a great preparation material for the OracleJava SE 7 Programmer certification. Java development isdivided into 16 chapters, starting with the runtime basics andconcluding with Swing. Answers to Self-Test questions arefound in the back of the book along with Java documentationcomments and an index.

COURSE MATERIALS

The main course materials are this study guide and the textbook. The study guide consists of the following:

■ Reading assignments for each lesson

■ Lessons that emphasize and augment the reading

■ Activities to perform tasks and apply your learning

■ Self-check questions and answers to assess your learning

■ Graded projects for each lesson

Instructions to Students2

Page 6: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

A STUDY PLAN

Everyone has his or her own style of learning. The object is to find the method of learning that works best for you. Whatfollows is a suggested format for using this study guide.Remember that it’s only a suggested plan. If you feel thatanother method would help you learn more effectively, byall means use that method.

This course divides the material to be covered into five lessons.Each lesson is divided into multiple assignments to make yourlearning more manageable. Each assignment includes a read-ing from your textbook and a supplementary assignment inthis study guide. For most assignments, there are self-checkquestions to check your understanding of what you’velearned. Be sure to complete all of the work in each lessonbefore moving on to the next. You’ll find this easy to do if youfollow the plan of study outlined below.

1. Note the textbook pages for each assignment and readthe summary material in this study guide.

2. Quickly read the assigned pages in your textbook. This is called skimming, and it’s a learning technique youshould use to get a general idea of the topics covered inthat part of the text.

3. Go back and slowly read the assigned textbook pagesagain. Pay careful attention to what you’re reading. Keepin mind the learning objectives and how the materialrelates to them. Pay particular attention to definitionsand main concepts.

4. Answer the questions and problems provided in the self-checks in the study guide. This will serve as a review ofthe material covered. The self-checks are an integral partof the assignment. Don’t move on to the next assignmentwithout taking the self-check. These questions are foryour use only—they aren’t graded. Don’t send youranswers to the school.

Instructions to Students 3

Page 7: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

5. Once you’ve completed a self-check, turn to the answersprovided at the back of this study guide. The self-checksare designed to show you how well you understand thematerial, so test yourself honestly. Make every effort tocomplete the questions before turning to the answers atthe back of this study guide. If you find any weak areasin your knowledge, go back and review the relevantmaterial until you understand it.

6. Follow this procedure for the next assignments, untilyou’ve completed the lesson.

7. When you’re confident that you understand all the assignedmaterial within a lesson, complete the examination orgraded project for that lesson. The examination is basedon both your textbook and this study guide.

8. Follow this procedure for all six lessons. If you have anyquestions during your studies, e-mail your instructor forassistance. You’re now ready to begin your study of Javaprogramming. Good luck!

Instructions to Students4

Remember to regularly check “My Courses” on your student homepage.Your instructor may post additional resources that you can access toenhance your learning experience.

Page 8: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 1: Introduction to the Java Language

For: Read in the Read in the study guide: textbook:

Assignment 1 Pages 7–11 Pages 1–10

Assignment 2 Pages 13–18 Pages 10–11

Assignment 3 Pages 19–28 Pages 12–30

Graded Project 40259400 Material in Lesson 1

Lesson 2: Data Types and Program Control

For: Read in the Read in the study guide: textbook:

Assignment 4 Pages 34–47 Chapter 2; Pages 158–164;166–176

Assignment 5 Pages 48–59 Chapter 3; Pages 110–117;176–177; 194–199

Assignment 6 Pages 60–65 Pages 136–158

Assignment 7 Pages 66–69 Chapter 9

Graded Project 40259500 Material in Lesson 2

Lesson 3: Object-Oriented Programming

For: Read in the Read in the study guide: textbook:

Assignment 8 Pages 80–96 Pages 104–110; 124–134; Chapter 6

Assignment 9 Pages 97–114 Chapter 7; Pages 268–278;427–429

Assignment 10 Pages 115–123 Pages 278–292; 406–420

Assignment 11 Pages 125–131 Pages 420–426; Chapter 13

Graded Project 40259600 Material in Lesson 3

5

As

sig

nm

en

tsA

ss

ign

me

nts

Page 9: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 4: Advanced Programming Logic

For: Read in the Read in the study guide: textbook:

Assignment 12 Pages 142–153 Chapter 10

Assignment 13 Pages 154–163 Chapter 11

Graded Project 40259700 Material in Lesson 4

Lesson 5: Graphical User Interface Design

For: Read in the Read in the study guide: textbook:

Assignment 14 Pages 170–182 Pages 473–496; 536–537

Assignment 15 Pages 183–193 Chapter 15

Graded Project 40259800 Material in Lesson 5

Lesson Assignments6

Note: To access and complete any of the examinations for this studyguide, click on the appropriate Take Exam icon on your “My Courses”page. You should not have to enter the examination numbers. Thesenumbers are for reference only if you have reason to contact StudentServices.

Page 10: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

7

Le

ss

on

1L

es

so

n 1

Introduction to the Java Language

INTRODUCTION

There’s no better way to learn how to program in a new lan-guage than to dive in! In this lesson, you’ll be introduced tothe Java language and runtime environment and you’ll tourthe NetBeans IDE. You’ll be writing, compiling, and runningyour first Java application by its conclusion.

OBJECTIVES

When you complete this lesson, you’ll be able to

■ Explain how procedural languages differ from object-oriented languages

■ Identify the main characteristics of Java technology

■ Install the Java Standard Edition 7 Runtime Environment

■ Identify language rules and common conventions in Java

■ Write, compile, and execute a simple Java program usingthe NetBeans IDE

ASSIGNMENT 1: A BRIEFOVERVIEW OF PROGRAMMINGRead Assignment 1 in this study guide. Then, read pages 1–10in your textbook.

The Procedural Approach

This assignment is an overview of basic programmingapproaches and introduces the Java language. The textbookassignment recounts the history of Java and reviews importantconcepts in high-level object-oriented programming (OOP).

Page 11: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java8

The goal of programming is to solve problems. In the proce-dural approach, the solution involves executing instructionsstep by step. Each step may modify some data, but the dataand instructions are stored separately. Data can be stored instructures such as arrays, sets, or records, while instructionsare grouped into procedures, and procedures are furthergrouped into modules. Procedures and modules allow pro-grammers to reuse code to reduce repetition and increasemanageability.

Take the example of making a fresh cup of coffee with a coffeepress. The data would include the amount of coffee beansand boiling water, whether the beans were ground or whole,and the time to boil the water and let the coffee brew. Theinstructions would include the following steps:

■ Measure the amount of beans and water.

■ Place the beans in the grinder.

■ Grind the beans in the grinder.

■ Place the water to boil on the stove.

■ Place the ground beans in the coffee press.

You get the idea. These and other instructions could thenbecome simple procedures named Boil(), Measure(), Grind(),Move(), Brew(), and Pour() in a module named Coffee. Theapproach focuses on action and which data is required toperform the actions.

A number of early languages, such as BASIC, COBOL, C, and FORTRAN, implement this approach. The more modernlanguages like Scala, Lisp, and F# implement a variation onthis approach, known as functional programming. Unlike traditional procedural programming, functional programminglanguages support additional built-in mathematical functionsand out-of-order execution for instructions.

The Object-Oriented Approach

The object-oriented approach is more abstract and less declar-ative than the procedural approach. Data and instructions arecombined into entities that resemble real-world objects. The

Page 12: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 1 9

data is stored as attributes of the object, while instructionsare grouped into its methods. Objects can have complex rela-tionships and interdependencies to optimize scalability andreduce overall redundancy. In object-oriented design, a classis a blueprint for objects, describing which attributes andmethods each object will support. Attributes are also knownas fields in Java.

Continuing with the coffee press example, an object-orientedapproach would first capture the real-world objects involved,which include the beans, grinder, water, and coffee press.The next step would be to determine which attributes eachobject requires. Coffee beans can be either whole or ground,so a field would need to represent that. Water can be eitherboiling or not boiling, and a coffee press can be brewing coffee,containing only beans, or empty. Like the procedural approach,measurements are tracked, but in object-orientation, eachobject tracks its own data. Finally, the methods need to bedetermined for each object. The methods are very similar tothe procedures described previously, except they’re stored inan object and usually require fewer arguments. For example,the Grinder object would contain a method named grind()that needs to know only how many beans to grind.

Most compiled languages and increasingly a number ofscripting languages as well, implement this approach. UnlikeC++ and Visual Basic, in which object-orientation was boltedonto an existing procedural language, Java is built from theground up on object-oriented programming. As you’ll see,even the simplest of programs requires a class and themain() method to execute.

The Java Approach

One of the early slogans for Java was “write once, run anywhere.”Java programs can run on diverse platforms—from standarddesktop and laptop computers to mobile phones and tablets.The current high definition standard even supports Java runningfrom BluRay discs!

When Java was introduced in 1995, most programming languagestargeted a specific platform. Conversely, Java applications areplatform-agnostic, meaning the developer only needs to learnJava, not keep track of the particulars of a specific CPU,

Page 13: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java10

motherboard, chipset, or operating system. A developer alsodoesn’t need to compile a program on each platform like C++,because the source code is compiled into optimized Javainstructions, known as bytecode. Then, a specialized execu-tion component known as the Java Virtual Machine (JVM)takes that bytecode and runs it on any platform with theJVM installed. The JVM is probably the reason why Javahasn’t faded away and only grows in popularity as devicesand platforms become more diverse and powerful.

Note: The keyword,native, allows for nativecode to be integratedinto Java applicationsto optimize certainfeatures for targetplatforms. Overuse ofnative code will nega-tively affect the defaultportability of a Javaapplication.

Page 14: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 1 11

Self-Check 1

At the end of each section of Programming in Java, you’ll be asked to pause and check yourunderstanding of what you’ve just read by completing a “Self-Check” exercise. Answeringthese questions will help you review what you’ve studied so far. Please complete Self-Check 1 now.

1. What is the fundamental difference between a procedural programming language and an OOP language?

__________________________________________________________

2. What does the slogan “write once, run anywhere” mean for Java?

__________________________________________________________

Check your answers with those on page 201.

Page 15: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java12

NOTES

Page 16: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 1 13

ASSIGNMENT 2: INSTALL THEJAVA RUNTIME ENVIRONMENTRead Assignment 2 in this study guide. Then, read pages 10–11in your textbook.

The Java Runtime Environment (JRE) is a composite of theJVM, runtime commands and applications, and essentialclass libraries. The runtime commands include java andjavaw for running stand-alone programs, Java Web Start todeploy applications through a browser, and Java Plug-in torun applets within a browser. Essential class libraries includeclasses for input/output (I/O), networking, database connections,and user interface design.

Oracle offers three different flavors for the Java RuntimeEnvironment:

■ Standard Edition (SE)

■ Enterprise Edition (EE)

■ Micro Edition (ME)

Java EE provides additional support for servlets, Java Server Pages (JSP), Java Server Faces (JSF), Enterprise Java Beans (EJBs), and other technologies associated withbusiness applications. Think of Java SE as the client-sideruntime, while Java EE provides an additional framework for server-side applications. Java ME is a configurable subsetof the Java SE for supporting small devices such as printers,mobile phones, and smart cards. Java ME doesn’t contain allclass libraries found in SE, but does include Java for MobileDevices, Java Technology for Embedded, Java TV, and JavaCard.

Java Development Kit

To run a Java application, only the JRE is required. To developa Java application, you also need the Java Development Kit(JDK). The JDK includes all components of the JRE, the com-piler javac, and other developer tools. These tools provideautomated documentation with JavaDoc, a compression

Note: Web Start appli-cations and applets arenow known as richinternet applications(RIAs) by Oracle.

Page 17: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java14

formatter known as Java Archive (JAR), and even its ownrelational database called Java DB. The JDK is also knownas the Java Software Development Kit (SDK), so don’t let thename conflict confuse you. These two terms are synonymousand used interchangeably in most documentation.

When downloading the JDK, you can choose to install the JDKonly or bundled with other Java technologies such as JavaFXor Java EE tools. The textbook uses the JDK only, but for thiscourse, you’ll download and install the JDK bundled with theNetBeans Integrated Development Environment (IDE).

Activity 1: Install the JDK 7 with NetBeans Bundle

1. Download the JDK 7 with NetBeans Bundle from theOracle Java SE Download page (Figure1). The currentdownload URL is http://www.oracle.com/technetwork/java/javase/downloads/jdk-7-netbeans-download-432126.html

a. On the Web page, choose the Accept LicenseAgreement radio button.

b. Click on the file required for your platform. Formost students, this would be the link labeledWindows x86.

c. Choose to save the file, so that you can re-run it if necessary.

d. Once the download is complete, run the file. If you’reprompted to allow the program to make changes toyour computer, click the Yes button.

2. Navigate through the Java SE Development Kit andNetBeans IDE Installer wizard.

a. Click the Next button.

b. On the JUnit License Agreement page, choose Iaccept the terms in the license agreement.Install JUnit.

Page 18: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 1 15

c. You can change the JDK installation location if youwould like. Click the Next button.

d. You can change the NetBeans IDE and JDK for theNetBeans IDE installation locations if you like. Clickthe Next button.

e. Verify your configuration settings and then click theInstall button.

f. The installation will take several minutes. Click theFinish button when it completes.

If you have any problems during the installation, please letyour instructor know.

FIGURE 1—NetBeans Download Page

Page 19: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java16

NetBeans Projects

NetBeans is intended for developing and deploying Javaapplications with many moving parts. To simplify manage-ment, code is organized into projects and further subdividedinto packages. A project is a complete application, while eachrelated group of components in that project is a package.

NetBeans includes the following types of projects:

Java Application—Standard stand-alone application that’srun using the java command. To simplify compilation, anauto-generated build script handles all source code files.

JavaFX Application—A stand-alone application with JavaFXenabled for a rich graphical user interface (GUI).

Java Class Library—Reusable code library with no user interface.

NetBeans Module—Plug-in for the IDE itself. Since NetBeansis a Java application, you can use Java to create plug-ins for it.

Activity 2: Create YourFirst NetBeans Project

1. To launch NetBeans, click on the Start Menu and clickthe All Programs section. Choose NetBeans IDE 7.2 inthe NetBeans folder.

2. In the File menu, choose New Project.

3. In the New Project wizard, choose the Java category andJava Application project (Figure 2).

4. Click the Next button.

5. Type the name FirstJavaApp in the Project Name textbox at the top. Leave all other default settings (Figure 3).

6. Click the Finish button. It will take several seconds forthe new project to be created and saved.

Page 20: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 1 17

FIGURE 2—New Project

Figure 3—New Java Application Dialog

Page 21: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java18

Self-Check 2

1. What is the primary difference between the Java SE and ME runtime environments?

__________________________________________________________

2. Why do you need to install the JDK to write Java applications? Is the JDK required to run Java applications?

__________________________________________________________

Check your answers with those on page 201.

Page 22: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 1 19

ASSIGNMENT 3: WRITE, COMPILE,AND EXECUTE JAVA PROGRAMSRead Assignment 3 in this study guide. Then read pages 12–30in your textbook.

As described on page 12 in the textbook, the basic developmentprocess is three steps: enter, compile, and run. In real-worlddevelopment, you would first define what the application will doand design the class structure and user interface prototypes.

Another important step is missing after compiling and runninga program: debugging! The compiler will catch syntax errors,but semantic errors won’t be obvious until running the appli-cation. Rarely will an application work perfectly as written,especially when you’re writing in a new programming language.Don’t be discouraged; making mistakes and learning how todebug them is an integral part of becoming familiar with anew language.

On page 13, the textbook describes how to compile and executea Java program using the command line. Because you’ll beusing NetBeans, the compile and execute steps are combinedinto one. To run a Java application, simply click the RunProject button (F6). The term building refers to the process ofcompiling all classes within a project. Although NetBeansautomates the process somewhat, it’s important to rememberthat Java source code files have the extension .java, andcompiled bytecode files have the extension .class. Also, mul-tiple .class files can be combined into executable archive fileswith the extension .jar.

Page 23: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java20

The main() Method

In Java, a class is the primary container for code. Becausemost applications consist of multiple classes, the class thatcontains the main() method will be loaded first. The main()method is the initial entry point, where JVM will start execution.The main() method is declared in a class as follows:

class SomeClass {public static void main ( String[] args ) {

//Starting code goes here}

}

The code in bold is required by the JVM to see the main()method. The public keyword ensures the main() method isvisible to the JVM, while the static keyword allows the JVMto call the method without first creating a class object. Thevoid keyword indicates that there’s no return value. Theargument String[] args allows you to send arguments fromthe command line when running an application. The variableargs can be named anything else, but common convention isargs. The following is an example of sending arguments:

java JavaApp1 “Argument 1” arg2 3

All arguments are treated as String objects (more about thatin the next lesson). The textbook describes command-linearguments in more detail on pages 165–166 of Chapter 5.With NetBeans, your applications won’t use command-linearguments, because they’ll be launched through the IDE, not via the command line.

Java Syntax and Common Coding Conventions

Like C and C++, Java is case-sensitive and uses the semicolon ;to terminate lines of code. Case-sensitivity can cause somefrustration to programmers who are familiar with more lenientlanguages like Visual Basic. Don’t think of it as an arbitraryconvention—think of it as a way for the compiler to encouragegood programming practices.

Note: Your textbookuses the argumentString args[] instead of String[] args, buteither order is allowed.String[] args is the pre-ferred convention.

Page 24: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 1 21

Code Blocks and Comments

Java uses curly brackets { } to enclose blocks of code anduses square brackets [ ] to define and access arrays (moreabout that in the next lesson). Pages 24–26 in the textbookgo into more depth about how to create blocks of code andgood indentation practices when doing so.

The characters // specify an inline comment, while /* and */are used for block comments. Developers use comments tohighlight important or complex algorithms, to provide book-marks for future reference, or to remove code that maycontain errors during debugging. The compiler never readscomments.

int i = 0; //This code initializes an integer to the defaultvalue 0.

/*

* This is a longer comment

* set off from the code

* in multiple lines.

*/

Note: You can use the Toggle Commentoption from the Sourcemenu or the keyboardshortcut CTRL+/ inNetBeans to hide codeduring debugging.

Page 25: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java22

There are also special comments using the characters /**and */ for detailed documentation comments using JavaDoc.The example below describes the loadImage method:

/*** Returns an {@link Image} object based on an

absolution {@link URL} * and filename {@link String}.* This method returns null if no compatible image

files exist. * @param url an absolute URL* @param name the image filename* @return An Image object* @see Image

*/public Image loadImage(URL url, String name) {

//Imagine some code here }

JavaDoc can then pull out the comments into HTML, XML, orany other standard documentation format to share them withother developers. JavaDoc will even generate missing com-ments for parameters, return types, and other details. Formore details on JavaDoc, you can visit the Oracle Website athttp://docs.oracle.com/javase/7/docs/technotes/guides/javadoc/.

Identifiers

When defining a class, method, variable, or custom data type,you must follow Java naming rules. The first character of anidentifier can be a letter, an underscore _, or, a dollar sign $.All subsequent characters can also include digits. As in otherlanguages, Java keywords are those that have special mean-ing and aren’t allowed when you define your own identifiers.See page 29 in the textbook for the complete list of Java key-words and examples of allowable identifiers.

Page 26: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 1 23

When following syntax rules, you should also consider com-mon programming conventions, especially those implementedin the language. There are two casing schemes used in mostprogramming languages: camel and Pascal. Camel casingkeeps the first letter of the name lowercase, but then usesuppercase for the first letter of each logical word or abbrevia-tion. A competing standard is known as Pascal casing, whereeven the first letter is uppercase. In Java, variables, methods,and package names use camel casing, whereas Pascal casingis used for class names and custom data types. This conven-tion makes it easier to eyeball whether something is a classor method without combing through lengthy documentation.

Cameo of Two Data Types and Control Statements

Textbook pages 16–24 briefly mention two numerical datatypes, and the control statements if and for. The data typeint represents whole numbers, while double represents frac-tional values. The if statement executes code only once whena condition is met, while a for statement executes coderepeatedly if the condition is met. Although you’ve beenexposed to these constructs before in other languages, you’llrevisit this topic within the larger context of program controlin the next lesson and further along in the textbook.

Brief Tour of the NetBeans IDE

Similar to other development environments, the NetBeansIDE uses toolbars, panels, and windows to provide access to information and tools on the same screen (Figure 4). Theamount of information can seem overwhelming at first, butover time, you’ll value having it at your fingertips.

Page 27: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java24

Panels

For projects in this course, you need to be concerned onlywith the following panels:

Projects. The Projects panel contains the logical structureof all of your files associated with each NetBeans project. Youcan add files to your project using the File menu or by right-clicking in the Projects panel.

Files. The Files panel contains the physical structure of allfiles associated with each NetBeans project. You can opendocuments by double-clicking in the Solution Explorer panelor using the File menu.

Documents. The Documents tabbed panel contains allsource code files opened in the IDE. A bolded file name in the tab indicates whether a file has been modified since itwas last saved.

Navigator. The Navigator contains a logical breakdown ofthe current document. Each method and field is displayedand can be double-clicked to go directly to that member.

Output. The Output displays compiler information and out-put for command-line applications with no GUI. You can alsoused it for standard keyboard input.

Figure 4—NetBeansIDE Window

Page 28: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 1 25

Main Toolbar

The main toolbar in NetBeans is broken into three groups(Figure 5). The first group is used for file operations, such ascreating new files and folders, opening projects, and savingall open files. The second group is used for performing undoand redo edit operations. The last group contains buttons forbuilding, cleaning, and then re-building, executing, anddebugging projects. The green triangle button and its key-board shortcut F6 builds a project and executes thebytecode.

Activity 3: Enter, Compile, and Run

You’ll enter, compile, and run a simple Java applicationusing NetBeans. Be sure to read pages 12–28 in the textbookcarefully before attempting this activity.

1. If you’ve closed out of the FirstJavaApp project andNetBeans, then launch NetBeans. (See Step 1 in Activity 2).

2. The FirstJavaApp.java file should be open inDocuments. If not, double-click the FirstJavaApp.javafile in Projects. You should see the following defaultcode provided:

/** To change this template, choose Tools |

Templates* and open the template in the editor.*/

package firstjavaapp;

/**** @author jhester*/

public class FirstJavaApp {

Figure 5—NetBeans Main Toolbar

Page 29: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java26

/*** @param args the command line arguments*/

public static void main(String[] args) {// TODO code application logic here

}}

3. Select the comment //TODO code application logichere and replace it with the following code:

System.out.println(“Welcome to the World ofJava!”);

4. Build and run the project by clicking the Run Projectbutton in the main toolbar or using the F6 keyboardshortcut.

5. The Output panel should display the following result:

run:Welcome to the World of Java!BUILD SUCCESSFUL (total time: 1 second)

In the next part, you’ll make an intentional syntax error andobserve how NetBeans handles it.

6. In the main() method, add the following line of code:

This isn’t valid syntax;

Notice how the NetBeans editor underscores the code with ared squiggly line. NetBeans is warning you that this part ofthe code will fail compilation.

7. Try to build and run the projectanyway. Click the Run Projectbutton in the main toolbar oruse the F6 keyboard shortcut.

8. NetBeans should display thewarning in Figure 6.

9. Click the Run Anyway button.The Output panel should dis-play an error message in red.

Figure 6—Compilation Error

Page 30: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 1 27

In the last part, you’ll make an intentional semantic errorthat won’t be detected until after the code is executed. Thiscode uses the for loop introduced on page 23 of the textbook.

10. Select the error-prone code This isn’t valid syntax; andreplace it with the following code:

/** This code will behave normally at first, * but then grow too big and become large* negative values.*/

for (int i = Integer.MAX_VALUE - 10000; ; i++ ){

System.out.println(“i: “ + i);}

11. Run and build the project. Notice when the numericalvalue gets too large for the int data type, the numberbecomes negative. Because there’s no exit conditionspecified in the for statement, the code will run in aninfinite loop.

12. In the Output panel, click the red stop button to endexecution.

Finally, you’ll correct the error and run the code again. Theprocess of running your code and verifying output is debug-ging. The more time you spend on designing and debugging,the less time you’ll spend on programming frustrations.

13. Modify the code in the for statement to stop once ibecomes negative as follows:

for (int i = Integer.MAX_VALUE - 10000; i > -1;i++ ) {

14. Run and build the project. Notice how execution endsbefore the max value is exceeded.

Page 31: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java28

Self-Check 3

1. What is the extension of a source code file and which command do you use to compile it?

__________________________________________________________

2. What is the extension of a bytecode file and which command do you use to run it?

__________________________________________________________

Check your answers with those on page 201.

Page 32: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

29

Gra

de

d P

roje

ct

Gra

de

d P

roje

ct

OVERVIEW

You’re ready to work on your first Java application. This proj-ect will assess your understanding of writing, compiling, andrunning a Java program.

Make sure that you follow all directions completely and verifyyour results before submitting the project. Remember toinclude all required components in your solution or you won’treceive full credit.

Your Project

For your first project, you’ll create a simple number guessinggame. The game will use a for statement to ask for threeguesses and an if statement to determine if the answer isright.

Instructions

1. In NetBeans, create a new Java Application projectnamed NumberGuess. Review Activity 2 for details.

2. In the main() method, add the code to generate a random number:

Page 33: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project 130

int randNum = 0, guessNum = 0;//Generates a random number from 1 to 10randNum = new java.util.Random().nextInt(10) + 1;System.out.println(“I am thinking of a number from1 to 10”);

3. Using a for loop, ask for three guesses. See pages 23–24in the textbook for more details. You can use the followingcode to ask for a guess:

System.out.print(“Guess? “);//Wraps the default input in a simple parsercalled Scannerjava.util.Scanner scan = newjava.util.Scanner(System.in);guessNum = scan.nextInt(); //Reads the next command-line intSystem.out.println(“You guessed “ + guessNum);

4. Using an if statement in the for block, determinewhether randNum and guessNum are equal. See pages21–23 for in the textbook for more details. You can use thefollowing code if randNum and guessNum are equal:

System.out.println(“You guessed it!”);break;

5. When you’re finished, the contents of the main() methodshould resemble the following:

int randNum = 0, guessNum = 0;//Generates a random number from 1 to 10randNum = new java.util.Random().nextInt(10) + 1;System.out.println(“I am thinking of random numberfrom 1 to 10”);for (/* Figure this part out yourself */) {

System.out.print(“Guess? “);java.util.Scanner scan = new

java.util.Scanner(System.in);guessNum = scan.nextInt();System.out.println(“You guessed “ +

guessNum);if (/* Figure this part out yourself */) {

System.out.println(“You guessed it!”);break;

}}

Note: The input/outputcode will be explainedin the last lesson. Don’tworry about under-standing all of it now.

Note: The break state-ment will be explainedin the next lesson.

Page 34: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project 1 31

6. Compile and run the project to ensure it works asexpected. To type input, make sure you click in theOutput panel; otherwise, you’ll modify code.

Submission Guidelines

To submit your project, you must provide the following two files:

■ NumberGuess.java

■ NumberGuess.class

To find these files within NetBeans, go to the NumberGuessproject folder. To determine this folder, right-click onNumberGuess project in the Projects panel. Copy the value forthe Project Folder textbox using the keyboard shortcutCTRL+C. In Windows Explorer, paste the project folder pathand hit the ENTER key. Copy both the NumberGuess.javafile from the src\numberguess folder and theNumberGuess.class file from the build\numberguess folderto your desktop or any other temporary location.

Follow this procedure to submit your project online:

1. Log on to the Penn Foster website and go to My Courses.

2. Click Take Exam next to the lesson you’re working on.

3. Attach your files as follows:

a. Click on the Browse box.

b. Locate the file you wish to attach.

c. Double-click on the file.

d. Click Upload File.

e. Since you have more than one file to attach, click onthe Browse box again, and repeat steps b, c, and dfor each file.

4. Enter your e-mail address in the box provided. (Note:This information is required for online submissions.)

5. If you wish to tell your instructor anything specificregarding this assignment, enter it in the Message box.

6. Click Submit File.

Page 35: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project 132

Grading Criteria

Your instructor will use the following guidelines to grade yourproject.

The source code file includes the provided code: 20 points

The for statement loops only three times: 30 points

The if statement checks for equality between the required variables: 30 points

Both source and compiled code files are included: 20 points

TOTAL 100 points

Page 36: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

33

Le

ss

on

2L

es

so

n 2

Data Types and Program Control

INTRODUCTION

As with all languages, you’ll need to learn the basics of howto store and perform operations on data and control applica-tion flow. This lesson will introduce you to using data types,operators, and expressions and handling program flow usingcontrol statements and blocks in Java. In addition, you’ll learnabout how to logically group values and statements usingarrays and methods, respectively.

OBJECTIVES

When you complete this lesson, you’ll be able to

■ Declare variables for values and choose the appropriateprimitive data type

■ Use literal values, typecasting, and standard operators

■ Use methods associated with String objects

■ Explain how different expressions are evaluated

■ Define application logic using appropriate control statements

■ Define and use methods

■ Declare and use arrays to handle multiple related values

■ Discuss multidimensional arrays

■ Handle runtime exceptions

Page 37: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java34

ASSIGNMENT 4: USE DATA TYPES,VARIABLES, AND OPERATORSRead Assignment 4 in this study guide. Then read Chapter 2,as well as pages 158–164 and 166–176 in your textbook.

In Assignment 4, you’ll be introduced to how to use variablesto perform operations. Be sure to complete the Try This activ-ities in Chapter 2. They’ll acquaint you with any unfamiliardata types in the lesson. The selected pages in Chapter 5introduce how strings are used in Java and some bitwisearithmetic operations.

Primitive Data Types

As you may remember from the previous lesson, all programminglanguages rely on data to perform their work. Each individualpiece of data (known as a datum) can represent different thingsand may require different storage considerations. Watermeasurement will require more precision than the number ofbeans, for example. This data is very different than determin-ing whether the water is boiling. The water is either boiling orisn’t boiling; there’s no in-between value.

The built-in data types in Java are known as primitive types.Their storage model is remarkably simple compared to objects.The value for a primitive type has a fixed size and is storedon the default memory stack. Whether an int type stores thenumber 4 or 4,000,000, an int will always be 16 bits (2 bytes)in size. If two int types have the same value, they’ll still bestored separately in memory. Primitive types are both fixed in size and unique.

In terms of complexity and storage, Boolean is the simplestprimitive. The only literal values valid for a Boolean are trueand false. Storage is a single bit that is either 0 or 1.

For numeric values, you can choose from integer or floating-point data types. In Java, all numbers are signed, meaningthat a sign bit is required for every number to indicatewhether it’s positive or negative. Integers are whole numberswithout fractional amounts, while floating-point numberssupport decimal points. Floating-point numbers store only

Page 38: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 2 35

the significant digits of numbers, ignoring leading and trailingzeroes, and use a base and exponent to represent the num-ber’s magnitude. The number of significant digits is known asits precision, while the magnitude is known as its scale. Forexample, the value 15,050,000 is stored as 15050000 in theinteger primitive int, but stored as 1.505E7 in the floating-pointprimitive double.

Integer primitives differ only in storage size. A byte uses 8 bits,while a long stores numbers with 64 bits or 8 bytes. The mostcommonly used integer primitive is int and for most programs,its size will be adequate. You’ll find a complete table of integerdata types and their sizes and number ranges at the bottomof page 33 in the textbook.

The primitives float and double also differ by storage, butbecause they use a floating-point representation, the differ-ence is in precision and scale, not an actual value range. Afloat devotes 23 bits to represent the precision and 8 bits forthe scale. Together with the sign bit, a float is 32 bits in size.A double is twice that size—64 bits.

The final primitive is char. This data type represents a 16-bitUnicode character (UTF-16), meaning that Java supports amajority of known languages in the world. A value for a charcan be specified as an integer, literal character, or hexadeci-mal character code. Character codes are specified using the\u suffix. You can find a complete list of character codes athttp://www.fileformat.info/info/charset/UTF-16/list.htm.

Variable Declaration and Scope

To reuse a value stored in memory, you must first reserveand identify it using a variable. In Java, all variables must bedeclared with a specified data type and name before they canbe used. The data type can be a primitive or object type andthe name must be a valid identifier. See the Identifiers sectionin the previous lesson for Java rules when using identifiers.

Page 39: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java36

The following code demonstrates how to declare variables:

Notice that the second and fourth lines declare multiple vari-ables using commas. The third, fourth, and last lines alsouse the assignment operator (=) to declare a variable and ini-tialize its value in the same statement. In Java, variablesmust be initialized to a value before they’re used in otherstatements. The last line uses the final keyword to declare aconstant. Constants can be used like variables, but theymust be initialized when declared and their values can’t bemodified after their assignment.

Variables don’t persist forever; they have a limited lifetime,known as scope. Scope is fairly straightforward: a variable is available only within the code block in which it’s declared.Although the same identifier can’t reference different valuesin the same scope, identifiers at different levels of scope canhave the same name. This can cause some serious confusion,so you should avoid using the same name for variables at different scopes.

The following simplified code demonstrates scoping:

{int x = 10;{//x is available here }}//x is out of scope hereint x = 10; //this is x at a different scope

Pages 43–46 in the textbook describe scoping issues in more depth.

int num; //One uninitialized integerdouble num1, num2, num3; //Three uninitialized floating-pointshort num4 = 1000; //One initialized integerfloat num5, num6 = 10; //One initialized and other notfinal char SPECIAL_CHAR = ‘Y’; //Constant value that can’t be changed

Page 40: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 2 37

Using Literal Values

Unlike variables, literal values are used once and then discarded.Like most languages, Java has some conventions for writingliteral values in code. Characters use single quotes whilemulticharacter strings use double quotes. Whole numbersare treated as int, byte, or short (depending on the literalsize), while numbers with decimal points are treated as doubletypes. If you want Java to treat whole numbers as long, thenyou can use the suffixes L in the literal for long. If you wantJava to treat a number with a decimal point as a float, thenuse the suffix f. This is the one situation where Java isn’tcase-sensitive. Oracle recommends using an uppercase suffixfor long and lowercase suffix for float.

The following are some literals with suffixes:

long num1 = 943543511234533145L; //Number was toobig for int, so must use suffix

float num2 = 453232234.52124f; //Loss ofprecision error if suffix was not used

By default, local variables aren’t set to a value. However,fields declared at the class level are set to a default valueautomatically. Table 1 lists the default values for data typeswhen declared at the class level. Notice that all referencetypes or objects default to the value null. Think of null as anempty variable with no reference. The next lesson will pick upthis topic again when discussing reference types.

Java 7 also supports other means of formatting and repre-senting literal numbers. Although the comma can’t be usedfor grouping digits in a number, the underscore character issupported. The underscore can be placed only between digitsand can’t be at the end or beginning of a number. The follow-ing code demonstrates using the underscore in a literalnumber:

int largeNumber = 36_997_000_145;

Although the default representation for numbers is traditionaldecimal notation, you can specify literals using scientificnotation, hexadecimal, or binary. Scientific notation is sup-ported only for the floating point types float and double, butcan use an uppercase or lowercase E to indicate the expo-nent. Hexadecimal requires the prefix 0x, while the prefix 0b

Page 41: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java38

indicates binary. Be aware that these alternative representa-tions are provided for convenience, but aren’t stored anydifferently than other numerical values.

The following are some literals specified in other notations:

double d1 = 5_100_000;

double d2 = 5.1E6; //Same value as d1 in scientificnotation

byte b1 = 127;

byte b2 = 0b0111_1111; //Same value as b1 in binary

byte b3 = 0x7F; //Same value as b1 and b2 in hexa-decimal

Type Casting

Normally, Java will handle conversions between primitivetypes automatically. For example, assigning an int value to a double is an automatic conversion that you need notworry about it. But you’ll run into situations where there’s a conflict between data types. Take the following example:

int i = 256;

byte b = i;

Data Type Default

Boolean False

byte, short, int 0

long 0L

float 0.0f

double 0.0

char ‘\u0000’

Object Null

Table 1—Data Type defaults

Page 42: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 2 39

The assignment of a variable to another variable isn’t at issue,because this is common. Assigning a variable to another sim-ply copies the original value and assigns it to the secondvariable. The conflict isn’t in the assignment, but the valueitself. The value 256 falls within the range of legal values forint, but well outside the valid range for byte. A byte can’t bemore than 127. Serious consequences will result when tryingto push too large a value into a smaller space. In Activity 4,you’ll explore these consequences firsthand.

In order to accept the conversion operation, you need to useexplicit conversion known as casting. Casting syntax specifiesthe desired data type in parentheses on the right side of theassignment operation. Using casting, the example can now becompiled with the following modification:

int i = 256;

byte b = (byte) i;

In the next lesson, you’ll also use casting to perform referencetype conversions as well.

Common Operators

An expression is a group of data that must be calculated atruntime. Expressions can contain literal values, variables,constants, and/or methods. Operators are special symbolsthat affect one or more values within an expression. The val-ues that are provided as input to an operator are known asoperands. Determining the overall value for an expression isknown as evaluation.

As the table on page 46 in the textbook demonstrates, Javaprovides standard arithmetic operators required for numericexpressions.

Note: All operators in Java are dependent on the operands youprovide, especially the case when using the division operatorwith two integers. The result will not be a fractional amount,but an unrounded integer. You’ll need to use casting to getthe decimal value. Instead of using 4 / 5, use (double) (4 / 5).

There are also single-argument operators, known as unaryoperators. Table 2 describes the unary operators.

Page 43: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java40

As indicated by the increment and decrement operators ++and – –, shorthand arithmetic assignment is supported byJava. To perform other arithmetic operations like division andmultiplication, you would use the arithmetic operator andassignment operator together. For example, to double thevariable x, you could use the expression x *= 2. Actually, thefollowing statements are equivalent:

i++;

i += 1;

i = i + 1;

Numeric expressions must evaluate to a number like int ordouble, while conditional expressions must evaluate to aboolean. The two tables on page 48 in the textbook list therelational and logical operators available in Java. Note that =is used for assignment and == tests equality. Another impor-tant difference is between the default operators & and |, andthe short-circuit operators && and ||. If the first operand isfalse when using the && operator or true when using the ||operator, then the second part isn’t evaluated, because thehole expression will evaluate to false or true, respectively.Such behavior reduces computation time, but can createsome unexpected results if you don’t know about it.

Unary Operator Description Code Example

+ Makes a number positive(default value) int i = +286;

– Makes a number negative float f = –120.7;

~ Reverses each binary bit of a number

byte b = ~0b011;//Becomes 100

++ Increments a variable by 1 i++;

– – Decrements a variable by 1 x– – ;

! Reverses a boolean value boolean b1 = false; boolean b2 = !b1;

Table 2—Unary Operators

Page 44: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 2 41

Operator Precedence

Normally, operations are performed in order from left to right.Some operations have higher priority than others and are eval-uated first. This is known as operator precedence. You’ve seenthis in many arithmetic operations before. Take the followingexample:

6 + 10 / 2 – 4

Without operator precedence, you would go from left to right,adding 6 to 10, then dividing it by 2, and finally subtracting 4.The result of 4 is incorrect, because multiplication and divi-sion occur before addition and subtraction. Using operatorprecedence, you should first divide 10 by 2, then add 6, sub-tract 4, and get the result of 7. Java is the same way, but thereare more than arithmetic operations to consider! Table 2-3 onpage 56 of the textbook lists precedence from highest to lowest.As in arithmetic, you can use the parentheses to performoperations out of their normal order.

Also confusing is the placement of ++ and – – operators. Thefollowing two expressions will increment x by 1, but will performthe operation at different times:

++x //Prefix increment

x++ //Postfix increment

In the first expression, x is incremented immediately and thenew value for x will be used for any other operations. In thesecond expression, x is incremented later and the currentvalue for x will be used for other expressions. Prefix opera-tions occur before evaluation, while postfix operations occurafter evaluation. In the next activity, you’ll use postfix andprefix operations in expressions.

Activity 4: Using Operators in Expressions

1. Launch NetBeans if it’s not already open. To launchNetBeans, click on the Start Menu and click the AllPrograms section. Choose NetBeans IDE 7.2 in theNetBeans folder.

Page 45: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java42

2. Create a new Java project named Lesson2Activity4. Tocreate a new Java project, follow these steps:

a. In the File menu, choose New Project. In the NewProject wizard, choose the Java category and JavaApplication project.

b. Click the Next button.

c. Type the name Lesson2Activity4 in the ProjectName text box at the top. Leave all other default set-tings.

d. Click the Finish button. It will take several secondsfor the new project to be created and saved.

3. Select the comment //TODO code application logic hereand replace it with the following code:

//Activity 4byte b1 = 0b0111_1111;int i1 = 127, i2 = -1;boolean isb1i1Equal = b1 == i1;boolean isb1i2Equal = b1 == i2;

System.out.println(“Is b1 equal to i1? “ +isb1i1Equal);System.out.println(“Is b1 equal to i2? “ +isb1i2Equal);

4. Before you run this code, take time to consider what youthink the output will be.

5. Build and run the project by clicking the Run Projectbutton in the main toolbar or using the F6 keyboardshortcut.

6. Remember that literals that begin with the 0b prefix areusing a binary representation. Did the output meet yourexpectations?

7. Modify the byte declaration line as follows:

byte b1 = 0b1111_1111;

Page 46: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 2 43

8. Notice there’s a compilation error indicated by the redsquiggly line under the code. Move your cursor over thehighlighted statement. What does “possible loss of preci-sion” mean?

9. To make this code compile, we need to explicitly cast thevalue to a byte. Modify the byte declaration line as fol-lows:

byte b1 = (byte) 0b1111_1111;

10. Build and run the project again. Why is the result different?

11. Under the previous code, add the following code:

double result1 = 10.2 - 5 * 10 + i1++;double result2 = (10.2 - 5) * 10 + ++i1;

System.out.println(“result1 = “ + result1);System.out.println(“result2 = “ + result2);

12. Before you run the code, take time to consider what youthink the output will be.

13. Build and run the project by clicking the Run Projectbutton in the main toolbar or using the F6 keyboardshortcut.

14. Remember order precedence and the difference betweenthe prefix and postfix increment operators. Also, noticethat i1 starts as 127 and then is incremented to 128after result1. Did the output meet your expectations?

You’ll use this same project in Activity 5, so you can keep itopen.

Note: Remember that abyte can’t be morethan 127 positive, butyou tried to push intothat small size thevalue 255. Don’t forgetthat one bit is reservedfor its sign.

Page 47: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java44

The String Object

In Java, variable-length text is stored in a specialized objectknown as String. String literals are enclosed using doublequotes, rather than the single quotes used by char. Table 2-2on page 40 lists some common escape characters you canuse in String literals for spacing and other special charac-ters.

Because a String is an object, it has methods you can use tomanipulate it. Page 160 in the textbook lists some commonString methods you’ll use. Like arrays, Strings use zero-basedindexes, so the first character is at position 0, not 1. Also,notice that you use the equals method to see if two Stringvalues have the same characters, not the equals operator ==.The most common operation you’ll perform with a String isconcatenation. Concatenation is combining Strings using theaddition operator +.

String values are immutable, meaning they can’t be modifiedafter being initialized. In other words, a String value is actuallyread-only. Take the following code:

String name = “Joshua, “;name += “welcome to”;name += “ Java”;name += “.”;

Although only the name variable is declared and used, thereare technically four String objects stored in memory. Theconcatenation is actually creating a new String object, ratherthan modifying the existing one. If the String values are lengthy,then you should consider using the StringBuilder classinstead.

The StringBuilder class limits the number of String objectsand provides additional manipulation methods. When you’redone using the StringBuilder class, you need only invoke thetoString() method to get the underlying String object. Youcan learn more about the StringBuilder class by visiting theOracle website at http://docs.oracle.com/javase/tutorial/java/data/buffers.html.

Page 48: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 2 45

Activity 5: Perform String Operations

1. Launch NetBeans and open the Lesson2Activity4 projectif you’ve closed out of the NetBeans.

2. The Lesson2Activity4.java file should be open inDocuments. If not, then double-click the file in theProjects panel.

3. So that you can keep the code used in Activity 4 for fur-ther reference without affecting this activity’s code, you’llcomment out the current code. To do this, highlight thecurrent code in the main() method and then choose theToggle Comment option from the Source menu or thekeyboard shortcut CTRL+/.

4. Add the following code to the main() method:

5. Read through the code before building and running thecode. Can you predict the output?

6. Build and run the project. Does it work as expected?

7. Modify the value for the msg variable and see if you canpredict how the output changes.

//Activity 5String msg = “Java is Fun to Write and Drink!”;System.out.println(msg);System.out.println(msg.toLowerCase());System.out.println(msg.toUpperCase());System.out.println(“Length: “ + msg.length());System.out.println(“First char: “ + msg.charAt(0));System.out.println(“Last char: “ + msg.charAt(msg.length()-1));System.out.println(“First i: “ + msg.indexOf(“i”));System.out.println(“Last i: “ + msg.lastIndexOf(“i”));

Page 49: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java46

Bitwise and Shift Operations

As you may recall from earlier programming courses, all numbersand instructions are stored using a binary representation.When creating low-level classes, you may need to manipulatethese representations. Java provides the bitwise and shiftoperators for just this purpose. Pages 166–176 in the text-book provide a thorough introduction to bitwise and shiftoperators if you want to learn more. Don’t feel too intimi-dated; most Java programmers use binary representationssparingly.

Page 50: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 2 47

Self-Check 4

1. What are primitive data types?

__________________________________________________________

2. What is the difference between integer numbers and floating-point numbers?

__________________________________________________________

3. When should you use explicit casting?

__________________________________________________________

4. What is the value of the variable result after the following statement?

double result = (5 - 10) + 15 % 7 * 10 ^ 2;

__________________________________________________________

5. What is the value of the variable charVal after the following statement?

char charVal = “Strings of Java”.toUpperCase().charAt(2);

__________________________________________________________

Check your answers with those on page 202.

Page 51: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java48

ASSIGNMENT 5: EXECUTE WITHPROGRAM CONTROL STATEMENTSAND METHODSRead Assignment 5 in this study guide. Then read Chapter 3,Chapter 4 pages 110–117, Chapter 5 pages 176–177, as well asChapter 6 pages 194–199 in your textbook.

Assignment 5 introduces the syntax for control statementsand methods. Be sure to complete the Try This activities inChapter 3. They’ll acquaint you with any unfamiliar datatypes in the lesson. The selected sections in Chapters 4–6describe basic and overloaded methods, and the ? operator.

Conditional Statements

It’s not uncommon that a statement or block of statementsshould execute only if a specific condition is true. One of theprimary mechanisms of control in Java is the if statement.The if statement can be accompanied by the else for anystatement(s) that must execute if the condition isn’t true. The general syntax is as follows:

if ( conditional_expression ) {//statements that execute if true

} else {//statements that execute if false

}

The syntax shown above is the long-hand form when morethan one statement must execute. You could also use theshort-hand syntax if only a single statement need execute.The following code is an example:

if (msg1.equals(msg2))System.out.println(“EQUAL”);else System.out.println(“NOT EQUAL”);

Typical of Java, there’s also a shorter syntax. If only a singlevalue needs to be returned, then you can use the ? operator.The ? operator uses the following syntax:

conditional_expression ? value_if_true :value_if_false

Page 52: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 2 49

The previous example could use the ? operator as follows:

System.out.println( msg1.equals(msg2) ? “EQUAL” :“NOT EQUAL”);

Although you can use logical operators to combine conditionalexpressions, you may want to perform separate checks. Youcan use the else-if statement to do this as follows:

if (guess == number) {System.out.println(“Good job!”);} else if (guess > number - 5 && guess < number +5) {System.out.println(“Very close!”);} else if (guess > number) {System.out.println(“Way too high!”);} else if (guess < number) {System.out.println(“Way too low!”);}

Notice that the conditional expression in the else-if state-ment is evaluated only when the condition is false in theprevious if or else-if statement.

Using else-if statements can be useful for complex conditionsand value ranges, but not for testing discrete values. Javaprovides the switch statement for those situations. The fol-lowing code demonstrates usage of the switch statement:

switch (state) {case “TX”:shippingCost = 4.59;break;case “GA”:shippingCost = 2.85;break;case “NY”:case “LA”:shippingCost = 3.65;break;default:shippingCost = 5.00; }

Page 53: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java50

Note the following about this code. The variable or expressioncan be a byte, int, char, String, or enumeration (more aboutthat in the next lesson). The first two case labels for TX andGA specify only one condition, but the third label for NY fallsthrough to the fourth label for LA. Any case label that doesn’tcontain a break statement will fall through. The break state-ments exit the switch statement, so that no other code in theswitch block is executed. Finally, the default label is exe-cuted if there’s no match in the previous case labels.

Iterative Statements

Whereas conditional statements will execute statement(s) onlyonce if a condition is true, iterative statements can executemultiple times while the condition is true. The two simplestiterative statements are while and do-while. The only differ-ence between the two statements is when the condition isevaluated. Because the condition in the do-while statementis evaluated at the end of each iteration, the statements inthe do-while block will execute at least once.

In both the while and do-while statements, the number ofiterations is dependent on the conditional expression and not necessarily on a counter. Java provides the for statementspecifically for handling counters. The general syntax for thefor statement is as follows:

for (initializer_statement; conditional_expres-sion; iteration_statement) {

//statements to run here}

The initializer statement runs once before the for block startsits first iteration. The conditional expression is evaluated beforeeach iteration, while the iteration statement is executed aftereach iteration. The following code demonstrates using the forstatement:

for (int count = 10; count >= 0; count—) {System.out.print(count + “...”);}

System.out.println(“BLAST OFF!”);

Besides using a counter, you can also use the break and continue statements to control the number of iterations. Thebreak statement will exit a code block, while the continue

Page 54: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 2 51

statement will skip the remaining code in the block and moveonto the next iteration. As you saw for the switch statement,the break statement can be unlabeled to exit out of theinnermost code block. You can also create labels and specifywhich code block to exit as follows:

outer: for (int x = 0; x < 100; x++) {inner: while (!isFound) {if (x == codeValue ) {System.out.println(“FOUND IT!”);break outer;}} }

Activity 6: Create a Simple Countdown

In this activity, you’ll use nested loops with a continuestatement.

1. Create a new Java Application project namedLesson2Activity6. Review steps 1 and 2 of Activity 4if you need help on performing this action.

2. Select the comment //TODO code application logichere and replace it with the following code:

char promptChar = ‘\u0000’; //nullcharacter//Remember this line from the first gradedproject?java.util.Scanner scan = newjava.util.Scanner(System.in);int counter = 100, block = 10; //Total countand block

do {for (int i = block; i > 0; i— ) {System.out.print(counter + “...”);counter—;}System.out.print(“\nContinue countdown?(y/n):“);promptChar = (char) scan.next().charAt(0); } while (promptChar != ‘n’);

Page 55: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java52

3. Before you run the code, take time to consider what youthink the output will be. The code will count from 100 indecrements of 10, until the n character is pressed.

4. Build and run the project by clicking the Run Projectbutton in the main toolbar or using the F6 keyboardshortcut. Remember: Click in the Output panel to typeinput. You have to type in a character other than n andhit the ENTER key to continue. Type n and hit theENTER key to stop the application.

5. Think about how you could modify this code to printonly even numbers in the countdown. Hint: The modulusoperator % is commonly used to find even and odd numbers.

6. Replace the code in the for block with the following:

if (counter— % 2 != 0) continue;System.out.print(counter + “...”);

7. Build and run the project. Does it work as expected?

8. Notice that every tenth value is omitted. This is becausethe counter variable is now decremented at the beginningof each iteration. It would be easier if the for statementcould handle both variables i and counter. Luckily, forloops can have multiple expressions in the iterationstatement!

9. Modify the for block as follows:

for (int i = block; i > 0; i—, counter— ) {if (counter % 2 != 0) continue;System.out.print(counter + “...”);}

10. Build and run the project. It should now work asexpected. How would you modify the code to exit beforereaching 50? Hint: You could use the break statement.

You’ll use this same project in Activity 7, so you can keep it open.

Page 56: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 2 53

Declaring Methods

Methods are useful in hiding complexity and reusing commoncode. Two methods you’ve been using so far are main() andprintln(). The main() method is where you placed code to runwhen the application starts, while println() writes output tothe command line. You also learned about methods used withString objects, such as toUpperCase() and charAt(). Some ofthese methods accept input data known as arguments andwhen they finish, send back output known as a return value.

To declare your own methods, you should use the followingsyntax:

return_type MethodName (list_of_parameter_types) {//definition here}

The return type specifies what data type the method willreturn or the keyword void if no value is returned. To returna value in a method, you use the return statement. Java isvery strict about return values—if the method specifies areturn type, then all code paths in the method must returnthat data type or compilation will fail. You can also specify areturn statement with no value to exit a method prematurely.

The parameter list is comma-delimited and order-dependent.When invoking a method, the Java runtime determines thevalues for the parameters based on the order of arguments.

Take the following method:

double drink(double sipAmount, double totalSize ){

return totalSize - sipAmount;}

Because this method specifies two double parameters, youmust provide two double arguments to invoke it. You don’tneed to handle the return value, but the order in which youplace the arguments will affect the return value. If you invokethe drink() method with drink(10, 20), then the argument 10will be the value for the sipAmount parameter, 20 will be thevalue for the totalSize variable, and the return value will be 2.0.

Page 57: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java54

Java also allows a variable number of arguments, known asvarargs. Unlike normal parameters, a varargs parameter isoptional and can have more than one value. The followingmethod uses the ellipse to specify a varargs parameter:

void printArgs(Object... objs) {for (int i = 0; i < objs.length; i++) {System.out.println(“Argument#” + i + “: “ +

objs[i]);}}

This should look similar to how main() method argumentswere handled in the first lesson. This is because the varargsparameter is treated like an array. Arrays will be discussed inthe next section.

The code printArgs(“Testing”, 5, 10.5f, ‘c’, false); will producethe following output:

Argument0: Testing

Argument1: 5

Argument2: 10.5

Argument3: c

Argument4: false

A varargs parameter can appear as the only or last parameterfor a method. Otherwise, the runtime would be unable to dif-ferentiate between normal and varargs parameters.

Note: Like class variables, methods can also include modifierssuch as public and static. These modifiers will appear beforethe return type. In the next lesson, the meaning of thesemodifiers will be discussed. For now, just understand thatstatic is a required modifier when invoking a method directlyfrom the main() method. Remember the main() method isalso declared with the static keyword.

Overloading

Recall that the Java runtime determines the values for theparameters based on the order of arguments when invokingmethods. The name of a method and its order of parameterdata types is known as a method signature. The method

Page 58: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 2 55

signature is how the runtime figures out which methodshould be invoked. When you invoke a method nameddoSomething with the arguments 3, 4, 5, and 6, then theJava runtime is looking for a method with the signaturedoSomething(int,int,int,int). Because of automatic type conversions, other compatible signatures could also includedoSomething(double,double,double,double) or evendoSomething(int,double,int,double).

Why is this somewhat obvious point worth mentioning? It’s because Java supports a feature known as overloading.Overloading occurs when two or more methods have thesame name, but specify a different order or data types forparameters. Overloading enables a single method name to bereused, so that it can be specialized for different situations.Take the drink() method from before. You could expand it toaccept an additional argument to handle more than one con-tainer. The following code overloads the drink() method:

Again, the Java runtime knows which version of the drink()method you want based on the arguments you provide. If youprovide two double arguments, then the first drink() methodis invoked. If you provide that additional int argument, thenthis second drink() method is invoked. Pages 194–199 inChapter 6 of the textbook provide further examples of methodoverloading. In the next activity, you’ll use overloaded meth-ods to modify the countdown application.

Activity 7: Create Countdown Methods

1. Open the Lesson2Activity6.java file in NetBeans.

2. Cut the following code from the main() method:

for (int i = block; i > 0; i—, counter — ) {if (counter % 2 != 0) continue;System.out.print(counter + “...”);

}

double drink(double sipAmount, double totalSize, int numContainers) {return numContainers * (totalSize - sipAmount);

}

Page 59: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java56

To cut the code, highlight the code lines and use thekeyboard shortcut CTRL+X. You can also right-click onthe selected code and choose the Cut option from thecontext menu.

3. Declare the following methods in the Lesson2Activity6class (make sure you place your cursor before the finalclosing curly brace):

4. Notice these are overloaded countdown methods. Thefirst countdown method will take three arguments sothat the countdown occurs in blocks and skips certainnumbers. The second countdown method will work onlycountdown in blocks and not skip numbers. The thirdcountdown method will simply count down withoutusing blocks or skipping numbers. The first two count-down methods return an int, so that the program cancontinue the countdown after the method returns. Thelast countdown will keep going until it reaches 1, so itreturns no value.

5. Paste the cut code into the first countdown method. Youcan use the keyboard shortcut CTRL+V or right-click inthe method and choose the Paste option from the con-text menu. Don’t worry if the paste operation failed; youcan always retype the code from step 2.

static int countdown (int counter, int block, int skip) {

}static int countdown (int counter, int block) {

}static void countdown (int counter) {

}

Page 60: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 2 57

6. Modify the code in the first countdown method as follows:

7. As you might imagine, the code for the second count-down method will be very similar. So why should yourewrite all of that code? The second countdown methodcould just call the first version, using the value of 1 forthe skip argument. This is informally called piggybacking.

8. Add the following code to the second countdownmethod:

return countdown(counter, block, 1);

9. You can do the same thing with the third countdownmethod as follows:

countdown(counter, counter);

Notice that there’s no return statement, because thethird countdown method doesn’t return a value. Byspecifying the counter argument for both the counterand block parameters, you’re allowing the countdown togo completely to 1.

10. Go back to the main() method and in the do-while block,invoke the first countdown method as follows:

counter = countdown(counter, block, 2);

11. Build and run the project. The output should match as itdid at the end of Activity 6.

12. Now, replace the code and invoke the second countdownmethod as follows:

counter = countdown(counter, block);

13. Build and run the project. The output should now matchas it did at step 4 of Activity 6.

static int countdown (int counter, int block, int skip){for (int i = block; i > 0; i—, counter — ) {if (counter % skip != 0) continue;System.out.print(counter + “...”);}return counter;}

Page 61: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java58

14. Finally, replace the code and invoke the third count-down method as follows:

countdown(counter);

15. Build and run the project. The output should now countall the way down to 1. Feel free to modify your argumentsto see how the output changes.

Page 62: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 2 59

Self-Check 5

1. Which iterative statement executes at least once?

__________________________________________________________

2. Which iterative statement uses an explicit counter?

__________________________________________________________

3. Which two statements control iterations within an iterative code block?

__________________________________________________________

4. How many return values can a method return?

__________________________________________________________

5. How many arguments are required for varargs parameter?

__________________________________________________________

Check your answers with those on page 202.

Page 63: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java60

ASSIGNMENT 6: USE ARRAYSFOR MULTIPLE VALUESRead Assignment 6 in this study guide. Then read Chapter 5,pages 136–158 in your textbook.

Assignment 6 introduces a new data type to handle multiplevalues. Be sure to complete the Try This activities 5-1 and 5-2in Chapter 5 to reinforce general use of arrays. Chapter 5also covers irregular arrays, which aren’t addressed in thisassignment.

Declare Arrays

An array is a zero-based index of common elements. In Java,arrays must meet the following criteria:

1. Each element must be the same data type.

2. Its length must be set to an int value.

3. Its length is fixed and can’t be modified.

When using arrays it’s also useful to remember that the lastindex is always one less than its length. For example, an arraywith a length of 10 elements will have elements at index posi-tions 0 through 9.

An array declaration is the same as any other variable declaration, but also includes square brackets. You mayremember that the main() method declares an array parameterto handle command-line arguments as follows:

public static void main(String[] args)

You can also declare an array by placing the square bracketsafter the variable name, but this isn’t common convention.Because arrays are objects, they must be initialized beforethey’re accessed. To initialize an array, you must use the newkeyword and specify its length in a pair of square brackets. Inthe next lesson, you’ll use the new keyword for other objectsas well.

Page 64: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 2 61

The following code declares and initializes an int array withfive elements:

int[] intArray = new int[5];

Notice the data type is repeated after the new keyword.Because an array is an object, the value for each element isset to its default. In this example, each int element is set to 0.

Using Arrays

To access elements in an array, you’ll use the square brack-ets as well. The following code sets each element in the arrayinitialized in the previous example:

intArray[0] = 1;intArray[1] = 2;intArray[2] = 3;intArray[3] = 4;intArray[4] = 5;

Of course, this code is very tedious, especially as arrays getlarger in size. You already learned about a better technique.Instead of manual code repetition, you can use a cleaneralgorithm to do the same thing with a for statement:

for (int i = 0; i < intArray.length; i++) {intArray[i] = i + 1;}

Notice the length field is used to retrieve the number of ele-ments in the array. If you need to initialize an array withvalues, you can also use another short-hand notation withcurly braces. The following code declares and initializes anarray with values using this notation:

String[] names = {“Joshua”, “Chelsea”, “April”,“Alisha”};

Java understands the number of elements based upon thenumber of provided arguments. The arguments have tomatch the data type of the array declaration, of course.

Page 65: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java62

Enhanced For Statement

When using arrays, you can choose a special type of for state-ment known as the enhanced for. The enhanced for statementwill automatically iterate across an array and retrieve eachelement without requiring an explicit index. The syntax forthe enhanced for is as follows:

for ( data_type variable_name : array_name) {//access each element in array

}

The following code will output each value in intArray usingthe enhanced for statement:

for (int intElement : intArray) {System.out.println(intElement);}

The enhanced for statement makes sense only when an index is needed to access elements. If the index is requiredfor another purpose such as modifying element values or performing a calculation, the enhanced for statement isn’tvery helpful.

Activity 8: Create a Simple Calculator

1. Create a new Java Application project namedLesson2Activity8.

2. Select the comment //TODO code application logichere and replace it with the following code:

java.util.Scanner scan = newjava.util.Scanner(System.in);

System.out.print(“Number of operands? “);double[] operands = new double[scan.nextInt()];for (int i = 0; i < operands.length; i++) {System.out.print(“\nValue “ + i + “ : “);operands[i] = scan.nextDouble();}

System.out.print(“\nOperation? “);String operation = scan.next();

Page 66: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 2 63

3. Before you run this code, take time to consider how youthink the application will behave. This code will ask for anumber of values, ask for an operation, and then returnthe result.

4. Build and run the project. Remember: Click in the Outputpanel to type input. Try doing an operation you can checkeasily to verify that it works. Test both operations.

5. Consider how you would add another operation such assubtraction or division. How would the for statement differ?

Multidimensional Arrays

Java also supports arrays with more than one index, which areknown as multidimensional arrays. Multidimensional arraysare used to represent matrices, tables, flat and 3D shapes,and image coordinates. For each dimension in a multidimen-sional array, another pair of square brackets is required. Theseextra pairs of square brackets set the length of each dimen-sion during initialization and specify the other index of eachdimension during access.

double result = 0;switch (operation.toUpperCase()) {case “ADD”:

result = 0; //Required for additionfor (double num : operands) result += num;break;

case “MULTIPLY”:result = 1; //Required for multiplicationfor (double num : operands) result *= num;break;

default:System.err.println(“\nNo such operation defined.”);

}System.out.println(“\nThe result is “ + result);

Page 67: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java64

The following code initializes a two-dimensional array andsets its first and last elements:

String[][] matrix = new String[4][5];matrix[0][0] = “first”;matrix[3][4] = “last”;

The total number of elements in a multidimensional array isthe product of elements in each dimension. If you access thelength field from a single dimension, then it will return onlythe number of elements in that single dimension. For example,matrix.length will return 4, representing the number ofdimensions, while matrix[0].length will return 5, indicatingthe number of elements in that dimension. The total numberof elements for a matrix is 20, because there are 4 dimensionswith 5 elements in each dimension.

Page 68: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 2 65

Self-Check 6

1. What are the three restrictions for arrays in Java?

__________________________________________________________

2. Which field returns the number of elements in an array?

__________________________________________________________

3. Which index value will retrieve the first element in an array?

__________________________________________________________

Check your answers with those on page 203.

Page 69: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java66

ASSIGNMENT 7: EXCEPTION HANDLINGRead Assignment 7 in this study guide. Then read Chapter 9 inyour textbook.

Assignment 7 describes how to deal with runtime errors incode.

Runtime Exceptions

An exception is an abnormal condition that occurs while anapplication is running. Most often, an exception is an error,but in some cases, the exception isn’t fatal and the applica-tion can recover. When an exception occurs, it’s thrown. Asa programmer, you can also throw exceptions manually.

If you don’t design an application to handle exceptions, then the operating system will have no choice but to termi-nate the application prematurely. Although you can avoidmany exceptions by performing simple checks, you can’t pre-dict all exceptions. Also, some methods in Java require youto plan for exceptions in order to invoke them. These types ofexceptions are known as checked and must be dealt with forthe code to compile. Exception handling is the mechanism oflistening for exceptions and dealing with them when they occur.

Exception classes take advantage of all object-oriented designprinciples. Exception objects are recoverable situations thatusually are within the control of a user or programmer, whereasError objects are system issues that aren’t recoverable andshouldn’t be handled. Both the Exception and Error classinherit core methods from the Throwable class. This meansthat all exceptions have a user-friendly message availablefrom the getMessage() method and a complete path fromwhich the exception originated with the printStackTrace()method. Java has both generalized Exception classes, suchas IOException and IllegalArgumentException, and morespecific Exception classes, such as FileNotFoundExceptionand PrintException. Tables 9-2 and 9-3 on pages 315 and316 in Chapter 9 of the textbook document the most com-mon exceptions.

Page 70: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 2 67

Exception Handling

There are four ways to deal with exceptions in a method:

1. Declare the exception thrown by the method (required ifchecked by compiler).

2. Handle the exception and continue execution.

3. Handle the exception and throw the exception again(known as re-throwing).

4. Handle the exception and throw another exception.

To declare a method throws an exception, you should use thethrows keyword as in the following example:

void couldDoSomethingVeryBad() throws Exception

The throws clause on a method means that to invoke themethod, the declared exception must be handled or alsodeclared unhandled by the invoking method. To handle theexception, you should use the try/catch blocks. Thetry/catch blocks use the following syntax:

try {//statements that might throw an exception

} catch ( exception_types exception_variable) {//handle the exceptions

}

The catch parameter can include more than one type ofexception or you can use multiple catch blocks for each typeof exception. To declare multiple exceptions in the catchparameter, use the bitwise OR operator |.

If you use more than one catch block, then be careful thatthey’re in order of specific to general or some catch blocksmay be unreachable. Every try block must have at least oneaccompanying catch block, but that catch block can be empty.To manually throw an exception, you should use the throwstatement. There’s also an optional finally block if you needto have any code run whether or not an exception is thrown.

Page 71: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java68

The following code handles any divide by zero exceptions thatare thrown and throws another exception:

A simple check for num1 so that it isn’t zero is a betterapproach than using exception handling. In a future lesson,you’ll see better uses for exception handling when performinginput/output operations.

double divide(double num1, double num2) {

double result = 0;

try {

result = num1 / num2; //num1 should not be zero

} catch (ArithmeticException ex) {

throw new IllegalArgumentException(“num2 parameter must not be 0!”);

} finally {

return result;

}

}

Page 72: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 2 69

Self-Check 7

1. What is an exception?

__________________________________________________________

2. Which blocks should you use to handle exceptions?

__________________________________________________________

3. How are the keywords throw and throws used in Java?

__________________________________________________________

Check your answers with those on page 203.

Page 73: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java70

NOTES

Page 74: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

71

Gra

de

d P

roje

ct

Gra

de

d P

roje

ct

Data Types and Program Control

OVERVIEW

After reading selected sections of Chapters 2, 5, and 9 in thetextbook and completing Lesson 2, you’re now ready to usedata types and control structures. This project will assessyour understanding of using variables, constants, operators,arrays, statements, methods, and exceptions.

Make sure to follow all directions completely and verify yourresults before submitting the project for grading. Rememberto include all required components in your solution.

Your Project

In this project, you’ll create a text-based Tic-Tac-Toe game inwhich each player places either an X or O mark on a nine-grid square. An X mark is known as a cross, while an O iscalled a nought. The winner is the first player to place theirmark on three contiguous squares vertically, horizontally ordiagonally across. You can read about it in more detail onWikipedia (http://en.wikipedia.org/wiki/Tic-tac-toe).

The output of this project will be referenced in the subsequentgraded projects for this course.

Page 75: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project72

Instructions

1. In NetBeans, create a new Java Application projectnamed TicTacToeGame.

2. Add the following variable and constant declarations tothe TicTacToeGame class:

static int[][] gameboard;static final int EMPTY = 0;static final int NOUGHT = -1;static final int CROSS = 1;

Note: The variable gameboard is a two-dimensional int array.Think of it as a table with rows and columns, where a cellcan be empty (0) or contain a nought (–1) or cross (1) . Theconstants EMPTY, NOUGHT, and CROSS will simplify yourcode.

3. Add the following utility methods to the TicTacToeGameclass:

static void set(int val, int row, int col) throwsIllegalArgumentException {if (gameboard[row][col] == EMPTY) gameboard[row][col] = val;else throw new IllegalArgumentException(“Player already there!”);}

static void displayBoard() {for( int r = 0; r < gameboard.length; r++ ) {System.out.print(“|”);for (int c = 0; c < gameboard[r].length; c++) {switch(gameboard[r][c]) {case NOUGHT:System.out.print(“O”);break;case CROSS:System.out.print(“X”);break;default: //EmptySystem.out.print(“ “);

Page 76: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project 73

}System.out.print(“|”);}System.out.println(“\n———-\n”);}}

4. Add the following method signatures to theTicTacToeGame class:

5. Define the createBoard method.

6. Define the winOrTie method. Check first for a win withrows and columns and then diagonally. Finally, check tosee if there are any empty cells without a cross or naught.

Note: Review the sections “Initializing Multidimensional Arrays”on pages 144–145 and “Iterating Over MultidimensionalArrays” on pages 156–158 for how to initialize and iteratethrough a multidimensional array. A player wins if all thecells in a row or column are the same mark or diagonallythrough the center. The players tie if all cells have a cross ornought, but no player has three marks horizontally, verti-cally, or diagonally. Return NOUGHT if nought wins, CROSSif cross wins, 0 if there’s a tie, and another value (like –2, forexample) if there are empty cells on the board.

7. In the main() method, perform the following actions:

a. Create the board and initialize a turn counter, playervalue, and game outcome. For nought, the value is–1, while 1 is the value for cross.

b. While there’s no winner or tie, display the board andprompt for a row and column for the current player.

static void createBoard(int rows, int cols) {//Initialize the gameboard

}static boolean winOrTie() {

//Determine whether X or 0 won or there is a tie}

Page 77: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project74

c. Use a try/catch block to handle the exception fromthe set method. You can use the System.err.printlnmethod rather than the System.out.println methodto output the exception. This will display the messagein red.

d. Display the final board and a message on whichplayer won or if there’s a tie.

8. When completed, the contents of the main() methodshould resemble the following:

createBoard(3,3);int turn = 0;int playerVal;int outcome;java.util.Scanner scan = new java.util.Scanner(System.in);do {displayBoard();playerVal = (turn % 2 == 0)? NOUGHT : CROSS;if (playerVal == NOUGHT) System.out.println(“\n—O’s turn—”); else System.out.println(“\n—X’s turn—”);System.out.print(“Enter row and column:”);try {set(playerVal, scan.nextInt(), scan.nextInt());} catch (Exception ex) {System.err.println(ex);}turn ++;outcome = winOrTie();} while ( outcome == -2 );displayBoard();switch (outcome) {case NOUGHT:System.out.println(“O wins!”);break;case CROSS:System.out.println(“X wins!”);break;case 0:System.out.println(“Tie.”);break;}

Page 78: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project 75

9. Compile and run the project to ensure it works asexpected. Try a few games to verify all wins and ties are correctly detected.

The application should behave as follows in the Output window:

| | | |______| | | |______| | | |______—O’s turn—Enter row and column:0 0|O| | |______| | | |______| | | |______—X’s turn—Enter row and column:0 1|O|X| |______| | | |______| | | |______—O’s turn—Enter row and column:1 1|O|X| |______| |O| |______| | | |______

—X’s turn—Enter row and column:2 0|O|X| |______| |O| |______|X| | |

Page 79: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

______—O’s turn—Enter row and column: 2 2.|O|X| |______| |O| |______|X| |O|

O wins!

SUBMISSION GUIDELINES

To submit your project, you must provide the following two files:

■ TicTacToeGame.java

■ TicTacToeGame.class

To find these files within NetBeans, go to the TicTacToeGameproject folder. To determine this folder, right-click onTicTacToeGame project in the Projects panel. Copy thevalue for the Project Folder textbox using the keyboardshortcut CTRL+C. In Windows Explorer, paste the projectfolder path and hit the ENTER key. Copy both theTicTacToeGame.java file from the src\tictactoegame folderand the TicTacToeGame.class file from the build\tictac-toegame folder to your desktop or any other temporarylocation.

Follow this procedure to submit your project online:

1. Log on to the Penn Foster website and go to My Courses.

2. Click Take Exam.

3. Attach your files as follows:

a. Click on the Browse box.

b. Locate the file you wish to attach.

c. Double-click on the file.

d. Click Upload File.

Graded Project76

Page 80: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project 77

e. Since you have more than one file to attach, click onthe Browse box again, and repeat steps b, c, and dfor each file.

4. Enter your e-mail address in the box provided. (Note:This information is required for online submissions.)

5. If you wish to tell your instructor anything specificregarding this assignment, enter it in the Message box.

6. Click Submit File.

Grading Criteria

Your instructor will use the following guidelines to grade your project.

The createBoard method works as required: 25 points

The winOrTie method works as required: 30 points

The application plays a standard Tic-Tac-Toe game 25 points

Both source and compiled code files are included: 20 points

TOTAL 100 points

Page 81: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project78

NOTES

Page 82: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

79

Le

ss

on

3L

es

so

n 3

Object-OrientedProgramming

INTRODUCTION

Because Java is an object-oriented language, learning itsstructures will provide a review of object-oriented program-ming (OOP). Java was built with good object-oriented designprinciples in mind, making it easier to do the right thing, butmore restrictive than other languages you’ve learned. In thislesson, you’ll define classes, interfaces, and enumerations andrevisit important OOP concepts such as inheritance and poly-morphism. You’ll also learn how to use Java’s packagingscheme and generics.

OBJECTIVES

When you complete this lesson, you’ll be able to

■ Define and instantiate classes

■ Describe reference variables and the object lifetime

■ Use inheritance and polymorphism

■ Differentiate between abstract and concrete classes

■ Use Java packages and the application programminginterface (API) documentation

■ Differentiate between interfaces and classes

■ Create interfaces and enumerations

■ Discuss autoboxing and generics

Page 83: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java80

ASSIGNMENT 8: CREATE OBJECTS AND CLASSESRead Assignment 8 in this study guide. Then read Chapter 4,pages 104–110 and 124–134, as well as Chapter 6 in your textbook.

Create Objects and Classes

The focus of Assignment 8 is using OOP with Java syntax.This assignment assumes you have a good grasp of generalobject-oriented design principles. If you need a refresher onobject-oriented design, you can read the Java tutorial on theOracle website at http://docs.oracle.com/javase/tutorial/java/concepts/index.html. Be sure to complete the Try Thisactivities in both Chapters 4 and 6; they’ll help to reinforcethe syntax and concepts.

Object Fundamentals

As you’ve learned in previous lessons, an object is a uniquerepresentation of variable-sized data in memory. This dataconsists of two things: state and behavior. State describes theobject, while behavior defines what that object can do. Theword unique means one object is stored separately fromanother, even if they have the same state. In Java, state isdefined by variable fields, while behavior is defined by methods.

A class is a user-defined type that describes objects.Although a class is loaded into memory like objects, a classdoesn’t have a unique state or behavior. Only static fieldsand methods are available through a class. Any changes tothe class will affect all objects based on that class, however.Think of a class as a group and objects as members of thatgroup. A class is merely a classification for a type of object.

An important object-oriented design principle is encapsulation.Encapsulation is designing a class, so that fields are pro-tected from direct access and all interaction with an objectrequires methods. A method that retrieves a field’s value isknown as an accessor. A mutator is a method that modifies a field’s value.

Page 84: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 81

Class Definition in Java

The following code defines the Robot class in a two-dimensionalmaze application:

class Robot {//fields (state)String name;int x,y;int direction;double speed;//methods (behavior)void turn(int direction) {}void move(double time) {}void move(double time, int direction) {}void setSpeed(double speed) {}

}

Note the use of the class keyword to specify the new datatype. The fields are merely variables declared directly in theclass body. It’s worth mentioning that the methods don’t usethe static keyword as you were using in the previous lessonbecause the methods will affect a single object. If you invokethe move() on a Robot object, another Robot object won’thave its x and y fields change.

The process of creating an object from a class is known asinstantiation. As with arrays, you need to use the new key-word to instantiate a class. You’ll use parentheses instead ofsquare brackets, however. The following code instantiates theRobot class twice to create two Robot objects and then setseach of their fields:

Robot robo1 = new Robot(); robo1.name = “Marvin”;robo1.speed = 4.2;Robot robo2 = new Robot();robo2.name = “Chip”;robo2.speed = 12.8;robo1.move(10);robo2.move(5);

Notice that dot notation is used to access object fields andmethods. Also, notice that the robo1 and robo2 objects haveseparate field values and methods. When the move() method

Page 85: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java82

is invoked on robo1, robo2 remains in its current state.While the move method is invoked for robo2, the state forrobo1 is unaffected.

Another important point is the default state of the Robotobjects. All fields will start with their default values. Becausethe x, y and direction fields aren’t set, their current state is0, 0 and 0.0, respectively.

Object References

As you’ll recall from the first assignment in the previous lesson,assigning a variable to another simply copies the original valueand assigns it to the second variable. The following codedemonstrates this concept:

Values for primitive data types are stored on the defaultmemory stack. The only data stored for a primitive variable is its value.

Because the size of object data isn’t fixed, objects are storedin the memory heap. The size of an object is determined whenit’s instantiated, not using a size predefined by the JVM. Ifobject data is stored in the memory heap, then what’s storedin the memory stack?

A reference to the object is stored on the memory stack.Think of a reference as a pointer to that object’s data. Thismeans that a simple assignment operation for primitive datatypes is actually a powerful reference mechanism for objects.

Note: Java providesthe transient keywordfor fields to indicatethey don’t need to bestored with an objectbecause their valuesdon’t affect that object’sstate. The result of thetransient keyword isapparent only whenusing serialization.

int i1 = 10;int i2 = i1; //now i2 is 10i2++; //i2 is now 11, but i1 is still 10

Page 86: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 83

Look at the following modified code that uses the Robot objects:

Robot robo1 = new Robot();Robot robo2 = robo1;

robo1.name = “Marvin”;robo1.speed = 4.2;

robo2.name = “Chip”;robo2.speed = 12.8;

System.out.println(robo1.name + “ “ +robo1.speed);System.out.println(robo2.name + “ “ +robo2.speed);

The output would be the following:

Chip 12.8Chip 12.8

This output may seem surprising until you realize that thevariables robo1 and robo2 reference the same object. Theassignment operation between objects doesn’t merely copyfield values, but copies the pointer to the object from one to another.

The same principle applies to passing arguments to parameters.When passing an object as an argument, any modifications tothe object will persist after the method returns. Unless this isthe desired effect, you may prefer to copy the object’s values andspecify a copy of the original object as an argument instead.

Class Members

By default, all fields and methods declared in a class willaffect only a single object. These constructs are known asinstance members. To access instance members, you mustinstantiate that class first and then access those membersthrough the object reference using dot notation. The previouscode examples demonstrate this type of access.

If you declare a field or method with the static keyword, thenthat field or method is now a class member. Setting classfields or invoking class methods will affect every object of theclass. To access class members, you need only reference the

Page 87: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java84

class itself in dot notation. As you may recall from the firstlesson, the reason the main() method uses the static key-word is so that the Java runtime isn’t required to instantiatethe class first. Only the class is loaded, not any of its objects.

Continuing our Robot class example, the following classmembers could be added:

static int totalRobots;static void stopAllRobots() {}To access these class members, you can use the class or anobject of the class. For clarity, the preferred convention is toaccess class members using the class and not its objects. Thefollowing code accesses class members of Robot using bothtechniques:

Robot.stopAllRobots(); //preferrednew Robot().stopAllRobots();

Access Modifiers

Access modifiers are keywords that determine the visibility of members to other classes. The two most common accessmodifiers are public and private. A member declared withthe public keyword is available to all other classes, while amember declared with the private keyword is available onlyin that class.

Access modifiers are important tools for good encapsulation.Most fields should be declared as private, while associatedaccessor and mutator methods should be declared as public.By limiting availability to fields, you’re ensuring that otherclasses must use methods, rather than direct access. Thislimitation ensures that an object’s state is consistent andhidden from unnecessary modifications by other classes. Theonly exception to using private on fields is constants or othervalues that are required by other classes and don’t affect anobject’s internal state.

Page 88: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 85

You would modify members of the Robot class to use goodencapsulation as follows:

private String name;private int x,y;private int direction;private double speed;private static int totalRobots;

//accessorspublic String getName() {

return name;}public Point getCoordinates() {

return new Point(x,y);}public double getSpeed() {

return speed;}public int getTotalRobots() {

return totalRobots;}//mutatorspublic void setName(String name) {this.name = name;}public void setSpeed(double speed) {this.speed = speed;}//functional methodspublic void turn (int direction) {}public void move(double time) {}public void move(double time, int direction) {}public static void stopAllRobots() {}The keyword this is used to reference the current runninginstance. When using a mutator, it’s common to name theparameter the same name as the field. To differentiatebetween the two variables, use the this keyword to referencethe field and not the parameter. Pages 132–134 in Chapter 4of the textbook detail this usage.

Note: The keyword thisis used to reference thecurrent runninginstance.

Page 89: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java86

The previous example code that instantiates Robot objectswill now need to be rewritten as follows:

Robot robo1 = new Robot();Robot robo2 = new Robot();robo1.setName(“Marvin”);robo1.setSpeed(4.2);robo2.setName(“Chip”);robo2.setSpeed(12.8);Notice the impact of accessor and mutator methods on how fields are used outside the class. If you provide a publicaccessor method for a private field, then the field becomeseffectively read-only outside of the class. If both public muta-tor and accessor methods are provided, then the field iseffectively read/write outside of the class. If no accessor ormutator method is provided, then the field is completelyinternal and unavailable outside the class.

Any calculation methods that are used only internally shouldalso be declared private. Only those functional methods thatmust be exposed to other classes should be declared public.Java also provides two other access levels to provide granu-larity between private and public. The protected keyword isthe same as using private, but with the addition of visibilityto subclasses. If no access modifier is specified, then thedefault access is package level. With package level, the mem-ber is visible only to those classes within the same package.Inheritance and packages will be discussed in the nextassignment.

Classes can also control their own visibility, but the languagerestricts access to only two levels: package level and public. Bydefault, NetBeans declares all classes with the public keyword.Only nested classes can also use the private and protectedkeywords.

Note: You can define more than one class or other data typewithin a single source file. But only one of those types can be declared with the public keyword, and the filename mustmatch the name of that public data type. Using an IDE likeNetBeans that organizes applications into projects makes iteasier to use different source code files for each data type. It’sa common practice to define more than one data type in asource file if only a text editor like Notepad or TextPad is used.

Page 90: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 87

Construction and Finalization

Within its lifetime, an object undergoes the following phases:

■ Referenced

■ Instantiated

■ Initialized

■ Used

■ Dereferenced

■ Finalized

■ Deleted

In the referenced phase, a variable is either declared orunderstood by the runtime to store a class pointer to theobject. The class must be loaded to determine the referencetype. The instantiated phase begins when the new keywordis used. In this phase, the space in the memory heap isreserved for the object.

The next phase is initialized. When an object is initialized, its default values are set on its fields. During the initializedphase, a specialized method called a constructor is invoked.A constructor method uses the same name as the class andimplicitly returns an object of that class. If you’re confusedwhy you haven’t seen a constructor yet, it’s because the com-piler automatically provides a default constructor to a class ifno constructors are found. The default constructor has noparameters and an empty body.

For example, the Robot class has the following default constructor:

Robot() { }

You can do so much more with a constructor. Constructorscan accept user-defined default values for an object’s fieldsand perform initial calculations or actions during object cre-ation. Like methods, constructors can also be overloaded. Toreference another overloaded constructor, use the this key-word as you would when referencing instance fields.

Note: The access modi-fier for the defaultconstructor matchesthe access modifier ofthe class. If the Robotclass was declaredpublic, then the defaultconstructor wouldinclude the publickeyword.

Page 91: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java88

The following code demonstrates overloaded constructors forthe Robots class:

Note: Most constructors are public or package level. Someconstructors are private to prevent instantiation by otherclasses. The Math class is a good example of this. Althoughthe Math class provides useful constants and methods, thisfunctionality isn’t dependent on instance fields or methods.Because instantiation isn’t required to use the class, theclass prevents instantiation.

Although this may seem like a lot of work when writing a class,it greatly simplifies object creation down the road. Instead ofmanually initializing fields or using mutator methods, youcan now create an object with all of the values you need witha single line of code:

Robot robo1 = new Robot(“Marvin”, 4.2);Robot robo2 = new Robot(“Chip”, 12.8);

You might be wondering if there’s a way to perform initializationon class fields when a class is loaded, similar to how instancefields are initialized using constructors. Pages 209–213 ofChapter 6 in the textbook describe how to use the staticblock for this purpose.

public Robot() {//invokes 2nd constructorthis(“Unnamed”);}public Robot(String name) {//invokes 3rd constructorthis(name,0);}public Robot (String name, double speed) {//invokes 4th constructorthis(name,speed,0,0);}public Robot (String name, double speed, int x, int y) {//workhorsethis.name = name;this.x = x; this.y = y;this.speed = speed;totalRobots++;}

Page 92: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 89

An object is in the used phase until the last variable that ref-erences it goes out of scope. When that happens, the object isnow dereferenced. Dereferenced means that there are no livepointers to the object, and the space it occupies in memorycould be used for other data.

In some runtime environments, you would then need to per-form the operations to delete the object from memory andreclaim it for usage with other objects. Provided by the JVM,an automated service known as the garbage collector performsthis deletion and reclamation for you. The garbage collector“takes out the garbage” only when there’s a significantamount of memory being consumed by dereferenced objects.This is especially the case when available system memory isbelow what’s required for Java applications.

Because you can’t plan for when the garbage collector performsits work, you can use the finalize() method for any opera-tions that must be done before the object is removed. Whenthe finalize() method is executed by the garbage collector,the object is now in the finalized phase immediately before dele-tion. Once an object is in the deleted phase, its memory canbe reclaimed for other objects.

Activity 9: Create a Class and Use Constructors

1. Create a new Java Application project namedLesson3Activity9 in NetBeans.

2. Create a new public class named Polygon in the project.

a. You can either right-click on the Lesson3Activity9project or choose New > JavaClass … in the contextmenu by right-clicking the Lesson3activity9 pack-age in Projects or use the CTRL+N keyboardshortcut and choose Java Class in the File Typespane and click the Next button (Figure 7).

b. In the Class Name text box, type Polygon and in thePackage drop-down list, choose lesson3activity9.

c. Click the Finish button.

Page 93: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java90

3. First, create a non-encapsulated class. Inside thePolygon class add the following code:

4. Open the Lesson3Activity9.java file. You can do thiseither by clicking its tab at the top of Documentsbecause it should be open or by double-clicking theLesson3Activity9.java file in the Projects pane.

String id;int numSides, lenSides;void printInfo() {System.out.print(id + “: “);System.out.println(numSides + “ sides with length of “ + lenSides);}

FIGURE 7—Create a New Class

Page 94: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 91

5. In the main() method of the Lesson3Activity9 class,add the following code and consider what the outputshould be for this code.

Polygon triangle = new Polygon();Polygon square = new Polygon();Polygon octagon = new Polygon();triangle.id = “triangle1”;triangle.numSides = 3;triangle.lenSides = 5;square.id = “square1”;square.numSides = 4;square.lenSides = 3;octagon.id = “octagon1”;octagon.numSides = 8;octagon.lenSides = 10;triangle.printInfo();square.printInfo();octagon.printInfo();

6. Build and run the project. Did the output match your expectations?

Notice how the code in the main() method is lengthy andrequires significant understanding of the Polygon class. Also,the Polygon class doesn’t provide much functionality or cal-culations that could be helpful when using polygons. In thenext section, you’ll modify the Polygon class to use properencapsulation and store a polygon’s perimeter and area.

7. Open the Polygon.java file. You can open the file eitherby clicking its tab at the top of Documents because itshould be open or by double-clicking the Polygon.javafile in the Projects pane.

8. Modify the code in the Polygon class as follows:

private String id;private int numSides, lenSides;

//calculated fieldsprivate int perimeter;private double area;

//internal calculations

Page 95: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java92

private void calculatePerimeter() {

perimeter = numSides * lenSides;

}

private void calculateArea() {//Uses the Math class

double numerator, denominator;

numerator = Math.pow(lenSides, 2) * numSides;

denominator = 4 * Math.tan(Math.toRadians(180/numSides));

this.area = numerator / denominator;

}

//accessor/mutators

public String getID() { return id; }

public void setID (String id) { this.id = id; }

public int getSides() { return numSides; }

public int getSideLengths() { return lenSides; }

public int getPerimeter() { return perimeter; }

public double getArea() { return area; }

public Polygon(String id, int numSides) {

this(id, numSides, 1);

}

public Polygon(String id, int numSides, int lenSides ) {

this.id = id;

if (numSides < 3)

throw new IllegalArgumentException(“Polygon must have at least 3 sides!”);

this.numSides = numSides;

if (lenSides < 1)

throw new IllegalArgumentException(“Polygon must have sides greater than 0!”);

this.lenSides = lenSides;

//perform calculations

calculatePerimeter(); calculateArea();

}

public void printInfo() {

System.out.print(id + “: “);

System.out.println(numSides + “ sides with length of “ + lenSides);

System.out.println(perimeter + “ perimeter with area of “ + area);

}

Page 96: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 93

Now your code in the main() method would be significantlysimplified and more information is available from thePolygon class. In the next section, you’ll replace the main()method code to use the improved Polygon class.

9. Open the Lesson3Activity9.java file. You can do thiseither by clicking its tab at the top of Documentsbecause it should be open or by double-clicking theLesson3Activity9.java file in the Projects pane.

10. Notice all of the red squiggly lines in the main() method!Because Polygon no longer has a default constructorand its fields are now hidden from other classes, thereare a significant number of compilation errors!

11. Modify the code in the main() method as follows:

Polygon triangle = new Polygon(“triangle1”, 3, 5);Polygon square = new Polygon(“square1”, 4, 3);Polygon octagon = new Polygon(“octagon1”, 8, 10);

//all other main() code is deleted

triangle.printInfo();square.printInfo();octagon.printInfo();

12. Build and run the project. The output should nowinclude the perimeter and area of each polygon. Feel free to build some more Polygon objects in the main()method, so that you can become more familiar withinstantiating and using well-encapsulated classes.

Nested Classes

Although sparingly used, Java allows you to define a classwithin another class. The inner class is known as a nestedclass. This capability is intended for the rare circumstancewhere a class is completely dependent on another class andincreased encapsulation could reduce complexity. Whenusing AWT and Swing, you’ll see some examples of nestedclasses, even anonymous ones!

Page 97: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java94

Sometimes a nested class indicates that an object containsanother object. In other scenarios, a nested class is simplya class placed within another because it needs access tounavailable fields or methods. The first situation describesnon-static nested classes, while the second describes a staticnested class. As you might expect, a static nested class isdeclared using the static keyword.

Here is an example of a non-static nested class:

public class Polygon {Side[] sides;public class Side {

int length, angle;}

}

Note: Although nested classes are often intended to providefurther encapsulation, the code above is a poor example ofgood encapsulation. The example is intended to simplify thesyntax. If this were encapsulated better, then the fields wouldbe private, and public accessors and mutators would bedefined in both the outer and inner classes.

In this example code, the class Polygon has an inner classnamed Side. Notice that the Polygon class references theSide class using an array. The nested class then representsthe relationship that a polygon contains many sides.

How do you access an inner non-static class? Because theinner class is dependent on objects of the outer class, youmust first instantiate the outer class and then instantiate the inner class. As you might imagine, this situation createssome unusual-looking code when using dot notation.

This code creates a Side object:

Polygon.Side side1 = new Polygon().new Side();

The declaration of the side1 variable makes sense, because aSide object is nested within the Polygon class. But the portionon the right side of the assignment seems very bizarre. It’s for good reason. Java initially didn’t support inner classes, sothe existing instantiation syntax was reused to accommodatethe new feature.

Page 98: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 95

If the Side class was declared as a static nested class ofPolygon by adding the static keyword, the syntax is more logical and easier to read:

Polygon.Side side1 = new Polygon.Side();

If you’re unsure when you’ll define nested classes, the answeris probably rarely if ever. But you’ll find yourself using nestedclasses when handling GUI elements and events.

Page 99: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java96

Self-Check 8

1. What is the difference between object references and primitive types?

__________________________________________________________

2. What is object encapsulation?

__________________________________________________________

3. What is the difference between instance and class members?

__________________________________________________________

4. When is a class instantiated? When is an object finalized?

__________________________________________________________

Check your answers with those on page 204.

Page 100: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 97

ASSIGNMENT 9: CREATE CLASSINHERITANCE AND PACKAGES Read Assignment 9 in this study guide. Then read Chapter 7,Chapter 8, pages 268–278, and Chapter 12, pages 427–429, inyour textbook.

Assignment 9 addresses how to inherit code from classes,class hierarchies, and Java packages. Be sure to completethe Try This activities in Chapters 7 and 8; they’ll help rein-force the syntax and concepts.

Classes and Subclasses

As described in the previous assignment, classes can bethought of as ways of classifying like objects. As with mostclassification schemes, objects can become more and morespecialized based upon the class in which they belong.Extending the previous example of a Robot class, you couldhave specific types of robots based on algorithm such as aBinarySearchRobot, on function such as a CarDriverRobot,or on built-in capabilities such as a CameraRobot. Althoughall of these classes are different and represent unique sets ofobjects, they also share state and behavior mechanisms. Forexample, all of these robots can move at a certain speed andcan be tracked using x and y coordinates.

Inheritance describes how subclasses can reuse code fromthe same class. The subclass is the one that’s specialized,while the superclass is the generalization. To take advantageof inheritance in Java, you use the extends keyword whendeclaring the subclass. Only single inheritance is supported inJava, so that a subclass can have only one direct superclass.

The following code declares a subclass of the Robot class:

public class CameraRobot extends Robot {private boolean pathBlocked;private int cameraDirection;public boolean isPathBlocked() {return pathBlocked;}public int getCameraDirection() {

Page 101: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java98

return cameraDirection;}public void turnCamera(int cameraDirection) {this.cameraDirection = cameraDirection;}}

You may not see it, but code inside the Robot class is nowautomatically part of the CameraRobot class because of theextends keyword. The CameraRobot class only needs to con-tain code that specializes it as a subclass.

There’s also a wider implication when considering object references. Any CameraRobot objects are now typed not onlyby the CameraRobot class, but also by the Robot class. Thecompiler will allow you to declare variables of type Robot andthey can reference both Robot and CameraRobot objects!

The following code demonstrates the specialization principleof subclasses:

CameraRobot cbot1 = new CameraRobot();Robot cbot2 = new CameraRobot();

The difference between these two object references will bediscussed in the Polymorphism section.

What Is Inherited?

When defining a subclass, it’s important to realize that noteverything is inherited. All fields and methods, both classand instance members are inherited. Constructors, however,aren’t inherited from the superclass. When a subclass construc-tor is invoked, an associated superclass is invoked implicitly.Since a subclass is a specialized type of its superclass,instantiation of a subclass must, by definition, instantiate thesuperclass as well. Therefore, you’ll need to copy the sameconstructors over to the subclass if you wish to offer thesame initialization functionality provided by the superclass.Although superclass instantiation occurs automatically, youshould use the super keyword to invoke superclass construc-tors and increase code reuse. To access fields, and methodslocated in the superclass, you can also use the super keywordin place of the this keyword.

Note: An explicit invo-cation to superclassconstructor must bethe first line within asubclass constructorbecause the superclassmust be instantiatedbefore the subclass.

Page 102: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 99

The following code contains the constructors for theCameraRobot subclass:

Of the items that are inherited, not every one is available to the subclass. Availability depends on access modifiers. Ifaccess is the default package level, then only subclasses inthe same package will have access to those members. If thekeyword protected was used, then subclasses in whicheverpackages they’re located will have access to those members.Even in subclasses, members declared with the private key-word aren’t accessible.

It may seem odd to inherit members that are inaccessible,but this is actually very common among real-world objects.Although you may inherit traits from your mother or father,many of those traits aren’t available for modification. For better or worse, you’re stuck with them!

Overriding Methods

Subclasses can do more than overload superclass methods;they can override them. As you recall from the previous lesson,the method signature is how the runtime figures out whichmethod should be invoked. In overloading, more than onemethod has the same name, but specifies a different order

public CameraRobot() {this(“Unnamed”);

}public CameraRobot(String name) {

this(name,0);}public CameraRobot (String name, double speed) {

this(name,speed,0,0);}public CameraRobot (String name, double speed, int x, int y) {

this(name, speed, x, y, 0);}public CameraRobot (String name, double speed, int x, int y, intcameraDirection) {

super(name,speed,x,y);pathBlocked = false;this.cameraDirection = cameraDirection;

}

Page 103: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java100

of data types for parameters. In overriding, a subclass canuse the same name and order of parameter data types as amethod in the superclass. This means that the subclass ver-sion of the method effectively replaces the method version inthe superclass.

The following method in the CameraRobot class overridesthe move() method in the Robot class:

@Overridepublic void move(double time) {//check if the path is blocked}

Note: The previous code uses the @Override annotation, whichis used by the compiler to check that the method signaturematches a method in the superclass. Not all annotationsare useful during development, but the @Override annotationis essential to making sure you override instead of overloada superclass method. Annotations are introduced onpages 430–432 in Chapter 12 of the textbook.

How does the runtime know which version of the move() methodis intended? Not surprisingly, the runtime chooses the versionbased on which class the object instantiated. If you invokemove() on a Robot object, then its version is executed. If youinvoke the move() on a CameraRobot object, then themove() method defined in that class is executed.

As you recall from the previous lesson, the final keyword is used in Java to declare constants. The final keyword canalso be used in inheritance. A method declared with the final keyword can’t be overridden by subclasses. If a class isdeclared with the final keyword, then it can’t have subclassesat all. Some built-in classes provided by Java are declared asfinal, because all or most of their methods are so complex,that inheritance isn’t recommended.

Although not recommended at all, you can use subclass hidingto replace fields and methods inherited from a superclass.Hiding is the process of using syntactic loopholes to preventthe side effects of normal inheritance. To hide a field, simplydeclare a field in the subclass as it’s named in the superclass.Because static methods can be accessible from instances asyou learned in the previous assignment, you can also hide a

Page 104: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 101

superclass method by using the same method signature withthe static keyword in the subclass. Polymorphism, as describedin the next section, doesn’t apply to hidden class methods,only overridden instance methods.

It makes sense in the Robot example scenario to use methodoverriding. A regular Robot object has no sensors to detectits surroundings, while a CameraRobot object can actually seeand verify whether its path is blocked. But if you find your-self overriding a majority of methods, you may want toreconsider whether inheritance is a good idea. If most of theinherited code is being replaced, then why inherit it in thefirst place? A better choice might be an interface, as you’lllearn in the next assignment.

Object References and Polymorphism

Now, revisit the following example code:

CameraRobot cbot1 = new CameraRobot();Robot cbot2 = new CameraRobot();

Although both lines of code instantiate a CameraRobot object,the first line uses a CameraRobot object reference and thesecond line uses a Robot object reference. Using the cbot1variable will provide access to the members in theCameraRobot and Robot classes. This makes sense becausethe CameraRobot class is a subclass of Robot and it inheritsits members.

The cbot2 variable is more limited, however. Because thisvariable is a Robot object reference, only those members inthe Robot class are accessible. The cbot2 variable does pointto a CameraRobot object, so you could use casting to getaccess to CameraRobot members. The following code demonstrates the technique:

CameraRobot cbo2AsCameraRobot = (CameraRobot) cbot2;

Now, take the following example code:

Robot bot1 = new Robot();Robot bot2 = new CameraRobot();

Page 105: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java102

Unlike the previous example, bot1 and bot2 use the sameobject reference type, but point to different types of objects.The variable bot1 references an object of the superclassRobot, while variable bot2 references an object of the sub-class CameraRobot. Because both variables are using theRobot class as the object reference, only those members inthe Robot class are accessible.

With what you’ve learned so far about object references, whatdo you think will happen when the following code is run?

bot1.move(2.8);bot2.move(5.4);

Surprisingly, when dealing with overridden methods, the ref-erence type of the variable has no effect on which version ofthe move() method is executed. The move() method definedin the Robot class is executed for bot1, while the version inthe CameraRobot class is executed for bot2. This result isknown as polymorphism. In polymorphism, the actualmethod that’s executed depends on the type of the object, notthe reference type of its variable.

The Object Class

In Java, even if you don’t use inheritance, every class is asubclass of the Object class. What this means is that everyclass has built-in functionality inherited from the Objectclass. Thus, you can invoke the getClass() on any object andit will return a reference to its class. The table on page 265 ofChapter 7 in the textbook lists all methods inherited from theObject class.

There are three methods that you’ll commonly override in yourclasses: toString(), equals(), and hashCode(). The toString()method is intended to provide a text representation of anobject for quick output. You’ve used the equals() methodbefore with String objects. The equals() method returns aboolean value indicating whether the current object and anobject argument are equivalent. If you choose to override the equals() method, you must also override the hashCode()method. The hashCode() method returns an int value thatshould be the same if two objects are equivalent.

Note: You can use theinstanceof operator toverify whether anobject is an instance of a specified class.This is preferred beforeperforming a referencetype cast.

Page 106: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 103

The following code overrides the toString() method for theRobot class:

Remember: Because it’s a subclass of Robot, the CameraRobotclass also inherits the overridden toString() method.

Abstract Classes

There will be some situations where a class is intended only forgeneralizing a group of classes and instantiation doesn’t makesense. Although there are many methods in the superclassthat won’t be overridden, some methods may be overriddenby every subclass. In other words, these method signaturesmay be the same across classes, but the actual code definedin each method will be different.

One solution to this problem is an abstract class. An abstractclass is one that can’t be instantiated and can include methodswithout definition code. The class is declared with the abstractkeyword and each method that isn’t defined must also includethe abstract keyword. Although an abstract class can’t beinstantiated, it can include constructors that subclasses can invoke.

The following code defines an abstract class namedMovableMachine:

public abstract class MovableMachine {private int x,y;private int direction;private double speed;public Point getCoordinates() {

return new Point(x,y);}public double getSpeed() {

return speed;}public void setSpeed(double speed) {

this.speed = speed;}

@Overridepublic String toString() {

return name + “at “ + x + “, “ + y + “ with speed of “ + speed;}

Page 107: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java104

//abstract methodspublic abstract void turn (int direction);

public abstract void move(double time);}

Because an abstract class can’t be instantiated, subclassesare required for actual usability. Subclasses of an abstractsuperclass are known as concrete classes, because they mustprovide the definition of all abstract methods. This require-ment to provide definition for abstract methods is known as acontract. If a subclass doesn’t provide definition for abstractmethods, then that subclass also must be declared abstractand rely on its own subclasses to provide those definitions.

Activity 10: Create an Abstract Class and Subclasses

1. Launch NetBeans and open the Lesson3Activity9 proj-ect if you’ve closed out of the NetBeans.

2. Create a new public class named Shape in the project.Review step 2 of Activity 9 if you need help performingthis action.

3. The Shape class should be defined as follows:

public abstract class Shape {private String id;//calculated fieldsprotected int perimeter;protected double area;public Shape(String id) {this.id = id;}//accessor/mutatorspublic String getID() { return id; }public void setID (String id) { this.id = id; }public int getPerimeter() { return perimeter; }public double getArea() { return area; }//internal abstract calculationsprotected abstract void calculatePerimeter();protected abstract void calculateArea();public void printInfo() {System.out.print(id + “: “);}}

Page 108: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 105

Notice the area and perimeter fields and calculatePerimeter()and calculateArea() methods are now declared with the protected keyword. Why is that required?

4. Open the Polygon.java file either by clicking its tab atthe top of Documents because it should be open or bydouble-clicking the Polygon.java file in the Projectspane.

5. Modify the Polygon class declaration to inherit from theShape class as follows:

public class Polygon extends Shape

6. Because the Polygon class now inherits code from theShape class, you need to remove the id, perimeter, andarea fields and getID(), setID(), getPerimeter(), andgetArea() methods.

7. Because the calculatePerimeter() and calculateArea()methods are declared with the protected keyword in theShape class, you need to change the private keyword toprotected on these methods in the Polygon class.

8. Replace the statement this.id = id; in the secondPolygon constructor with the statement super(id);

9. Replace the statement System.out.print(id + “: “); in theprintInfo() method with the statement super.printInfo();

10. Open the Lesson3Activity10.java file and modify thefirst four lines in the main() method as follows:

Shape triangle = new Polygon(“triangle1”, 3, 5);Shape square = new Polygon(“square1”, 4, 3);Shape octagon = new Polygon(“octagon1”, 8, 10);Shape hexagon = new Polygon(“hexagon1”, 6, 5 );

11. Build and run the project. The output should match theoutput at the end of Activity 9.

The reason this code works is because of polymorphism.In the next section, you’ll add another subclass of Shapenamed Circle.

12. Create a new public class named Circle in the project.

Note: You could copyand paste the codefrom the Polygon.javafile and modify it,rather than retyping itall. Remember the key-board shortcuts areCTRL+C for copy andCTRL+V for paste.

Page 109: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java106

13. The Circle class should be defined as follows:

14. Open the Lesson3Activity9.java file and add the follow-ing code to the main() method:

Shape circle = new Circle(“circle1”, 5);

circle.printInfo();

15. Build and run the project. You should now have bothPolygon and Circle objects using the Shape class andthrough polymorphism displaying the correct results!

public class Circle extends Shape {private int radius;protected double perimeter; //hides Shape fieldpublic Circle(String id, int radius) {

super(id);this.radius = radius;calculatePerimeter();calculateArea();

}//accessors/mutatorspublic int getRadius() { return radius; }public int getDiameter() { return 2 * radius; }//calculationsprotected void calculatePerimeter() {

perimeter = 2 * Math.PI * radius;}protected void calculateArea() {

area = Math.PI * Math.pow(radius, 2);}public void printInfo() {

super.printInfo();System.out.println(“radius of “+ radius);System.out.println(perimeter + “ perimeter with area of “ + area);

}}

Page 110: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 107

Define a Package

To avoid naming conflicts between classes and other types,Java uses a unit of organization known as a package. Apackage groups related types into a logical namespace. Eachpackage can in turn have sub-packages, so that the result isan organized hierarchy of data types.

Rather than requiring a complex name for a class such asPokerGamePlayingCardDeck, you could create a packagewith the name games.poker.cards and simply rename theclass Deck. In the package games.poker.cards, you wouldexpect to find other card-related classes used in a pokergame, such as Card, PlayerHand, DealerHand, and River.Because the dot-notation includes other packages (games,games.poker), you would expect to find a more generalPlayer class in the games package and perhaps a Bet classin the games.poker class.

To define a package, you must perform two actions:

1. Use the package statement in all related source code files.

2. Place the source code files in the same folder structurerequired for the package.

All source code files in the same package should include apackage statement with that name. The following is an examplepackage statement for the Robot and CameraRobot classes:

package games2d.maze;

The package statement must be the first line of executablecode. This means that comments and annotations can pre-cede the package statement, but no other elements. Commonconvention is to use all lowercase letters for package names,but all other characters allowed in Java identifiers can alsobe used.

If no package statement is included in a source code file,then the data type(s) in the source code file are placed in thedefault package. The default package is global level, meaningthat no package name is required to access the data type(s).If a package statement is included, then the package name isautomatically prepended to the data type name(s). With the

Page 111: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java108

package statement above, the full names of the Robot andCameraRobot classes are now games2d.maze.Robot andgames2d.maze.CameraRobot.

Finally, you must place the source code files in the package inthe same folder structure as indicated in the package state-ment. That means for the Deck class in thegames.poker.cards package, you need to move theDeck.java file into the \games\poker\cards folder. For thefiles Robot.java and CameraRobot.java, you need to movethem into the \games2d\maze folder. After compiling thefiles, the compiled files (.class) should also remain in thisfolder structure or be compressed into a self-contained JARfile. Remember: Java package names are case-sensitive, soyou should make sure the folder names are all lowercase aswell.

The location of these package folders must be specified in theCLASSPATH environmental variable if running the files man-ually on the command-line using the java executable. Thisdevelopment environment can be tedious and error-prone.

Luckily, the NetBeans IDE automates the creation, compila-tion, and running of packages. Each project you’ve developedin NetBeans is part of a package with the same name as yourproject, but in all lowercase. To create a new package, eitherchoose New > Java Package … in the context menu whenright-clicking on the Source Packages folder in Projects oruse the CTRL+N keyboard shortcut and choose Java Packagein the File Types pane and click the Next button. You cancreate a dot-notated sub-package such as pack.subpack ormanually create a package named pack and then right-click onthe pack package and create a new package named subpack.

Page 112: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 109

Using a Package

As described in the last section, data types inside packagesnow have longer names and these longer names are requiredto access those data types. Now that Robot and CameraRobotare in the games2d.maze package, their full name is requiredwhen accessing them outside that package. The followingexample demonstrates this.

games2d.maze.Robot bot1 = newgames2d.maze.CameraRobot();

Although the compiler or runtime has no problem with longernames for data types, some programmers do. To resolve thisissue, you can use the import statement. The import state-ment allows you to use shortened names for the data type(s)in the package you import. You can import either one datatype at a time (preferred by NetBeans) or all data types in apackage using * as a wild card.

The following import statements will allow you to use theRobot and CameraRobot with their shortened names:

These import statements will be stripped out after compilation,so they’re only intended to reduce the number of keystrokeswhen using data types from other packages. So don’t worryabout having too many import statements affecting runtimeperformance. The import statement must come after thepackage statement if it exists and before any other executablecode.

Note: Declaring explicit import statements is good programmingpractice, but NetBeans provides a lazy import as needed. If adata type isn’t recognized in your code, NetBeans will place ared squiggly line below the data type with the message can’tfind symbol. Simply right-click on the source code file andchoose the Fix Imports option from the contextual menu. Adialog box will then appear allowing you to choose whichpackages you need to import if there’s a conflict. After click-ing the OK button in the Fix All Imports dialog, NetBeans willautomatically add the required import statements for you(Figure 8).

Note: As you recall fromthe graded projects,you used the Scannerclass to handle userinput. Because theScanner class waslocated in the java.utilpackage, you had touse the full namejava.util.Scanner inthat code.

Note: Only types within apackage are imported,not sub-packages.

import games2d.maze.*; //imports both Robot and CameraRobotimport games2d.maze.Robot;import games2d.maze.CameraRobot;

Page 113: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java110

One word of caution when usingimport statements: conflicts. If youimport too many packages, thenpossibly conflicting data types willrequire long names anyway. Forexample, there’s a Robot class in both the games2d.maze andjava.awt packages. In the scenariowhere there’s a conflict betweenclasses, you’ll need to choose whichpackage to import and which class(es)you’ll need to use the longer name.

Finally, you can also use a special type of import statementknown as static import. For classes that contain class mem-ber exclusively, that static import statement can be used toomit the class when using its members. The best example ofdoing this is the Math class. The Math class contains noinstance members, only class constants and methods. Ratherthan typing Math.PI to use this constant, you can use astatic import statement to abbreviate the reference to PI.

The following code example uses a static import statementfor the Square class:

import static java.lang.Math.pow;

public class Square {private int sideLength;private double calculateArea() {

return pow(sideLength, 2); }

}

In this example, the code can reference the class methodpow() without the package or class name. You can also usethe * as a wildcard character to import all class members.Oracle recommends using static import statements spar-ingly, because they can create some very confusing anddisorganized code if used all the time.

In the following activity, you’ll create a new package for the Shape, Circle, and Polygon classes and then import that package.

Figure 8—Fix All Imports Dialog

Page 114: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 111

Activity 11: Create and Import a Package in NetBeans

1. Launch NetBeans and open the Lesson3Activity10project if you’ve closed out of the NetBeans.

2. Create a new java package named geometry.shapes2d.To create a new package, either choose New > JavaPackage … in the context menu when right-clicking onthe Source Packages folder in Projects or use theCTRL+N keyboard shortcut and choose Java Package inthe File Types pane and click the Next button. Then,type geometry.shapes2d in the Package Name textboxand click the Finish button.

3. Move the Circle.java, Polygon.java, and Shape.java filesinto the geometry.shapes.2d package. To do this, youshould click and drag each file from the lesson3activity10package on top of the geometry.shapes2d package inthe Projects pane.

Note: For each package move, you’ll be prompted by theMove Class dialog for verification. By default, NetBeanswill refactor, meaning that each moved file will have thepackage statement automatically added to the top andany file that referred to the old package will now have an import statement referring to the new one. Click theRefactor button on this dialog to continue.

4. Open the Circle.java, Polygon.java, and Shape.javafiles one at a time. Notice the new package statement atthe top added by NetBeans.

5. Open the Lesson3Activity10.java file. Notice the newimport statement at the top added by NetBeans.

6. Build and run the project. The output should be thesame as that at the end of the previous activity.

Page 115: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java112

Common Packages

The Java SE 7 platform comes with existing packages youcan use. The documentation of these data types is known asthe application programming interface (API) specification. TheAPI specification describes an overview of each data type, itssuperclasses and subclasses, and fields and methods. Youcan either download this documentation or access the APIspecification remotely on Oracle’s website athttp://docs.oracle.com/javase/7/docs/api/.

Note: In NetBeans, you can view the API documentation for abuilt-in class or one of its methods very easily. Either right-click on the class or its member and choose the ShowJavaDoc option from the context menu or use the ALT+F1keyboard shortcut. JavaDoc is the older name associatedwith Java API documentation.

Page 278 in Chapter 8 includes the top-level packages originally found in java. The java.lang package contains the fundamental types required by the Java language, so it’salways imported implicitly. Not surprisingly, the basic inputand output types are found in the java.io and java.nio pack-ages, while networking-related features are in java.net. Thejava.applet package is used to create applets, while graphicsand painting uses the java.awt and javax.swing packages.

One important package omitted from the textbook is thejava.util package. This package contains the collectionsframework and other utility classes like the Scanner class.The collections framework contains powerful list structuresthat offer more flexibility and generally better performancethan arrays. Unlike arrays, collections aren’t fixed in size and provide built-in sorting and searching capabilities.

Table 3 contains common collection classes you might finduseful. Because most collections use generics to handle dif-ferent types, usage of a collection will be delayed until thatsection in the lesson.

Page 116: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 113

Class Description

ArrayList A resizable list of index-ordered elements with next/back iteration

HashMap A resizable set of unordered elements retrievable by key

LinkedList A resizable list of index-ordered elements with next/backiteration and stack/queue functionality.

TreeMap A resizable set of elements ordered in hierarchical sortingalgorithm and retrievable by key.

Table 3—Common Collection Classes

Page 117: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java114

Self-Check 9

1. What is inheritance? Which class is the superclass and which is the subclass?

__________________________________________________________

2. Given the following code, what is the output?

public class SuperClass {

public void print() {System.out.println(“Super print()”);

}

class SubClass extends SuperClass {

public void print() {System.out.println(“Sub print()”);}

public static void main(String[] args) {

SuperClass obj = new SubClass();

obj.print();

}

}

__________________________________________________________

3. What is the difference between abstract and concrete classes?

__________________________________________________________

4. Which two purposes does a package serve in Java?

__________________________________________________________

Check your answers with those on page 204.

Page 118: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 115

ASSIGNMENT 10: CREATEINTERFACES AND ENUMERATIONSRead Assignment 10 in this study guide. Then read Chapter 8,pages 278–292, and Chapter 12, pages 406–420, in your textbook.

Assignment 10 adds two other reference types used in Java:interfaces and enumerations. This study guide will introduceyou to the selected sections in Chapter 8 and Chapter 12. Besure to complete the Try This activities in both chapters. They’llhelp reinforce the syntax and concepts.

Interface and Implementation

When considering a class, it’s important to differentiatebetween a class’s interface and its implementation. An inter-face is the declaration of each method, including the methodname, parameter list, and return value. The implementationis code that defines how the method uses the arguments asinput and returns the result as output. The implementationis the code between the opening and closing curly braces.

For the following method in the Square class, the interface isbolded and the implementation is italicized:

public double getArea() {

return Math.pow(sideLength, 2);

}

The interface describes what an object can do, while theimplementation defines how the object does it.

Inheritance without the Side Effects

Although inheritance provides reuse and encapsulation amongsubclasses, it also creates tight-coupling between these classes.This means that any implementation changes in the superclasswill affect all subclasses and their implementation. Althoughthe subclasses share the same interface, their implementationmay be unrelated and doesn’t require inheritance.

Page 119: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java116

In many situations, inheritance doesn’t make sense. Classesmay share the same interface, but inherit code from differentsuperclasses. Take the following class as an example:

public class Mouse { public void eat () {}public void sleep() {}public void turn (int direction) {}public void move(double time) {}public void move(double time, int direction) {}

}

The Robot and Mouse classes both share some methods,namely move() and turn(), but in all other ways they’re dis-similar. A Robot object can’t eat or sleep, while a Mouseobject can’t be tracked using x and y coordinates. It wouldn’tmake sense to create some superclass named Movable just fora single method!

Not only that, but because Java supports only single inheritance,the Robot and Mouse classes couldn’t share one superclassand be subclasses of another. It would make logical sense forRobot to have a superclass like Machine and Mouse to havea superclass like Animal. Neither the Robot nor Animalclass can be subclasses, unless they give up inheritance withtheir other superclasses.

To overcome these design issues, Java provides the interfacekeyword to separate out just the interface portion from a class.Unlike abstract classes, interfaces can contain no privatefields or method implementations, only constants, initializedfields, and method declarations. A class can have only oneimmediate superclass, but it can implement zero or moreinterfaces.

To resolve the issue with the Robot and Mouse classes, youcould declare a new interface called Movable that containsonly shared methods between the two classes. The followingcode demonstrates one way to define the Movable interface:

public interface Movable {public void turn (int direction);public void move(double time);public void move(double time, int direction);

}

Page 120: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 117

The Robot and Mouse classes would use the implementskeyword in their class declarations as follows:

Similar to inheriting an abstract class, classes that imple-ment an interface must define all methods of that interface.Interfaces are also treated as powerful reference types andsupport polymorphism. Implementing an interface is knownas “inheritance without the side effects.” This is because onlythe interface is inherited, not the implementation details thatare bound to change from class to class. The interface is lesslikely to change, so that classes that communicate usinginterfaces are known as loosely-coupled.

How powerful is an interface? Take the following method asan example:

The moveInMaze() method will move a Mouse, Robot, or any other object that implements the Movable interface. Theimplementation of the moveInMaze() method doesn’t need tobe concerned with implementation details, but only how touse the interface. Even though a Mouse object can eat andsleep, using an interface allows other classes to focus on whatthey need to do with the object, not be concerned with all ofthe class details that aren’t important with the task at hand.

Activity 12: Create and Use an Interface

1. Launch NetBeans and open the Lesson3Activity11project if you’ve closed out of the NetBeans.

2. Add a new interface named Nameable.

public class Mouse extends Animal implements Movable {/*implementationomitted*/}

public abstract class Robot extends Machine implements Movable{/*implementation omitted*/}

Note: In abstractclasses, methods withno definition must usethe keyword abstract.The keyword abstractisn’t required in thiscode, because all meth-ods in an interfacecontain no definition.

public void moveInMaze( Movable m, double time, int direction) {m.move(time, direction);

}

Page 121: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java118

You can either right-click on the Lesson3Activity11project and choose New > Java Interface … in the con-text menu by right-clicking the lesson3activity11package in Projects or use the CTRL+N keyboard short-cut and choose Java Interface in the File Types paneand click the Next button.

In the Class Name text box, type Polygon and in thePackage drop-down list, choose lesson3activity11.

3. The Nameable interface will contain three methods forobjects with names and descriptions. The code for theNameable interface should be as follows:

public interface Nameable {public String getID();public void setID (String id);public void printInfo();}

4. Open the Shape.java file in the geometry.shapes2dpackage.

5. Modify the Shape class declaration to implement theNameable class as follows:

public abstract class Shape implementsNameable

6. Right-click somewhere in the source code file and choose the Fix Imports option from the contextual menu. This will add the import statement for the interface automatically.

Now that you’ve created an interface for objects withnames and descriptions, you’ll create another class unrelated to two-dimensional shapes. This new classrepresents a geometric proof that contains a name anddescription, but has no other similarity with the Polygonand Circle classes.

Note: The interface contains very littlecode. Because classesthat implement aninterface must provideimplementation for allmethods declared in aninterface, most inter-faces are specializedand brief.

Page 122: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 119

7. Create another class named Proof to the geometrypackage.

■ You can either right-click on the Lesson3Activityproject in Projects and choose New > Java Class …in the context menu or use the CTRL+N keyboardshortcut and choose Java Class in the File Typespane and click the Next button.

■ In the Class Name text box, type Proof and in thePackage drop-down list, type geometry.

8. The Proof class should be defined as follows:

9. Right-click somewhere in the source code file and choose the Fix Imports option from the contextual menu. This will add the import statement for the interface automatically.

public class Proof implements Nameable {private String id;private String prove;private String[] given;public Proof(String id, String prove, String... given) {

this.id = id;this.prove = prove;this.given = given;

}//Nameable implementation

public String getID() { return id; }public void setID(String id) { this.id = id; }public void printInfo() {

System.out.print(id + “: “);System.out.print(“\nProve: “ + prove);System.out.print(“\nGiven: “ +

Arrays.toString(given));}}

Page 123: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java120

10. Open the Lesson3Activity11.java file and modify the following code in the main() method:

11. Right-click somewhere in the source code file and choose the Fix Imports option from the contextual menu. This will add the import statement for the Proof class automatically.

12. Build and run the project. You should now have all threeobjects, Polygon, Circle, and Proof objects using theNameable interface and through polymorphism displaying the correct results.

Creating Basic Enumerations

Using names for values rather than literal values themselvesmakes code more readable. This is especially the case fornumerical values. It’s easier to remember that a number isthe width of a box if it’s named with the variable boxWidth,than it’s simply as its value of 8.5.

Nameable triangle = new Polygon(“triangle1”, 3, 5);

Nameable square = new Polygon(“square1”, 4, 3);

Nameable octagon = new Polygon(“octagon1”, 8, 10);

Nameable hexagon = new Polygon(“hexagon1”, 6, 5 );

triangle.printInfo();

square.printInfo();

octagon.printInfo();

hexagon.printInfo();

Nameable circle = new Circle(“circle1”, 5);

circle.printInfo();

Nameable proof = new Proof(“Congruent triangles”, “ABM and DCM are congruent”,

“AD bisects BC”, “BC bisects AD”);

proof.printInfo();

Page 124: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 121

Simply described, an enumeration is a custom data type thatcontains a limited set of named values. An enumeration isdescribed in Java using the enum keyword. The followingcode defines an enumeration for e-mail messages:

public enum MailPriority {REQUIRED_RESPONSE, REQUIRED_ACKNOWLEDGEMENT, OPTIONAL_RESPONSE, OPTIONAL_ACKNOWLEDGEMENT }

Like constants, enumeration values are by convention in alluppercase. To use an enumeration, you would declare a vari-able with that enumeration type and set the value as in thefollowing code:

MailPriority p = MailPriority.REQUIRED_RESPONSE;

Enumerations are much more powerful in Java than in other languages. Although the new keyword isn’t required toinstantiate enumerations, they support fields, methods, andconstructors. The following code declares the MailPriorityenumeration using preset int values:public enum MailPriority {

REQUIRED_RESPONSE (10), REQUIRED_ACKNOWLEDGEMENT(8), OPTIONAL_RESPONSE (4), OPTIONAL_ACKNOWLEDGEMENT (2);//preset valueprivate int relValue;public int getValue() {return relValue;}//constructorpublic MailPriority (int relValue) {this.relValue = relValue;}

}

Page 125: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java122

Built-In Methods for Enumerations

Although enumerations can’t be subclassed, they’re subclassesof the superclass Enum. This means that enumerations includethe built-in methods shown in Table 4.

The following code demonstrates how to use these methods:

for(MailPriority p : MailPriority.values()) {System.out.print(“\n” + p.name());System.out.print(“(“ + p.ordinal() + “) - “);System.out.print(“\”“ + p.toString() + “\”“);

}

The output of the code is as follows:

REQUIRED_RESPONSE(0) - “REQUIRED_RESPONSE”

REQUIRED_ACKNOWLEDGEMENT(1) - “REQUIRED_ACKNOWLEDGEMENT”

OPTIONAL_RESPONSE(2) - “OPTIONAL_RESPONSE”

OPTIONAL_ACKNOWLEDGEMENT(3) - “OPTIONAL_ACKNOWLEDGEMENT”

Note: Because enumer-ations contain discretevalues, they can be usedin switch statements.

Table 4

Method Description

name() Returns the name of an enumeration constant.

ordinal() Returns the order of an enumeration constant as it was declared.

values() Returns an array of enumeration constants.

Table 4—Built-in Methods

Note: The toString()method is overridden inthe Enum class to pro-vide the same value asthe name() method.

Page 126: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 123

Self-Check 10

1. What does the phrase “inheritance without the side effects” mean?

__________________________________________________________

2. What are two key differences between abstract classes and interfaces?

__________________________________________________________

3. What is the simple definition of an enumeration?

__________________________________________________________

Check your answers with those on page 205.

Page 127: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java124

NOTES

Page 128: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 125

ASSIGNMENT 11: BOXING AND GENERICSRead Assignment 11 in this study guide. Then read Chapter 12,pages 420–426, as well as Chapter 13 in your textbook.

Assignment 11 introduces two important reference typemechanisms: boxing and generics. This study guide coversthe selected section in Chapter 12 and Chapter 13. Be sureto complete the Try This activities in Chapter 13, which areinvaluable in gaining a more in-depth study of generics.

Type Wrappers

Although primitive types over significant memory and per-formance advantages over objects, you’ll find that certainmethods will require an object or you need a primitive valueto be modified by a method. The Java language provides spe-cial classes known as type wrappers to allow primitive typesto be stored, used, and passed as objects. The following tablelists the type wrapper classes and their associated primitivetypes.

Table 5

Type Wrapper Class Supported Primitive Type

boolean boolean

Byte byte

Short short

Integer int

Long long

Float float

Double double

Character char

Table 5—Type Wrapper Classes

Page 129: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java126

All numeric type wrappers are subclasses of the abstractNumber class. The Number class provides xxxValue() meth-ods to retrieve a primitive value of any numerical value,whether it’s wrapped by a Byte or Float class. Other featuresprovided by numeric type wrappers include parsing, convert-ing, bitwise manipulation, and display in other representationssuch as hexadecimal, octal, and binary.

To manually wrap a primitive type, you need only specify thevalue in the class constructor. The following code demonstratesusing a primitive type variable and a literal value:

int primVal = 10;Integer i1 = new Integer(primVal);Integer i2 = new Integer(10);

This process of placing a primitive value into its type wrapperclass is known as boxing. The reverse, removing a primitivetype from its type wrapper is known as unboxing. The follow-ing code manually unboxes the wrapper objects i1 and i2:

int p1 = i1.intValue();int p2 = i2.intValue();

Autoboxing

Although you could manually box and unbox primitive types,the runtime does this automatically for you. Any time anoperation or method requires an object, the primitive value isboxed. Whenever a primitive value is required by an operationor method, it’s unboxed.

The following code demonstrates this automatic unboxingand boxing for operations:

int result1 = i1 + i2 + 5; //AutounboxedInteger result2 = p1 + p2 + 5; //Auto boxed

This, of course, works with methods just as easily. If a methodrequires a subclass of the Object class, for example, then theruntime boxes the primitive value and then automaticallyunboxes it whenever needed.

Note: As you learned in the previous gradedproject, the Characterclass is useful forchecking for types ofcharacters, includingvalid characters forJava identifiers! TheCharacter class alsoprovides methods foroffsetting charactersand modifying themusing character codes.

Page 130: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 127

Note: Autoboxing may seem to be modifying wrapper objects,but like the String object, wrapper objects are immutable.This means that autoboxing can have an impact on performancesimilar to reassignment with a multitude of String objects. Therecommendation is to group together and perform operationswith primitive types before assigning the primitive result to awrapper object.

Generic Objects and Generics

So far you’ve learned how to group objects by either a directclass or superclass. You also know that every object is a sub-class of the Object class. With that knowledge in mind, youwant to generalize methods to handle any object by using theObject class. For example, you may want to create a general-ized method for outputting an object’s string representation:

public static void print(Object obj) {System.out.println(obj.toString());

}

This method isn’t necessarily a bad idea, because every classinherits the toString() method. Even if that class doesn’toverride the toString() method to display state data, themethod will output the class name by default. You mightstart feeling over-confident and then try something like thefollowing method:

This method is much more problematic. Although all classesinherit the equals() method from the Object class, its defaultimplementation will return true only if both variables referencethe same object, not when they’re equivalent. This means themethod will work for some pairs of object arguments, but notothers.

public static boolean isEqual(Object obj1, Object obj2) {return obj1.equals(obj2);

}

Page 131: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java128

Now, another example of over-generalization. You have amethod that accepts an array of Object types. Instead ofchecking first to see what actual types they are, you perform

a cast and then invoke a method not inherited from theObject class. The following code demonstrates this tech-nique:

This is a problem, because some objects may not implementthe Movable interface and can’t be casted as such. The com-piler doesn’t know that the cast is invalid, because the actualvalue for the obj variable isn’t known until runtime. This codewill compile, even though it’s possible there will be seriousruntime errors. Runtime debugging can consume significantlymore time than checking the cast when the code compiles.

The solution is generics. Generics is a category of classes andinterfaces that can handle specific parameter types withoutusing the Object class. Because these specific parametertypes are checked at compile time, generics provide typesafety. Type safety prevents runtime errors when casting.

Generic Methods

When using generics in methods, you can think of them asextra parameters for a method. The only difference is a genericparameter can represent any type and is specified in anglebrackets before the return type, not in the parameter list.

public static void moveObjects(Object[] objArray, double time) {for (Object obj : objArray) {

Movable m = (Movable) obj;m.move(time);

}}

public static <T> void moveObjects(T[] genArray, double time) {for (T generic : genArray) {Movable m = (Movable) generic;m.move(time);}}

Page 132: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 129

The following is a generic version of the moveObjects() method:

Now the compiler can track the data type sent to themoveObjects() method using the generic parameter T.Because there are no restrictions on which type T can be,this isn’t altogether helpful. The following modification canrestrict T to only those objects that implement the Movableinterface:

This modification will now cause the following code to failcompilation before the runtime throws an exception:

String[] strings = {“we”, “do”, “not”, “move!”};moveObjects(strings, 2.8);

Notice that the code above doesn’t have to specify a genericargument, because the generic argument can be implied bythe data type of the first method argument genArray. Sincethe genArray argument is String array and String objectsdon’t implement the Movable interface, the code fails compi-lation.

Of course generic types are uncommon, because there’s oftenan interface or specific class in which objects must implementor extend. In this scenario, we could just as easily support an array of Movable objects which would provide type-safetywithout generics.

public static <T extends Movable> void moveObjects(T[] genArray, double time){

for (T generic : genArray) {

Movable m = (Movable) generic;

m.move(time);

}

}

Page 133: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java130

For a more in-depth exploration of generics, please readthrough all of Chapter 13 in the textbook. Because mostoften you’ll use generic types and not define them, the nextactivity will have you use the generic collection ArrayList.

Activity 13: Use a Generic Collection

1. Open the Lesson3Activity12.java file of theLesson3Activity project in NetBeans.

2. Replace the code in the main() method with the following:

3. Build and run the project. The output should match theoutput at the end of Activity 12.

The big difference between non-generic and generic col-lections is that the programmer isn’t required to performmany casting operations and deal with possible issues atruntime. Using a non-generic ArrayList where every ele-ment was stored as an Object type, was painful inprevious versions of Java. Look at the following code foran example of this pain:

ArrayList list = new ArrayList();list.add(new CameraRobot());list.add(new Mouse());

for (Object obj : list) ((Movable)obj).printInfo();

Using generic collections, you can be assured that all ele-ments are stored using the data type you need. Althoughthey may seem rather complex at first, generics are asimplification tool.

Note: The diamondoperator <> is usedwhen instantiatinggeneric classes thathave the generic typealready specified in thevariable data type. InJava, you don’t need to provide the genericargument twice.

java.util.ArrayList<Nameable> list = new java.util.ArrayList<>();

list.add(new Polygon(“triangle1”, 3, 5));

list.add(new Polygon(“square1”, 4, 3));

list.add(new Polygon(“octagon1”, 8, 10));

list.add(new Polygon(“hexagon1”, 6, 5 ));

list.add(new Circle(“circle1”, 5));

list.add(new Proof(“Congruent triangles”, “ABM and DCM are congruent”,

“AD bisects BC”, “BC bisects AD”));

for (Nameable n : list) n.printInfo();

Page 134: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 3 131

Self-Check 11

1. How are type wrappers used in Java?

__________________________________________________________

2. What is autoboxing?

__________________________________________________________

3. Given the following method declaration, which type of objects are allowed for the array and elem parameters?

<T extends Comparable<T>> void sortArray (T[] array, T elem)

__________________________________________________________

__________________________________________________________

Check your answers with those on page 205.

Page 135: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java132

NOTES

Page 136: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

133

Gra

de

d P

roje

ct

Gra

de

d P

roje

ct

Object-OrientedProgramming

OVERVIEW

After reading selected sections of Chapters 4, 6, 7, 8, 12, and 13in the textbook and completing Lesson 3, you’re ready to beginobject-oriented programming. This project will assess yourunderstanding of creating a class hierarchy in a package andwriting code for classes and enumerations.

Make sure that you follow all directions completely and verifyyour results before submitting the project. Remember to includeall required components in your solution.

YOUR PROJECT

In this project, you’ll create data types in a class structure forcell-based board games similar to Tic-Tac-Toe. Games likeConnect Four and Mastermind also use boards divided byrows and columns. The Board and Cell classes represent theboard, while the Player, Mark, and Outcome enumerationstrack the game.

You’ll use the classes and enumerations created in this projectin future graded projects. You use the NetBeans project inthe next lesson.

INSTRUCTIONS

1. In NetBeans, create a new Java Application projectnamed BoardGameTester.

2. Create a new package named games and a sub-package ofgames named board. The easiest way is simply to createa package named games.board.

Page 137: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project134

3. Add an enumeration named Player to the games.boardpackage. You could add Empty Java File or chooseJava Enum as the file type. This enumeration representsthe current player in a turn-based game. Use the follow-ing code:

public enum Player {FIRST,SECOND}

Note: Although Tic-Tac-Toe and Mastermind allow onlytwo players, Connect Four can be played with up to fourplayers. For simplicity, our code will handle only twoplayers.

4. Add an enumeration named Outcome to thegames.board package. This enumeration represents theresult when the turn is completed. Use the followingcode:

5. Add an enumeration named Mark to the games.boardpackage. This enumeration represents the result whenthe game is completed. Use the following code:

Note: Yellow and red are used in Connect Four, whileMastermind uses all six colors.

6. Add the Cell class to the games.board package. Itshould have the private variables content, row, and column, and the public methods getContent,setContent, getRow, and getColumn. Use the followingcode as a guide:

public class Cell {private Mark content;private int row, column;

public Cell(int row, int column) {this.row = row;this.column = column;

content = Mark.EMPTY;}public Mark getContent() { return content; }

public enum Outcome {PLAYER1_WIN, PLAYER2_WIN, CONTINUE, TIE}

public enum Mark {EMPTY, NOUGHT, CROSS, YELLOW, RED, BLUE, GREEN, MAGENTA, ORANGE}

Page 138: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project 135

Note: All classes that support direct instantiation shouldhave a constructor. In this case, the constructor will beused by the Board class to create each of its cells.

7. Add the Board class to the games.board package. It shouldhave a two-dimensional array of Cell objects. The Boardclass should initialize a board with a specified number of columns and rows, provide access to Cell objects, anddisplay all of its cells correctly. Use the following code asa guide:

public class Board {private Cell[][] cells;

public Board(int rows, int columns) {cells = new Cell[rows][columns];for( int r = 0; r < cells[0].length; r++ ) {

for (int c = 0; c < cells[1].length; c++) {cells[r][c] = new Cell(r,c);

}}

}public void setCell(Mark mark, int row, int column) throwsIllegalArgumentException {

if (cells[row][column].getContent() == Mark.EMPTY) cells[row][column].setContent(mark);

else throw new IllegalArgumentException(“Player already there!”);}public Cell getCell(int row, int column) {return cells[row][column];

}public String toString() {

StringBuilder str = new StringBuilder();

for( int r = 0; r < cells.length; r++ ) {str.append(“|”);for (int c = 0; c < cells[r].length; c++) {

switch(cells[r][c].getContent()) {

public void setContent(Mark content) { this.content = content; }public int getRow() { return row; }

public int getColumn() { return column; }}

Page 139: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project136

case NOUGHT:str.append(“O”);break;

case CROSS:str.append(“X”);break;

case YELLOW:str.append(“Y”);break;

case RED:str.append(“R”);break;

case BLUE:str.append(“B”);break;

case GREEN:str.append(“G”);break;

case MAGENTA:str.append(“M”);break;

case ORANGE:str.append(“M”);break;

default: //Emptystr.append(“ “);

}str.append(“|”);

}str.append(“\n”);

}return str.toString();

}

}

Note: This code should seem familiar to you. The meth-ods in the TicTacToeGame class are similar to those inthe Board class. The StringBuilder class was usedinstead of the String class for better performance. Youcan learn more about the StringBuilder class by visitingthe Oracle Website at http://docs.oracle.com/javase/tutorial/java/data/buffers.html.

Page 140: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project 137

8. Add the following import statement to theBoardGameTester class:

import games.boards.*;

9. In the main() method of BoardGameTester, perform thefollowing actions:

a. Create a 3 × 3 board for a Tic-Tac-Toe game.

b. Create a 6 × 7 board for a Connect Four game.

c. Create a 5 × 8 board for a game of Mastermind.

d. Set a cell to a nought or cross on the Tic-Tac-Toe board.

e. Set a cell to yellow or red on the Connect Four board.

f. Set a cell to yellow, red, green, blue, magenta, ororange on the Mastermind board.

g. Display the boards for Tic-Tac-Toe, Connect Four,and Mastermind.

10. Compile and run the project to ensure it works as expected.

SUBMISSION GUIDELINES

To submit your project, you must provide the followingsource code files in a ZIP file:

■ BoardGameTester.java

■ Board.java

■ Cell.java

■ Mark.java

■ Outcome.java

■ Player.java

Page 141: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project138

To find these files within NetBeans, go to theBoardGameTester project folder. To determine this folder,right-click on BoardGameTester project in the Projectspanel. Copy the value for the Project Folder textbox usingthe keyboard shortcut CTRL+C. In Windows Explorer, pastethe project folder path and hit the ENTER key. Right-click onthe src folder and choose the Send to... > Compressed(zipped) folder option from the context menu. Rename the fileto BoardGameTester_Lesson3.zip and copy it to your desk-top or any other temporary location.

Follow this procedure to submit your project online:

1. Log on to the Penn Foster website and go to My Courses.

2. Click Take Exam.

3. Attach your Zip file as follows:

a. Click on the Browse box.

b. Locate the file you wish to attach.

c. Double-click on the file.

d. Click Upload File.

4. Enter your e-mail address in the box provided. (Note:This information is required for online submissions.)

5. If you wish to tell your instructor anything specificregarding this assignment, enter it in the Message box.

6. Click Submit File.

Page 142: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Grading Criteria

Your instructor will use the following guidelines to grade your project.

All types are organized in correct package hierarchy 10 points

Mark enumeration correctly defined 5 points

Outcome enumeration correctly defined 5 points

Player enumeration correctly defined 5 points

Cell class correctly defined 10 points

Board class correctly defined 10 points

BoardGameTester class correctly defined 20 points

The application returns expected output 25 points

All source code files are included: 10 points

TOTAL 100 points

Graded Project 139

Page 143: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

NOTES

Graded Project140

Page 144: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

141

Le

ss

on

4L

es

so

n 4

Advanced Programming Logic

INTRODUCTION

So far the applications you’ve designed are transient andunoptimized. They’re effective as long as a user keeps theprogram running and performs one action at a time. Well-built applications usually take advantage of a user’s localstorage and memory/CPU utilization. In this lesson, you’lllearn how to load and save data to files and use multithread-ing techniques to improve the consistency and performanceof your applications.

OBJECTIVES

When you complete this lesson, you’ll be able to

■ Differentiate between the I/O classes provided by Java

■ Write data from an application to a file

■ Read data from a file back into an application

■ Access the local user’s file system using the java.nio package

■ Create a custom thread using the Thread class andRunnable interface

■ Control a running thread’s lifetime and priority

■ Use thread synchronization and notification techniques

■ Use the java.util.concurrency package

Page 145: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java142

ASSIGNMENT 12: USE I/O CLASSESRead Assignment 12 in this study guide. Then read Chapter 10in your textbook.

Assignment 12 introduces basic input/output programmingin Java and addresses the new I/O classes provided by Java 7in the java.nio package. Be sure to complete the Try Thisactivities in Chapter 10.

Standard Stream Classes

A stream is a sequential flow of data from a source to a destination. Sources can include files, network hosts, or even local String objects. Data sent through a stream can beraw bytes, individual characters, sequences of characters, orentire objects. Input streams read data from a stream, whileoutput streams write data to a stream.

There are many stream classes located in the java.io pack-age, each specialized for certain types of streams, sources,and destinations. In the textbook, Table 10-1 on page 328lists all of the byte stream classes, while Table 10-2 on page329 lists all of the character stream classes. The fundamentaldifference between byte and character streams is that characterstreams convert bytes into characters. Byte streams don’tassume a character set and are intended for images, objectserializations, and other binary data.

Byte Streams

Byte input and output streams are subclasses of the abstractclasses InputStream and OutputStream, respectively. Thecore method of the InputStream class is read(). The read()method can retrieve a single byte or an array of bytes. Whenthe end of the stream is reached, read() will return -1. Thecore method of the OutputStream class is write() and canalso handle a single byte or array of bytes. The OutputStreamclass includes the flush() method to push buffered data intothe stream. Both InputStream and OutputStream provide aclose() method to end the stream and release all systemresources used by that stream.

Page 146: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 4 143

The following code demonstrates a common algorithm usedin reading byte streams:

while ( (byteRead = inputStream.read() ) != -1) {//do something with the bytes here

}

As you can see from this example code, the while and do-while statements are prominent in I/O programming. Noticealso from this example that the read() method is invoked,then immediately assigned, and compared to -1. This condi-tion will ensure the block ends once the end of the stream isreached.

Character and Buffered Streams

Character input and output streams are subclasses of the abstract classes Reader and Writer, respectively. TheReader class also provides the read() method, but unlike theInputStream class, the Reader retrieves converted char valuesfrom the stream. The Writer class provides a write() methodfor characters, but also includes the append() method foradding characters to the end of a stream. The flush() methodpushes buffered characters into the stream. Like InputStreamand OutputStream, the Reader and Writer classes provide aclose() method.

Because character streams merely convert between bytes andcharacters, character stream classes accept byte streams fortheir constructors. By wrapping a byte stream in a characterstream, you can take advantage of sources and destinationsthat don’t natively support character conversion. The follow-ing code wraps the standard input byte stream with acharacter stream:

Reader reader = new InputStreamReader( System.in );

Often, you’ll need to read characters, not one at a time, but entire lines at a time. BufferedReader is a wrapper forReader objects to provide the additional readLine() method.The PrintWriter is a wrapper for Writer objects to providethe additional println() and printf() methods. The printf()method is intended for formatting an array of objects in a

Note: Both byte andcharacter streamclasses can throw an IOException. If amethod throws anIOException, then youmust either handle theexception in atry/catch block withinthe method or declarethat method throws anIOException.

Page 147: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java144

String. You can read more about formatting string syntax inthe Java 7 API Documentation at http://docs.oracle.com/javase/7/docs/ api/java/util/Formatter.html#syntax

System Streams

In using the command line for I/O operations, you’ve alreadybeen exposed to predefined streams provided by the Systemclass:

■ System.in—Standard keyboard entry using theInputStream class

■ System.out—Standard text-based output using thePrintStream class

■ System.err—Standard text-based output formatted forerrors using the PrintStream class

Another technique for using the command line is to use theConsole class. If you develop command-line applications, youshould use the Console class rather than the System streams.Unfortunately, the Console class isn’t compatible with theOutput pane in the NetBeans IDE.

Opening and Closing Streams

To open a stream for reading or writing in Java, you need onlyinstantiate the stream class. The available() method in theInputStream class will return the number of bytes availablefor reading. The ready() method returns a boolean indicatingwhether the stream is available for reading with the Readerclass.

Note: Byte streamshave a class similar to PrintWriter. ThePrintStream class alsoprovides the println()and printfs() methods.

Page 148: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 4 145

When reading or writing with the stream is complete, thatstream should be closed and its pointer dereferenced. The following code performs this action manually:

Note: The finally block will execute whether or not an excep-tion is thrown. However, if the close() method throws anexception, then any exceptions thrown from the try block will be effectively suppressed. The Throwable class providesgetSuppressed() and initCause() to access suppressed excep-tions in these situations.

Java 7 introduces a new construct to handle this logic seamlessly. The try-with-resources statement will automati-cally close and dereference resources that implement theAutoCloseable interface. All stream classes implement thisinterface, so this construct can definitely simplify your code.

The previous example could be rewritten using the try-with-resource statement:

try ( FileWriter fs = new FileWriter(“output”) ) {//perform write operations

} catch (IOException ex) {//handle exception

}

try {FileWriter fs = new FileWriter(“output.txt”);//perform write operations} catch (IOException ex) {

//handle exception} finally {

if (fs != null ) { // <- instantiation may have failedfs.close(); // <- close the streamfs = null; // <- dereference the stream pointer

}}

Page 149: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java146

Reading and Writing to Files

To read from a file, you can use the byte streamFileInputStream or character stream FileReader. To write to a file, you can use the byte stream FileOutputStream orcharacter stream FileWriter. The constructors for theseclasses can accept a path name or legacy File object. Theseconstructors can throw FileNotFoundException if the loca-tion is invalid or SecurityException if the current userdoesn’t have permission to read or write to it.

The following code copies a file byte into another file:

In the next activity, you’ll use the ObjectInputStream andObjectOutputStream classes to write and read an object anduse the FileInputStream and FileOutputStream classes toread and write that object to a file.

Activity 14: Read and Write Objects with a File

1. Create a new Java Application project namedLesson4Activity14 in NetBeans.

2. Create a new public class named Employee to the Lesson4Activity14 package.

3. Inside the Employee class, add the following code:

Note: For an object to be written to a stream, it mustimplement the Serializable interface. All fields, includingthose declared as private, are written to the stream.

Note: The readObject()method throws aClassNotFoundException,because the object mayrepresent a class that’sunavailable to theapplication.

try (

FileInputStream fsIn = new FileInputStream(“input.txt”);FileOutputStream fsOut = new FileOutputStream(“output.txt”)

) {int b;while ( (b = fsIn.read()) != -1 )

fsOut.write(b);} catch (IOException ex) {

System.err.println(ex.toString());}

Page 150: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 4 147

4. Open the Lesson4Activity14.java file. You can do this by either clicking its tab at the top of Documentsbecause it should be open or by double-clicking theLesson4Activity14.java file in the Projects pane.

5. Make sure you add import the java.io package in theLesson4Activity14.java file using the following statement:

import java.io.*;

6. Add the following code in the main() method:

7. Build and run the project. The output should be asfollows:

Employee object written to file.Employee object read from file.999-99-9999 (Joshua Hester) - Developer.

//Activity 14Employee emp = new Employee(“Joshua Hester”, “999-99-9999”, “Developer”);

//save employee to filetry (FileOutputStream fout = new FileOutputStream(“emp.data”);

ObjectOutputStream objout = new ObjectOutputStream(fout);) {objout.writeObject(emp);objout.flush();System.out.println(“Employee object written to file.”);} catch (IOException ex) {System.err.println(ex);}

emp = null; //clear employee

//read back employee from filetry (FileInputStream fin = new FileInputStream(“emp.data”);ObjectInputStream objin = new ObjectInputStream(fin);) {emp = (Employee) objin.readObject();System.out.println(“Employee object read from file.”);} catch (IOException | ClassNotFoundException ex) {System.err.println(ex);}System.out.println(emp);

Page 151: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java148

New I/O Classes

Although the system.io package provides classes, enumera-tions, and interfaces to handle local file system viewing andmanipulation, Java 7 introduced a new file I/O mechanismin the java.nio package. The java.nio package offers signifi-cant advantages over the older java.io package. Not only arefile I/O operations with java.nio greatly simplified, but thismechanism utilizes memory buffers, read/write channels,and multiple threads.

Table 6 lists common I/O classes and interfaces in thejava.nio package and java.nio.file and ava.nio.file.attributesubpackages.

Note: Many of theseclasses are abstract,because the JVM provides the implemen-tation optimized for thetarget file system atruntime. This meansthat file I/O operationsshould work regardlessof which operating sys-tem is installed.

Table 6

Class Description

Buffer Abstract sequence of primitive elements storedfor an underlying stream

MappedByteBuffer An abstract byte-portion of a file mapped to memory

FileChannel An abstract channel for file reading/writing and manipulation

NetworkChannel An interface for channels using network protocols

SocketChannel, ServerSocketChannel Abstract network channels that represent clientsenders and server listeners, respectively

PathInterface that represents a file/directory locationon the file system. To get a Path object, use thePaths class.

DirectoryStream Interface used to iterate through entries in a directory

Files A class that provides static methods for opening,Table 6—Java.nio classes

Page 152: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 4 149

You’ll use a Path object to reference a file or directory loca-tion. The Paths class provides the static method get(), whichcan accept one or more String arguments. The following codedemonstrates how to access a File using the Paths class:

Path p1 = Paths.get(“file.txt”);//relative Path p2 = Paths.get(“C:\\Java\\file.txt”);//absolutePath p3 = Paths.get(“C:”, “Java”, “file.txt”);//same as p2boolean isSameFile = Files.isSameFile(p2, p3);//set to true

Assuming the current compiled class is in the same locationas file.txt, all three of these Path objects would reference thesame file. When using absolute locations, the last code state-ment is the preferred convention. This is because the JVMautomatically adds the path separator (\ for Windows; / forLinux, Unix, and Mac) for the target OS. It’s always prefer-able to be agnostic in terms of the OS, so that your Javaapplication will run on any platform.

A Path object doesn’t map to an actual file or directory location,because a path may not exist on the local file system. This ishelpful for creating new files, but can complicate matters whenreading from or appending to an existing file. Before using aPath object for input, you should invoke either the exists() ornotExists() method on the Files class. If the file system can’tconfirm its existence because of a hardware or driver issue,then it may return false for both methods.

The Files class also provides methods to verify the capabili-ties of the file. The isReadable() and isWritable() methods areimportant to check before attempting to open a file. TheStandardOpenOptions enumeration specifies how the fileshould be opened when performing write operations. Thisenumeration includes the following fields:

1. WRITE—Write access.

2. APPEND, TRUNCATE_EXISTING—Add data to the end ofthe file or overwrite existing data, respectively.

Note: You can use thegetPath() method onthe default FileSystemobject to retrieve a Path object. Also, the FileSystem objectprovides helpful OS-specific methods toensure that your fileI/O code remainsagnostic of the OS.These methods includegetSeparater() andgetRootDirectories().

Note: TheStandardOpenOptionsenumeration fields usethe bitwise OR operator| to combine values.

Page 153: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java150

3. CREATE, CREATE_NEW—Create a new file. CREATEwill open the file if it already exists, while CREATE_NEWwill throw an exception if the file already exists.

4. DELETE_ON_CLOSE—Deletes the temporary file afterI/O operations are complete.

When handling files, you’ll most often use Files and/or Pathto access a file for reading or writing. The simplest method is to use the self-explanatory methods readAllBytes() orreadAllLines() or write(). This is appropriate for small files less than a megabyte in size. Larger text files can retrievebuffered streams using the newBufferedReader() andnewBufferedWriter() methods. For backwards compatibility,the methods newInputStream() and newOutputStream() areprovided, but the newByteChannel() method is intended forlarger data files. Finally, the most robust and complex mech-anism for accessing files is using FileChannel, which offersfile-locking features, file bytes to memory mapping, andadvanced reading and writing controls.

The following code reads all bytes from one file and copiesthose bytes into another:

In Activity 15, you’ll use buffered streams to write and thenread back contents of a file.

Path srcFile = Paths.get(“original.txt”);Path destFile = Paths.get(“copy.txt”);try {

byte[] readBytes = Files.readAllBytes(srcFile); //readFiles.write(destFile, readBytes); //write

} catch (IOException ex ) {System.err.println(ex.toString());

}

Page 154: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 4 151

Activity 15: Use New I/O Classes to Read and Write Files

1. Open the Lesson4Activity14 project in NetBeans.

2. Open the Lesson4Activity13.java file.

3. Make sure to add the following statements to theLesson4Activity13.java file:

import java.nio.*;import java.nio.file.*;[program font ends here]

4. So that you can keep the code used in Activity 13 for fur-ther reference without affecting this activity’s code, you’llcomment the current code. To do this, highlight the cur-rent code in the main() method and then choose theToggle Comment option from the Source menu or thekeyboard shortcut CTRL+/.

5. Add the following code to the main() method as follows:

//Activity 15

Path file = Paths.get(“activity.txt”);

Charset cset = Charset.forName(“UTF-16”);

if (Files.notExists(file)) { //Check for file

System.out.println(“Enter text for new file. Hit ENTER on a blank line to end.”);

try (BufferedReader stdin = new BufferedReader( new

InputStreamReader(System.in));

BufferedWriter fout = Files.newBufferedWriter(file, cset);) {

String line = ““;

while ((line = stdin.readLine()) != null && line.length() != 0 ) {

fout.write(line);

fout.newLine();

}

fout.flush();

} catch (IOException ex) {

System.err.println(ex);

}

System.out.println(“File written.”);

} else {

System.out.println(“Reading file ....”);

try (BufferedReader fin = Files.newBufferedReader(file, cset);) {

String line = ““;

Page 155: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java152

This code checks to see if a file doesn’t exist. If the filedoesn’t exist, then it creates the file by reading each linefrom the command line and writing it to the file. If thefile does exist, then the contents of the file are read line-by-line and printed as output.

6. Build and run the project. You should be prompted towrite the contents of the file. You can write as many linesof text as you like. When you’re done, hit the ENTER keyon a blank line to finish writing to the new file.

7. Run the project again. Because the file was already written,the contents of the file should be displayed.

while ((line = fin.readLine()) != null) {

System.out.println(line);

}

} catch (IOException ex) {

System.err.println(ex);

}

}

Page 156: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 4 153

Self-Check 12

1. What are the differences between byte, character, and buffered streams?

__________________________________________________________

2. Which standard method is used to retrieve data from a stream? Which standard method isused to modify data in a stream?

__________________________________________________________

3. Which three predefined streams accept standard input and generate output and errors?

__________________________________________________________

4. How does the try-with-resources statement handle resource objects?

__________________________________________________________

5. Which interface in the java.nio package represents the location of a file or directory?

__________________________________________________________

Check your answers with those on page 205.

Page 157: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java154

ASSIGNMENT 13: USE MULTIPLE THREADSRead Assignment 13 in this study guide. Then read Chapter 11in your textbook.

Assignment 13 introduces multithreading concepts and howto use threads in Java as well as high-level threading classes.Be sure to complete the Try This activities in Chapter 11. It’shighly recommended that you read the Concurrency lesson in the Oracle Java Tutorials at http://docs.oracle.com/javase/tutorial/essential/concurrency/ before implementingmultithreading in any professional applications.

Threading Basics

A process is a unique runtime environment for a runningapplication. Each process contains its own state, memoryaddress, and set of resources. Processes can communicatewith each other, but not through direct memory access.These communication mechanisms are controlled by theoperating system, not the programmer.

A thread is a distinct task performed by an application.Threads can share state and memory, because they’re exe-cuted within the same process. Whereas multiple processorcores dictate how many concurrent processes can execute,application code dictates how many concurrent threads canexecute in a process.

It’s important to note that neither multiprocessing operatingsystems nor multithreaded applications execute their unitsexactly at the same time. There’s a system of schedulingrequired, where each execution unit, whether a thread orprocess, is assigned a slice of time in which to be active. Theexecution is active until the time expires; it completes or ahigher priority unit requires access. In the case of processes,the operating system controls access to hardware resources. Inthe case of Java threads, it’s the JVM that controls executionscheduling and execution.

Page 158: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 4 155

Creating Threads

By default, all Java applications have a single user threadknown as main. As you recall, the main() method is the firstpoint of entry for a Java application. All execution in themain() method is executed on the main thread. Even whencode outside the main() method is executed, the main threadis used, because the invocations originate from within themain() method. Thus, all applications you’ve developed so farare single-threaded.

To create custom threads, you can either implement theRunnable interface or extend the Thread class because theThread class implements the Runnable interface. Explicitlyimplementing the Runnable interface is preferred, but you’llstill use the Thread class to start and control the thread. Thetable at the bottom of page 369 in Chapter 11 of the textbooklists the most common Thread methods. The body for athread is defined within its run() method. The run() methodoften performs long-running calculations or complex iterativealgorithms. The run() method must match the following signature:

public void run()

The following code creates a thread class by implementingthe Runnable interface:

public class ThreadWithRunnable implementsRunnable {

public void run() {

//perform work

}

}

Note: Because the run()method can’t acceptarguments or returnvalues, input and out-put is handled bysharing fields betweenthreads. The Callableinterface is more flexiblewith its call() method,which can return avalue.

Page 159: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java156

The following code creates a thread class by extending theThread class:

public class ThreadWithThreadClass extends Thread{

public void run() {//perform work

}}

The real difference between these two techniques is overheadand how the thread is started. To start a thread, you mustuse the start() method of the Thread class. If the customthread class extends Thread, then you need to instantiateonly the Thread class and invoke start(). If the customthread class implements Runnable, then you need to instan-tiate the custom thread class, specify the thread object in theThread class constructor, and then invoke the start()method.

The following code demonstrates how to start threads usingboth techniques:

//thread instantiationThread thRunnable = new Thread(newThreadWithRunnable());Thread thThreadClass = newThreadWithThreadClass();//start the threadsthRunnable.start();thRunnable.start();

Thread Lifetime

Figure 9 depicts the states in a thread’s lifetime.

As indicated in the lifetime, the start() method doesn’t actu-ally run the thread, but places it in the runnable queue. Formost threads, the majority of their lifetime is spent in therunnable state. When a thread actually runs is determinedby the scheduler based on its priority and position in thequeue. A higher priority thread is more likely to receive exe-cution time than a lower priority thread. In many cases, ahigh-priority thread can dominate execution if other threads

Note: Although therun() method containsthe main body of athread, it’s actually thestart() method thatexecutes the body on aseparate thread.

Page 160: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 4 157

in the runnable queue are low-priority. To set a thread’s pri-ority, you can use the setPriority() method. The defaultpriority level is NORM_PRIORITY, with both MIN_PRIORITYand MAX_PRIORITY as the other options.

A thread can move from running back into the runnable stateby using the yield() method. The yield() method notifies thescheduler that a thread is willing to give up execution time forother runnable threads. Unfortunately, the exact implemen-tation differs by operating system. In Windows, the thread is forced to wait a specified amount of time, but then canimmediately resume its execution later. In Linux, the threadis forced to wait until all other threads in the queue executeat least once.

From the running state, a thread can also move into the blockedand dead state. A thread in the blocked state is effectivelypaused, waiting in memory for immediate execution. Likerunnable, the blocked state uses a queue for waiting threads.The operating system can interrupt a thread if a runtimeexception occurs or a higher priority thread requires execution.The sleep() method moves a thread into the blocked state fora predetermined number of milliseconds. After the time haselapsed, the thread is pushed into the wait queue for immediateexecution.

FIGURE 9—A Thread’s Lifetime

Page 161: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java158

The join() method is a bit more complex. When Thread1invokes the join() method on Thread2, Thread1 will beblocked until Thread2 is dead. A thread is considered dead ifthat thread completes its work or is stopped manually by theprogrammer or operating system. The isAlive() method indi-cates whether a thread is in any other state than dead.Remember that a thread is alive when it’s in the runnablequeue or blocked.

Activity 16: Create and Control a Custom Thread

1. Create a new Java Application project namedLesson4Activity16 in NetBeans.

2. Create a new public class named Timer to thelesson4Activity16 package.

3. Inside the Timer class, add the following code:

public class Timer implements Runnable {private boolean stopped;private long delay;

public Timer (long delay) {this.delay = delay;

}public void stop() { stopped = true; }public void run() {while (! stopped ) {

java.util.Date time = new java.util.Date();System.out.println(time);for (long i = 0; i < delay; i++);

}}}

This class is a simple timer that outputs the currenttime in a thread. The stop() method ends the timer.

4. Open the Lesson4Activity16.java file. You can do thiseither by clicking its tab at the top of Documentsbecause it should be open or by double-clicking theLesson4Activity16.java file in the Projects pane.

Page 162: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 4 159

5. Add the following code in the main() method:

6. Build and run the project. The timer should display untilyou hit the S key and ENTER. The only reason this worksis because the timer is displaying output on a separatethread from the main thread, which is listening for input.

Code Synchronization

For threads to communicate, they must share fields and objectreferences with each other. When multiple threads share datalike this, error conditions such as thread interference andmemory inconsistency can occur. In thread interference, twoor more operations running in different threads act on thesame data and overlap their sequence of execution. Threadinterference errors are difficult to detect, because the resultsare unpredictable. Memory inconsistency occurs when multi-ple threads see the same data differently. For example, whileThread1 is incrementing a counter variable, Thread2 may bereading the previous value and assuming it’s the current value.

To prevent these error conditions, you can use the synchro-nized keyword. The synchronized keyword can lock a block of statements or entire method, so that only one thread at atime can execute. When using the synchronized keyword

Timer tmr = new Timer(1_000_000_000);System.out.println(“Timer started. \’s\’ to stop”);new Thread(tmr).start();

while (true) {try {if (System.in.read() == ‘s’) {

tmr.stop();break;

}} catch (java.io.IOException ex) {System.err.println(ex);}}

System.out.println(“Timer stopped.”);

Note: By default, eachthread stores a copiedvalue from a sharedfield. A field declaredwith the volatile key-word will allow allthreads to use a mastercopy of value. If a fieldis bound to changeoften in multithreadedsituations, you mayfind more consistentresults by using thevolatile keyword.

Page 163: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java160

with a block of statements, you choose an object that repre-sents the lock. This usage of the synchronized keyword isknown as a synchronized statement. In most cases, the lockis the current object modified by the group of statements.

The following code demonstrates a synchronized statement:

synchronized(this) {this.counter++;

}

When using the synchronized keyword with a method, onlya single thread can execute the method at a time. This meansthat method invocations by other threads are blocked untilthe current thread returns from the method. This type ofmethod is known as a synchronized method.

The following code demonstrates a synchronized method:

public synchronized void increment(int value) {this.counter += value;

}

When using synchronized statements and methods, you cantake advantage of thread-related methods provided by theObject class. An overloaded version of the wait() methodtakes no argument and will move a thread into the blockedstate until it’s notified to resume. By default, this will movethe thread directly into the wait queue rather than having atimeout. The notify() method will resume a single threadfrom the wait queue. The resumed thread will be the firstthread in the queue. The notifyAll() method will attempt toresume all threads in the queue, so that the highest prioritythread will resume first.

A simple threading model that utilizes these methods is producer/consumer. The producer provides a resource that’s used by the consumer. A consumer thread invokes await() on itself to allow the producer to prepare access to theresource. When the resource is available, the producer threadthen invokes the notify() or notifyAll() methods. When theconsumer thread completes, it can then wait again untilresources are made available by the producer thread.

Page 164: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 4 161

High-Level Concurrency

If manual threading seems too complex to implement large-scale,don’t worry. Java offers high-level locking, thread pools, andconcurrent-safe collections to simplify multithreaded applications.These types are found in the java.util.concurrent package.

Table 7 lists these high-level concurrency types.

Table 7

Class Description

Lock An interface that allows explicit control for tryingto acquire and releasing a single-thread lock

ReadWriteLockAn interface that allows one lock to be shared byreader threads and another exclusive lock forwriter methods

Callable An interface implemented by threads which canreturn a value

RecursiveTask Abstract class that represents a task that can bedivided into recursive invocations

Future This interface represents the result from anasynchronous invocation

ExecutorService An interface for executing threads within automated thread pools

ScheduledExecutorService An interface for executing threads at set delayand/or repeated period

BlockingQueue, ConcurrentMap,ConcurrentMap

Interfaces implemented by collections that protect elements when multiple threads access those elements concurrently

Table 7—High-level Concurrent Classes

Page 165: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java162

The following code demonstrates usages of high-level concur-rency classes and interfaces:

This code generates a random number after a 10-second delay.

public class CalcThread implements Callable {//Callable implementationpublic Integer call() throws Exception {

//Get number from 1 to 10return ThreadLocalRandom.current().nextInt(1,11);

}public static void main(String[] args) {

ScheduledExecutorService ex =Executors.newScheduledThreadPool(1);

Callable c = new CalcThread();Future f = ex.schedule(c, 10, TimeUnit.SECONDS);while (!f.isDone()) {} //waitingtry {

System.out.println(f.get());ex.shutdown();

} catch (Exception e) {System.err.println(“Error: “ + e.toString());

}}

}

Page 166: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 4 163

Self-Check 13

1. How does a thread differ from a process?

__________________________________________________________

2. What are the two techniques for creating a custom thread class?

__________________________________________________________

3. How do the Runnable and Callable interfaces differ?

__________________________________________________________

4. What is the initial state of a thread after the start() method is invoked?

__________________________________________________________

5. What does the synchronized keyword allow?

__________________________________________________________

Check your answers with those on page 206.

Page 167: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java164

NOTES

Page 168: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 4 165

Advanced Programming Logic

OVERVIEW

Now you’re ready to add file I/O to your board game applica-tion. This project will assess your understanding of writing afile and using multithreading.

Make sure to follow all directions completely and verify yourresults before submitting the project for grading. Rememberto include all required components in your solution.

YOUR PROJECT

In this project, you’ll modify the BoardGameTester applicationto save the gameboard to a file. You’ll perform the file writingprocess on a separate thread.

INSTRUCTIONS

1. In NetBeans, open the BoardGameTester project.

2. Create a new package named games.utilities.

3. Add a public class named FileManager that contains thefollowing methods:

public static void writeToFile(String saveState, String

fileName) {

//TODO: Write a string to a new file synchronously

}

public static void writeToFileAsync(final String saveState,

final String fileName) {

//TODO: Write a string to a new file asynchronously

}

Gra

de

d P

roje

ct

Gra

de

d P

roje

ct

Page 169: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java166

4. Implement the writeToFile method using the new fileI/O classes in a try-with-resources statement.

Note: Use the code in Activity 15 as a guide for thewriteToFile method. Remember to import the java.io,java.nio, java.nio.charset, and java.nio.file packages.

5. Implement the writeToFileAsync method using a sepa-rate thread. Use the following code as a guide:

new Thread() {public void run() {writeToFile(saveState, fileName);}}.start();

Note: This code uses an anonymous inner class to declareand instantiate a Thread class. Unlike a traditional innerclass, anonymous inner classes are available only withinthe statement they’re declared. You’ll see more examplesof anonymous classes with Swing in the next lesson. Toensure that local variables are unchanged by the innerclass, the parameters saveState and fileName must bedeclared with the final keyword.

6. In the main() method of the BoardGameTester project,add the following code:

Note: Remember to import the games.utilities package!

7. Compile and run the project to create three files, one foreach saved board game. Open the files to ensure theycontain the correct game board display.

Note: Notepad won’t display the line returns in the file.You may need to open the text files using Microsoft Wordor Wordpad instead.

These three game board files will be required for submission.

FileManager.writeToFileAsync(ticTacToe.toString(), “ttt.txt”);FileManager.writeToFileAsync(connectFour.toString(), “c4.txt”);FileManager.writeToFileAsync(mastermind.toString(), “mm.txt”);

Page 170: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 4 167

SUBMISSION GUIDELINES

To submit your project, you must provide the followingsource code files in a ZIP file:

■ BoardGameTester.java

■ FileManager.java

■ ttt.txt

■ c4.txt

■ mm.txt

To find the Java source files within NetBeans, go to theBoardGameTester project folder. To determine this folder,right-click on BoardGameTester project in the Projectspanel. Copy the value for the Project Folder textbox usingthe keyboard shortcut CTRL+C. In Windows Explorer, pastethe project folder path and hit the ENTER key. Copy both theBoardGameTester.java file from the src\boardgametesterfolder and the FileManager.java file from thesrc\games\utilities folder to your desktop or any other tem-porary location. The three game board files will be located atthe root of the project folder.

Follow this procedure to submit your project online:

1. Log on to the Penn Foster website and go to My Courses.

2. Click Take Exam.

3. Attach your zip file as follows:

a. Click on the Browse box.

b. Locate the file you wish to attach.

c. Double-click on the file.

d. Click Upload File.

4. Enter your e-mail address in the box provided. (Note:This information is required for online submissions.)

5. If you wish to tell your instructor anything specificregarding this assignment, enter it in the Message box.

6. Click Submit File.

Page 171: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java168

GRADING CRITERIA

Your instructor will use the following guidelines to grade yourproject.

FileManager class correctly defined 40 points

BoardGameTester class correctly modified 20 points

All three game board files are correct 20 points

All source code and files are included: 20 points

TOTAL 100 points

Page 172: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 4 169

Graphical User Interface Design

INTRODUCTION

So far you’ve focused on developing command-line applicationsthat strictly control text-based input/output. Most modernapplications use a graphical user interface (GUI) for input/output and rely on user events to perform their operations. Inthis lesson, you’ll be introduced to the APIs for the abstractwindowing toolkit (AWT), Swing, and JavaFX. After completingthis lesson, you’ll be prepared to create robust and user-friendly applications in Java!

OBJECTIVES

When you complete this lesson, you’ll be able to

■ Discuss Java applet technology and life cycle

■ Create and use a Java applet

■ Use the Graphics class to paint text and basic shapes

■ Register and handle standard events

■ Differentiate Swing from the abstract windowing toolkit(AWT)

■ Explain the model-view-controller pattern

■ Use layout managers to organize Swing components

■ Create and add standard Swing components

■ Create an applet with Swing

■ Describe JavaFX technology

Le

ss

on

5L

es

so

n 5

Page 173: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java170

ASSIGNMENT 14: CREATEAPPLETS AND HANDLE EVENTS Read Assignment 14 in this study guide. Then read Chapter 14,pages 473–496, as well as Chapter 15, pages 536–537, in yourtextbook.

Create Applets and Handle Events

Assignment 14 introduces applets and event handling usingAWT, and covers anonymous inner classes, which are presentedin Chapter 15. Be sure to complete the Try This activities inChapter 14.

Applet Basics

An applet is a small GUI application embedded in a Webpage. Applets are often built as executable Java archive (JAR)files and are executed by the JVM associated with a brower’splug-in manager. Because applets are automatically loadedby the browser, Java applets run in security sandbox to pro-tect the client OS from malicious code. Unsigned applets arethose that aren’t signed with a valid certificate from a trustedcertificate authority (CA). They can’t access the local file sys-tem or other remote Web servers. Signed applets can run instandalone mode and are limited only by general OS security.

Applets are embedded in Web pages in the same way as othermultimedia is. In earlier versions of HTML, you would use the<applet> element, while the <object> element is preferred forHTML5. The following HTML embeds an applet in a Web page:

<object type=“application/x-java-applet”width=“800” height=“600”>

<param name=“code” value=“AppletClass” /><param name=“archive” value=“Applet.jar” />Applet failed to run. Please install the

Java plug-in.</object>

The type attribute specifies the Multipurpose Internet MailExtensions (MIME), so that the browser knows to use theJava plug-in. The code parameter specifies the applet class,

Page 174: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

while the archive parameter contains the location of the JARfile. If the JVM isn’t installed or not configured correctly inthe browser, the text in the <object> element is displayed inthe Web page.

AWT-based applets extend the Applet class and override thepaint() method. The paint() method receives a Graphicsobject from the JVM to draw text, shapes, and components in the applet.

The Graphics Context

One of the first aspects in GUI programming that you’ll needto get used to is how methods are used. Although you’ll con-tinue to write and invoke your own methods, more often thannot, the JVM environment will call methods automatically foryou. It’s your responsibility to implement or override certainmethods to execute custom code in response.

The paint() method is a good example of how this works.Because Applet is a subclass of Component and Container,it inherits the paint() method. In AWT, any time a componentor its container is resized or redisplayed in any way, thepaint() method is invoked. Rather than being concerned aboutthe complexity of painting graphics for each OS, the JVM pro-vides a concrete implementation of the abstract classGraphics to the paint() method. The Graphics object is alsoknown as the Graphics context, because the JVM with nativeOS-specific code provides the concrete class. As a program-mer, you need write only code in the paint() method that tellsthe Graphics context what to do.

The Graphics class contains many different methods for creat-ing simple and complex shapes, and drawing lines and text.One-dimensional segments and shape outlines are created byusing the drawXXX() methods, while filled shapes is createdby the fillXXX() methods. The setColor() method indicatesthe Color object used for painting colors, while setFont()specifies the Font object used for painting text. The followingmethods are common when painting shapes and text:

■ drawString()—Paints text using the specified x/y coordi-nate as the top-left corner of the text block.

Lesson 4 171

Page 175: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project172

■ drawLine()—Paints a line from one x/y coordinate to another.

■ drawArc() and fillArc()—Paints a line or filled area from anx/y coordinate within a rectangular block at specifiedstart and end angles.

■ drawRect(), fillRect(), draw3DRect(), and fill3DRect()—Paints closed rectangle outline, fill with or without a3-dimensional highlight starting at an x/y coordinatewith a specified width and height.

■ drawOval() and fillOval()—Paints a closed circular shapewithin a rectangular block starting from a top-left x/ycoordinate.

■ drawPolygon() and fillPolygon()—Paints a closed shapeusing an array of x/y coordinates or a Polygon object.

■ drawPolyline()—Paints an open shape using an array ofx/y coordinates.

To designate where something is painted, you must specifythe x/y coordinates of where it will appear in the component.The top-left corner is 0,0, while moving to the right increasesthe x value and moving down decreases the y value (Figure 10).

Take the following code:

Font font = new Font(“Arial”, Font.BOLD, 18 );String text = “Have a nice day!”;g.setColor(Color.YELLOW);g.fillOval(100,100,200,200);g.setColor(Color.BLACK);g.fillOval(150, 150, 25, 25);g.fillOval(225, 150, 25, 25);g.drawArc(150, 180, 100, 75, -180, 180);//Measure textFontMetrics measure = g.getFontMetrics(font);int txtWidth = measure.stringWidth(text);g.setColor(Color.RED);g.setFont(font);g.drawString(text, 100 + 200/2 - txtWidth/2, 325);

This code will generate an applet that paints the graphic inFigure 11.

Page 176: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project 173

Applet Life Cycle

Before the paint() method is called, the init() and start()methods are invoked by the JVM. The init() method is invokedonly once, while the start() method is invoked every time theapplet is restarted. The stop() is invoked whenever the appletis suspended. The final method invoked is destroy(). Thisoccurs only once when the applet is shut down. Unlikepaint(), the init(), start(), stop(), and destroy() methodsaccept no arguments.

A common action to take in the init() method is to retrievecustom parameters from the Web page. The following HTMLspecifies a custom parameter for an applet:

Figure 10—x/y Coordinates Figure 11—Graphic Code Output

<object type=“application/x-java-applet” width=“800” height=“600”><param name=“code” value=“AppletClass” /><param name=“archive” value=“Applet.jar” />

<param name=“username” value=“jhester” />Applet failed to run. Please install the Java plug-in.

</object>

Page 177: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project174

The following code retrieves the custom parameter username:

String username = getParameter(“username”);

Code in the init() method could also start other user threads,so that the code in destroy() would terminate those threads.Think of the start() and stop() methods as the methods thatare invoked when an applet is paused and then resumed.Rather than consume resources indefinitely, use the stop()method to stop painting and calculations, until the start()method is invoked.

To change what’s displayed in the applet after fields havebeen updated to new values, you should invoke the repaint()method. This is because iteration within the paint() methodwould make the applet unresponsive to user events. The JVMwill then invoke the paint() method again with the updatedvalues. An overloaded version of repaint() accepts a boundingrectangle with x/y coordinates and width and height, so thatonly a portion of the applet is repainted.

Of course, applets can do more than simply paint graphics.They can play audio clips, display images, and even resizethemselves. Table 14-1 on pages 488–489 in the textbooklists all of the methods provided by the Applet class. Becausean Applet is a direct subclass of Panel, it inherits methodsfrom the AWT classes Panel, Container, and Componentas well.

Page 178: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Activity 17: Create a Basic Java Applet

1. Create a new Java Application project namedLesson5Activity17 in NetBeans.

2. Replace the Lesson5Activity17.java with the following code:

3. Run the file by right-clicking on theLesson5Activity17.java file in Projects and choosing theRun File option in the contextual menu or using theSHIFT+F6 keyboard shortcut. This technique will auto-matically compile and run the class in the defaultappletviewer.

4. The applet should display a target with concentric blackand red circles.

Event Delegation ModelApplets, like any application with a GUI, are event driven. Thismeans that rather than pushing the user through a predefinedalgorithm and prompting for input whenever it’s needed, aGUI application is primarily concerned with responding touser interactions whenever they occur. Such user interac-tions occur when a user clicks on a button, clicks and dragsacross the screen, or touches a tablet screen. These userinteractions are called events.

import java.awt.*;import java.applet.*;public class Lesson5Activity17 extends Applet {public void init() { System.out.println(“Applet initialized!”); }public void start() { System.out.println(“Applet started!”); }public void stop() { System.out.println(“Applet stopped!”); }public void destroy() { System.out.println(“Applet destroyed!”); }public void paint (Graphics g) {for (int circles = 0; circles < 6; circles ++) {

g.setColor((circles % 2 == 0)? Color.BLACK : Color.RED);int size = 30 * circles;int align = size /2;g.fillOval(0 + align, 0 + align, 180 - size, 180 - size);

}}}

Graded Project 175

Page 179: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java176

Events are divided by source and type. If a user clicks on abutton, then that button will generate an ActionEvent. If auser changes the value in a textbox, then that textbox willgenerate a TextEvent. Hardware devices like keyboards andmice also generate events. Table 14-2 on page 491 in thetextbook lists commonly used event classes.

Event Listening and Registration

To respond to an event, you need to use an event listener. Anevent listener is registered with one or more sources and isnotified when that event occurs. Event listeners are interfacesin Java, so you must implement an interface to receive andrespond to event notifications. The listener interface containsone or more methods that are invoked with the event type.Table 14-3 on page 492 in the textbook lists commonly usedlistener interfaces.

The following code implements the MouseListener andMouseMotionListener interfaces for a simple line drawingapplication:

public class MouseHandler implements MouseListener, MouseMotionListener {

int prevX, prevY, curX, curY;public void mouseClicked(MouseEvent me) {/*do nothing */}public void mouseMoved(MouseEvent me) {/*do nothing*/}public void mouseEntered(MouseEvent me) {

System.out.println(“Listening for mouse events!”);}public void mouseExited(MouseEvent me) {

System.out.println(“Ignoring mouse events!”);}public void mousePressed(MouseEvent me) {

prevX = me.getX(); prevY = me.getY();}public void mouseDragged(MouseEvent me) {

curX = me.getX(); curY = me.getY();}public void mouseReleased(MouseEvent me) {

//draw line from prevX,prevY to curX,curY}

}

Page 180: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 5 177

Most listener interfaces are restricted to one or two methods,but not so for low-level events involving keyboards, mice, focus,and windows. Unfortunately, you’ll notice that implementingan interface is all or nothing. You can’t implement a fewmethods of an interface—you must implement all methods,even if your application doesn’t need to listen for those events.Java provides listener adapter classes as a workaround for thisissue. For example, instead of implementing the MouseListener,MouseMotionListener, and MouseWheelListener interfaces,you could simply subclass MouseAdapter. Java providesadapter classes that combine many related listener interfaces.These adapter classes include MouseAdapter,MouseMotionAdapter, FocusAdapter, KeyAdapter, andWindowAdapter.

The previous class could be briefer using the MouseAdapterclass:

public class MouseHandler extends MouseAdapter {int prevX, prevY, curX, curY;public void mousePressed(MouseEvent me) {

prevX = me.getX(); prevY = me.getY();}public void mouseDragged(MouseEvent me) {

curX = me.getX(); curY = me.getY();}public void mouseReleased(MouseEvent me) {

//draw line}

}

To ensure that the listener is notified when an event occurs,you must register that listener with the event source. Javaprovides addXXXListener() and removeXXXListener() meth-ods to allow components to provide or withhold notifications,respectively.

Page 181: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java178

The following code will instantiate the MouseHandler class to handle events associated with the MouseListener andMouseMotionListener interfaces:

MouseHandler mouseHandler = new MouseHandler();addMouseListener(mouseHandler);addMouseMotionListener(mouseHandler);

It’s common to register listeners within the start() method ofan applet and then remove those listeners in the stop() method.By doing this, you’re reducing the resource consumption whilethe user isn’t actively using the applet.

The following code removes notification of mouse-related events:

removeMouseListener(mouseHandler);removeMouseMotionListener(mouseHandler);

Anonymous Inner Classes

Often, listener classes are declared as inner classes within theircomponents. This is because listener classes usually requireaccess to the same Graphics context as the component andmay need to share important fields and methods within theclass. This is the preferred technique in most cases.

The following code declares the MouseHandler class withinan applet class:

public class DrawApplet extends Applet {MouseHandler mh;public void init() {

mh = new MouseHandler();}public void start() {

addMouseListener(mh);addMouseMotionListener(mh);

}public void paint(Graphics g) {

g.drawLine(mh.prevX, mh.prevY, mh.curX, mh.curY);}public void stop() {

removeMouseListener(mh);removeMouseMotionListener(mh);

}

Page 182: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 5 179

Because the listener object is referenced multiple times in theinit(), start(), paint(), stop(), and destroy() methods, thiscode makes sense as a formally named class. But what if youwanted to declare a listener class, but used it only once andnever needed to reference the class again?

Welcome to anonymous inner classes. An anonymous innerclass is one that’s defined when it’s instantiated or “on-the-fly.”As you might guess, because the class is anonymous, youcan’t refer to the class again and can access its methods onlythrough the object. Thus, anonymous classes can contain onlyinstance members. The following code defines an anonymousinner class for a listener to keyboard events:

addKeyListener( new KeyAdapter() {

public void keyTyped(KeyEvent ke) {if(ke.getKeyChar() == ‘s’) {

saveToFile();}

}}

);

public void destroy () {mh = null; //dereferenced

}//inner listener classclass MouseHandler extends MouseAdapter {

int prevX, prevY, curX, curY;public void mousePressed(MouseEvent me)

{prevX = me.getX(); prevY = me.getY();

}public void mouseDragged(MouseEvent me)

{curX = me.getX(); curY = me.getY();

}public void mouseReleased(MouseEvent me) {

repaint(); //in the Applet class}

}}

Page 183: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java180

The class has no name, so you need only specify an interfaceor superclass name. An anonymous inner class can’t imple-ment more than one interface or extend a superclass andimplement an interface. You must choose only one way ofinheriting interface or implementation.

As you’ll notice, the convenience of anonymous inner classesis overwhelmed by the increased complexity it introduces intoyour code. Anonymous inner classes are often used for eventhandling, so you should be aware of them even if you choosenot to use them often in your applications.

Activity 18: Create an Interactive Applet

1. Open the Lesson5Activity18 project in NetBeans.

2. In the Lesson5Activity18.java file, add the followingimport statement:

import java.awt.event.*;

3. In the Lesson5Activity18.java file, add the members tothe Lesson5Activity18 class:

private StringBuilder input = newStringBuilder();private KeyHandler kh = new KeyHandler();private class KeyHandler extends KeyAdapter {public void keyTyped (KeyEvent ke) {input.append(ke.getKeyChar());repaint();}

This listener class will allow you to type text in theapplet.

4. In the start() and stop() methods, make the followingmodifications:

public void start() {System.out.println(“Applet started!”);

this.addKeyListener(kh);

}

public void stop() { System.out.println(“Applet stopped!”);

Page 184: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 5 181

this.removeKeyListener(kh);

}

5. Add the following code to the paint() method:

g.setFont(new Font(“Arial”, Font.PLAIN, 14));g.setColor(Color.GREEN);g.drawString(input.toString(), 50, 50);

6. Run the file in the appletviewer by right-clicking on theLesson5Activity18.java file in Projects and choosingthe Run File option in the contextual menu or using theSHIFT+F6 keyboard shortcut.

7. When you type keys on the keyboard, you should seethem written to the applet.

Page 185: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java182

Self-Check 14

1. What is an applet? How does it differ from a traditional stand-alone application?

__________________________________________________________

__________________________________________________________

2. Which method should you override to create the visual elements of an AWT-based applet?

__________________________________________________________

3. Which Graphics method should you use to paint the outline of a circle? Which Graphicsmethod should use to paint an open shape?

__________________________________________________________

__________________________________________________________

4. What is the role of the source and listener in the event delegation model?

__________________________________________________________

5. What is an anonymous inner class?

__________________________________________________________

Check your answers with those on page 206

Page 186: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 5 183

ASSIGNMENT 15: USE SWINGRead Assignment 15 in this study guide. Then read Chapter 15in your textbook.

Assignment 15 continues GUI development by introducingSwing. This assignment also mentions the current evolutionof GUI development with JavaFX. Be sure to complete theTry This activities in Chapter 15.

AWT and Swing

The difference between the abstract windowing toolkit (AWT)and Swing is stark. With AWT, the focus was on having GUIapplications rely heavily on native code, so that an applicationdeveloped in Java would look and feel similar to non-Javaapplications developed for that platform. With Swing, compo-nents have a unique look and feel that’s consistent acrossJava applications and platforms. In AWT, two componentsrepresented every visual element: a native implementationand a Java abstract class. In Swing, all visual elements arepure Java. For this reason, AWT components are known asheavyweight, while Swing components are considered light-weight. Although Swing still uses AWT for much of itsplumbing, specifically events and graphics, its componentsare much more robust and customizable than those directlyprovided by AWT.

Swing is highly customizable, because its components implementa modified model-view-controller (MVC) pattern. In MVC,implementation is separated into three different elements: amodel that represents the underlying object state, a view thatdisplays that state, and a controller which modifies that state.The view is responsible for output only, while the controlleraccepts the input. The model is invoked by the view to be readand invoked by the controller to be modified. This means thata single object could have different views and be modified bymore than one type of input. In Swing, the model and vieware combined into a single thing known as the UI delegate.

Page 187: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java184

In other words, a button doesn’t have to resemble a standardrectangle or behave in the same way as every other button. Abutton could be circular, transparent, or accept input via amouse drag rather than a mouse click. In Swing, the onlylimitations are your imagination and the expectations of your users!

Containers and Layout Managers

Swing takes advantage of the concept of containership.Components aren’t lone elements, but placed within otherelements, similar to placing smaller boxes within largerboxes. Top-level containers are at the top of the hierarchyand can’t be placed into other containers. The JWindow,JDialog, and JFrame containers are used for stand-aloneapplications, while the JApplet container is intended forSwing-based applets. The JFrame container is a standardapplication window, but JWindow and JDialog are intended forcustomized windows and dialogs that don’t contain standardinterface elements.

Each top-level container defines a set of dividers known aspanes. The top pane in the hierarchy is the JRootPane. Youcan manually divide the interface further by using the JPanelclass. A layout manager controls how components and sub-panes are arranged in a pane. To specify a layout manager,you use the setLayout() method. You can choose from manydifferent layout manager classes.

The simplest layout manager is FlowLayout (Figure 12).Components are laid out from left to right or right to left andtop to bottom, based upon the available size in the container.Components can be aligned horizontally by center, left orright. A pixel amount can be specified for the horizontal andvertical gap between components. This is the default layoutmanager for JPanel objects.

Figure 12—FlowLayoutExample

Page 188: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 5 185

The next layout manager is GridLayout (Figure 13).Components are laid out by row and column, where eachcomponent expands to fit its destination cell. LikeFlowLayout, you can also specify a horizontal and verticalgap between cells.

Another simple layout manager is BorderLayout (Figure 14).With this layout manager, the panel is divided into five differentregions: PAGE_START, PAGE_END, LINE_START,LINE_END, and CENTER. Components inserted into thePAGE_START and PAGE_END regions will have the preferredheight, but expand to fit the width of the panel. Componentsinserted into the LINE_START and LINE_END regions willhave the preferred width, but expand to fit the height of thepanel. Components in the CENTER region will expand to fillany empty regions. You can also specify a horizontal and ver-tical gap between cells.

A more complex layout manager is GridBagLayout (Figure 15).Like GridLayout, the panel is divided into rows and columns.Unlike GridLayout, rows and columns can be different sizesand cells can span more than a single row or column. Also,you can ensure components use preferred widths and heightsby specifying sizing constraints.

Figure 13—GridLayoutExample

Figure 14—BorderLayoutExample

Figure 15—GridBagLayout

Page 189: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java186

BoxLayout (Figure 16) is a more flexi-ble version of FlowLayout. LikeFlowLayout, controls are eitherstacked vertically or lined up horizon-tally. The Box class provides customfillers known as struts to provide hori-zontal gaps between components andglue to create automatic space thatgrows vertically or horizontally. Rigidareas are fixed elements that can fillspace both vertically and horizontally.

CardLayout is a layout manager that allows you to stackgroups of components on top of each other. BecauseCardLayout only allows switching between groups using acombo box, the JTabbedPane component is the preferredtechnique for organizing groups of controls. To use theJTabbedPane component, you add components to a JPaneland then add that JPanel as a tab (Figure 17).

The other layout managers like GroupLayout andSpringLayout are intended for IDEs with visual designers. Ifyou add a Swing GUI Form such as JDialog, JFrame,JPanel, or JApplet to a NetBeans project, then you can useeither of these layout managers to click and drag componentsfrom a toolbox onto a visual designer (Figure 18). You canalso place components using absolute positioning as well.

Figure 16—BoxLayout Example

Figure 17—JTabbedPaneExample

Page 190: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 5 187

Swing Components

All Swing components are derived from the JComponentclass, including JFrame. The table on page 507 of the text-book lists common Swing components, some of which arecontainers themselves. To add a component to a container,you need only invoke its add() method; to remove it, you usethe remove() method. If using a layout manager that requiresadditional information on where to place the component,such as BorderLayout and GridLayout, you should specifythose arguments as well.

The following code adds a button to a JFrame usingBorderLayout:

frame.add( new JButton(“Button 1”),BorderLayout.PAGE_START);

Figure 18—NetBeans Visual Designer

Note: You’re not expectedto use the NetBeansvisual designer for proj-ects or activities. Ifyou’re familiar withGUI-based interfacedesign, then you’re wel-come to use the visualdesigners in NetBeansto reduce the amountof code you type.

Page 191: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java188

As for JFrame properties, its constructor can accept a Stringfor its window title and GraphicsConfiguration for the devicescreen. The setSize() method will set the width and height ofthe window in pixels, while the setVisible() method isrequired to display the window. By default, closing a JFramewon’t stop the application from running. To change thisbehavior, invoke the setDefaultCloseOperation() methodwith the EXIT_ON_CLOSE constant.

Event handlers in Swing use a special thread known as theevent dispatcher. To launch a JFrame object from the main()method so that it uses the event dispatcher thread, ratherthan the main thread, you should use the invokeLater() orinvokeAndWait() methods from the SwingUtilities class. TheinvokeLater() method is intended for the initial load instandalone applications, while the invokeAndWait() is usedfor UI updates when outside the event dispatcher thread andis intended for applets.

The following code uses an anonymous inner class thatimplements Runnable to instantiate JFrame:

SwingUtilities.invokeLater( new Runnable () {public void run() { new CustomJFrame(); }

});

Read through pages 515–530 in your textbook for an intro-duction to the JButton, JTextField, JCheckBox, and JListcomponents. Other common Swing components you’ll probablyuse include JTextArea, JComboBox, JMenuBar, JSpinner,and JSlider. You can visit the Java tutorials on Oracle’s web-site for usage details on other important Swing components:http://tinyurl.com/cu69r87

Notice that Swing components use the same event delegationmodel you learned for AWT-based applets.

Activity 19: Create a Line Drawing Application with Swing

1. Create a new Java Application project namedLesson5Activity19 in NetBeans.

2. Replace the contents of Lesson5Activity19.java with thefollowing code:

Page 192: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 5 189

import java.awt.*;import java.awt.event.*;import java.util.*;import javax.swing.*;

public class Lesson5Activity19 extends JFrame {ArrayList<Point> drawPoints = new ArrayList<>();Color penColor = Color.BLACK;private Lesson5Activity19() {//initializePaintComponent comPaint = new PaintComponent();comPaint.setBackground(Color.WHITE);comPaint.setSize(300, 300);JPanel panButton = new JPanel();panButton.setLayout(new GridLayout(4,0));//create buttonsJButton btnBlack = new JButton(“Black”);btnBlack.setForeground(Color.WHITE);btnBlack.setBackground(Color.BLACK);panButton.add(btnBlack);JButton btnRed = new JButton(“Red”);btnRed.setForeground(Color.BLACK);btnRed.setBackground(Color.RED);panButton.add(btnRed);JButton btnGreen = new JButton(“Green”);btnGreen.setForeground(Color.BLACK);btnGreen.setBackground(Color.GREEN);panButton.add(btnGreen);JButton btnBlue = new JButton(“Blue”);btnBlue.setForeground(Color.BLACK);btnBlue.setBackground(Color.BLUE);panButton.add(btnBlue);//add listenersMouseHandler mh = new MouseHandler();comPaint.addMouseListener(mh);ActionHandler ah = new ActionHandler();btnBlack.addActionListener(ah);btnRed.addActionListener(ah);btnGreen.addActionListener(ah);btnBlue.addActionListener(ah);this.setLayout(new BorderLayout());this.add(comPaint, BorderLayout.CENTER);

Page 193: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java190

this.add(panButton, BorderLayout.LINE_END);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.setTitle(“Lines with Swing”);this.setSize(350, 300);this.setVisible(true);}public static void main(String[] args) {SwingUtilities.invokeLater( new Runnable () {

public void run() { new Lesson5Activity19(); }});}//inner classesprivate class PaintComponent extends JComponent {public void paint(Graphics g) {

g.setColor(penColor);for (int i = 1; i < drawPoints.size(); i ++) {

g.drawLine(drawPoints.get(i-1).x, drawPoints.get(i-1).y, drawPoints.get(i).x, drawPoints.get(i).y);

}}}private class MouseHandler extends MouseAdapter {public void mousePressed(MouseEvent me) {

drawPoints.add(new Point(me.getX(), me.getY()));}public void mouseReleased(MouseEvent me) {

drawPoints.add(new Point(me.getX(), me.getY()));repaint();

}}private class ActionHandler implements ActionListener {public void actionPerformed(ActionEvent ae) {

JButton button = (JButton) ae.getSource();penColor = button.getBackground(); //Set to button back-

ground color}}}

Page 194: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 5 191

Look carefully at this code. It uses a two-panel layout todisplay a custom component for drawing and a panel forcolor buttons. When you click on two different places inthe drawing panel, a line is drawn between the two points,connecting any previous points as well. The buttonschange the color of these lines.

3. Build and run the project. Once you get the hang of it,try customizing the application to draw other shapes.

Applets with Swing

How different is it to create a Swing-based applet than anAWT-based applet? Only two main differences exist. First, the Swing-based applet must be a subclass of JApplet,rather than Applet. Second, the UI is built on the event dis-patcher thread by invoking theSwingUtilities.invokeAndWait() method. Because JApplet isa subclass of Applet, the lifetime methods init(), start(),stop(), and destroy() are the same.

The example code on pages 537–538 demonstrates a Swing-based applet. It should look very recognizable to you, combiningwhat you learned about applets and Swing in one place.

JavaFX

Although Swing-based applications are still very common, thenext generation of Java GUI applications is using JavaFX(Figure 19). JavaFX provides rich graphics and robust anima-tion support for applications that are designed to run acrosstraditional desktop, mobile, and embedded platforms. The APIfor JavaFX is very similar to Swing in many respects, but itprovides a greater range of visual customization and multi-media support. All UI classes and interfaces for JavaFX arelocated in the javafx package, and no implementation isreused from AWT or Swing.

Page 195: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java192

JavaFX applications extend the Application class and use theirstart() method as the main entry point. Content is stored on a stage, divided by scenes and further by frames. JavaFX alsosupports standard Web technologies such as HTML and CSS(Cascading Style Sheets) for content and styling.

Although a more thorough discussion on JavaFX is outsidethis course, the NetBeans IDE contains a few samples forJavaFX applications that you can run and modify to becomemore familiar. You can also visit the JavaFX documentationprovided by the Oracle website at http://docs.oracle.com/javafx/index.html for detailed tutorials and step-by-stepexercises.

Figure 19—Colorful CirclesSample Project for JavaFX

Page 196: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Lesson 5 193

Self-Check 15

1. How does Swing differ from AWT?

__________________________________________________________

2. What is the MVC pattern and how does Swing modify it?

__________________________________________________________

3. Which layout manager is optimal for a table-like layout that allows components to expandmore than one column or row?

__________________________________________________________

4. Which method must you use to instantiate a JFrame object? Which method must you invoke on a JFrame object for it to display?

__________________________________________________________

__________________________________________________________

5. How does JavaFX differ from Swing?

__________________________________________________________

Check your answers with those on page 207.

Page 197: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Programming in Java194

NOTES

Page 198: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graphical User Interface

OVERVIEW

Now you’ll develop a graphical user interface for theTicTacToe game. This project will assess your understandingof AWT, Swing, and event handling.

Make sure that you follow all directions completely and verifyyour results before submitting the project. Remember to includeall required components in your solution.

YOUR PROJECT

In this project, you’ll create the GUI front-end for the TicTacToegame. This application will leverage the classes you wrote inthe graded project for Lesson 3. You’ll copy code from GradedProject 3 for this project.

Figure 20 is a guide for the completed user interface.

195

Gra

de

d P

roje

ct

Gra

de

d P

roje

ct

FIGURE 20—The CompletedTic Tac Toe Game

Page 199: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project196

INSTRUCTIONS

1. In NetBeans, create a new Java Application projectnamed TicTacToeGUIGame.

2. Copy the games.board package from the Lesson 3 proj-ect named BoardGameTester.

■ Right-click on the game.board package in theBoardGameTester project of the Projects panepanel.

■ Choose the Copy option from the context menu oruse the keyboard shortcut CTRL+C.

■ Paste it in the TicTacToeGUIGame project using thePaste option in the context menu or the keyboardshortcut CTRL+V.

Make sure to copy and paste the package in the SourcePackages folder.

3. In the Cell.java file, have the Cell class extend theJButton class. This action will ensure that each cell onthe board has the look and feel of a standard Java button.

4. Override the paintComponent method in the Cell class as follows:

public void paintComponent(Graphics g) {

//paint the basic button first

super.paintComponent(g);

int offset = 5;

Graphics2D g2 = (Graphics2D) g;

g2.setStroke(new BasicStroke(5));

switch(content) {

case NOUGHT:

g2.setColor(Color.RED);

//Draw O

g2.drawOval(offset, offset, this.getWidth() - offset * 2, this.getHeight() - offset * 2);

break;

case CROSS:

g2.setColor(Color.BLACK);

//Draw X

Page 200: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project 197

Note: This code uses the enhanced Graphics2D class to set the stroke thickness to more than one pixel. TheOracle documentation provides more guidance on creat-ing complex geometric shapes using the Graphics2Dclass at http://docs.oracle.com/javase/tutorial/2d/geometry/index.html. Remember to import thejava.awt and javax.swing packages!

5. In the Board.java file, have the Board class extend theJPanel class. This action will ensure that the board canlay out each cell and process its UI events.

6. Make the following modifications to the Board constructor:

These changes will add each cell to the UI and assign anActionListener object to each cell.

Note: Remember to import the java.awt, java.awt.event,and javax.swing packages.

7. In the TicTacToeGUIGame.java file, have theTicTacToeGUIGame class extend JFrame. This action will ensure that the game is hosted in a Java window.

8. Import the games.board, java.awt, and javax.swingpackages.

g2.drawLine(offset, offset, this.getWidth() - offset , this.getHeight() - offset );

g2.drawLine(this.getWidth() - offset, offset , offset, this.getHeight()- offset);

break;

}

}

public Board(int rows, int columns, ActionListener ah) {cells = new Cell[rows][columns];this.setLayout(new GridLayout());for( int r = 0; r < cells.length; r++ ) {

for (int c = 0; c < cells[r].length; c++) {cells[r][c] = new Cell(r,c);this.add(cells[r][c]);cells[r][c].addActionListener(ah);

}}}

Page 201: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project198

9. Add the following code to the main method:

SwingUtilities.invokeLater( new Runnable () {public void run() { new TicTacToeGUIGame(); }});

10. Declare the following instance variables inTicTacToeGUIGame:

private Board gb;private int turn;

11. Add the following method to handle each turn:

private void takeTurn(Cell c) {Mark curMark = (turn++ % 2 == 0)? Mark.NOUGHT: Mark.CROSS;gb.setCell(curMark, c.getRow(), c.getColumn());}

12. Define the following constructor to create the board, provide the event listener, and display the board in the window:

private TicTacToeGUIGame() {gb = new Board(3, 3, new ActionListener() {public void actionPerformed(ActionEvent ae) {Cell c = (Cell) ae.getSource();takeTurn(c);}});this.add(gb);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.setTitle(“TIC-TAC-TOE”);this.setSize(300, 300);this.setVisible(true);}

13. Compile and run the project. Test to make sure eachbutton displays a nought or cross when clicked.

Page 202: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project 199

SUBMISSION GUIDELINES

To submit your project, you should submit the final JAR file:

TicTacToeGUIGame.jar

To ensure the JAR file is built, you should click the Buildbutton or hit the F11 key.

To find the JAR file with NetBeans, go to theTicTacToeGUIGame project folder. To determine this folder,right-click on TicTacToeGUIGame project in the Projectspanel. Copy the value for the Project Folder textbox usingthe keyboard shortcut CTRL+C. In Windows Explorer, pastethe project folder path and hit the ENTER key. Copy theTicTacToeGUIGame.jar file from the dist folder to your desktopor any other temporary location.

Follow this procedure to submit your project online:

1. Log on to the Penn Foster website and go to My Courses.

2. Click Take Exam.

3. Attach your file as follows:

a. Click on the Browse box.

b. Locate the file you wish to attach.

c. Double-click on the file.

d. Click Upload File.

4. Enter your e-mail address in the box provided. (Note: Thisinformation is required for online submissions.)

5. If you wish to tell your instructor anything specificregarding this assignment, enter it in the Message box.

6. Click Submit File.

Page 203: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Graded Project200

Grading Criteria

Your instructor will use the following guidelines to grade your project.

Cell class is modified correctly 20 points

Board class is modified correctly 20 points

The game window displays correctly 20 points

The buttons behave correctly when clicked 20 points

JAR file is provided: 20 points

TOTAL 100 points

Page 204: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

201

An

sw

er

sA

ns

we

rs

Self-Check 11. Procedural programming languages use step-by-step

instructions, while object-oriented programming (OOP)languages model real-world structures and relationships.Procedural programming languages separate data andinstructions, but object-oriented languages combinethem into fields and methods of objects.

2. A Java application that’s written and compiled can runon any platform with the Java Virtual Machine (JVM)installed. The developer doesn’t need to write code for aspecific CPU, motherboard, chipset, or operating system.

Self-Check 21. Java Micro Edition (ME) is a configurable subset of Java

SE (Standard Edition), because it must support smaller,embedded devices that can’t store all class librariesfound in SE.

2. The JDK (Java Development Kit) is required to writeapplications, because it includes the compiler and other developer tools. The JDK isn’t required to run Javaapplications—only the JRE (Java Runtime Environment)is needed. The JRE includes the JVM (Java VirtualMachine), runtime commands and applications, andessential class libraries.

Self-Check 31. The extension of a source code file is .java and the

command that compiles it is javac.

2. The extension of a bytecode file is .class and the com-mand that runs it is java or javaw.

Page 205: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Self-Check 41. Primitive data types are built-in data types that are fixed

in size and stored only in the default memory stack.

2. Integers are whole numbers, while floating-point numberssupport fractional values. Floating-point numbers usescale and precision to represent values, while integersonly reserve a dedicated sign bit.

3. You should use explicit casting for a data type whenmoving values from a larger container into a smaller one.The conversion could result in a loss of precision, so youmust use explicit casting.

4. The value of the result is 7.0. According to operator prece-dence, the parenthetical subtraction will occur first(5 – 10) to yield –5. Then, the modulus operator will beused (15 % 7) to yield a remainder of 1. Next, the multi-plication operation will be performed (1 * 10) to yield 10.Remember the ^ operator is used for bitwise XOR opera-tions, so it will be performed last. The addition operationoccurs next (–5 + 10) and yields 5. Finally, the XORoperation compares 5 (0b101) to 2 (0b010) and yields 7(0b111). The final result will be 7.0 because the resultvariable is a double. For more on bitwise and shift oper-ators, read pages 166–171 in Chapter 5 of the textbook.

5. The value of charVal is R. The toUpperCase() methodreturns the String value as STRINGS OF JAVA. ThecharAt() method with the 2 argument will return thethird character R.

Self-Check 51. The do-while statement executes at least once, because

the while expression isn’t evaluated until after the firstiteration.

2. The for statement uses an explicit counter to loop.

3. The break and continue statements. The break state-ment exits out of an iterative loop, while the continuestatement skips to the next iteration.

Self-Check Answers202

Page 206: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Self-Check Answers 203

4. A method can return only one value. A method may notreturn a value if its return type is void.

5. No arguments are required for a varargs parameter. Zeroor more arguments can be specified for a varargs parameter.

Self-Check 61. In Java, elements in an array must be the same data

type, the length of an array must be an int, and itslength is fixed and can’t be modified.

2. The length field returns the number of elements in thearray.

3. The index value 0 will return the first element in thearray, because arrays use zero-based indexing.

Self-Check 71. An exception is simply an abnormal condition that

occurs in a program. Some exceptions are errors fromwhich an application can’t recover, while others can behandled by users or programmers to continue runningthe application.

2. The try/catch blocks handle exceptions. The try blockcontains code that might throw an exception, while thecatch block performs an action when the exception isactually thrown.

3. The throws keyword is used in method declarations toindicate that invoking the method will require dealingwith a specific exception, while the throw keyword isused to manually throw an exception within a method.

Page 207: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Self-Check Answers204

Self-Check 81. Object references are stored in the memory heap and are

actually pointers to that object’s data, whereas primitivetypes are stored on the memory stack and only contain a value.

2. Encapsulation is designing an object so that its state(fields) is protected from direct access and all interac-tions with the object involve its behaviors (methods).

3. Instance members are unique to each object, whereasclass members affect all objects of a class.

4. A class is instantiated when the new keyword is usedand memory in the heap is reserved. An object is final-ized when the garbage collector prepares to delete theobject from memory and invokes the finalize() method.

Self-Check 91. Inheritance is when one or more classes inherit code

from another class. The superclass contains the inher-ited code, while its subclasses are those that receive theinherited code.

2. The output is Sub print() because the print() methodis overridden in Subclass. Polymorphism dictates thatthe actual method invoked depends on the type of theobject, not the reference type of its variable. Although thevariable obj is of type SuperClass, the actual object is oftype SubClass.

3. Abstract classes are those that can’t be instantiated butcan contain methods without definition code. Concreteclasses are subclasses that provide the definition forabstract methods.

4. In Java, a package prevents naming conflicts betweenclasses and other types and provides an organized hier-archy for data types.

Page 208: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

Self-Check 101. The phrase “inheritance without the side effects” describes

how using interfaces ensures only the method declarations,not the implementation details of each method, areinherited by each class. Also, in class inheritance, there’stight coupling and only a single class can be inherited. Ininterface implementation, there’s loose coupling andmultiple interfaces that can be implemented by a singleclass.

2. Abstract classes can contain implementation and onlysupport single inheritance. Interfaces can’t containimplementation, but support multiple inheritance.

3. An enumeration is a custom data type that contains alimited set of named values.

Self-Check 111. Type wrappers are special classes that represent primi-

tive values, so that they can be stored, used, and passedas objects.

2. Autoboxing is the automatic boxing of primitive typesinto objects and unboxing of objects into primitive types.This is provided by the runtime without requiring manualboxing or unboxing with type wrapper methods.

3. Only those object types that implement the genericComparable interface are allowed for both the arrayand elem parameters.

Self-Check 121. A byte stream reads/writes un-encoded data bytes, while

a character stream code/encodes that data. Bufferedstreams wrap character streams so that characters canread/write line by line, rather than character by character.

2. The read() method is standard for input streams whichretrieve data from a stream. The write() method is stan-dard for output streams which modify data in a stream.

Self-Check Answers 205

Page 209: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

3. System.in is the standard method for retrieving data usingthe keyboard. System.out and System.err are used togenerate output for all-purpose and error text, respec-tively.

4. Resource objects are automatically closed and derefer-enced at the end of a try-with-resources block. If theclose() method throws an exception, then any otherexceptions thrown in the try-with-resources block will be suppressed.

5. The Path interface represents the location of a file ordirectory in the java.nio package.

Self-Check 131. A thread is a task performed by an application and can

be controlled by the programmer. A process is a uniqueruntime environment for a running application that iscontrolled by the OS.

2. You can either implement the Runnable interfacedirectly or extend the Thread class, which also imple-ments the Runnable interface.

3. The Runnable interface provides a run() method thatcan’t return a value, while the Callable interface providesa call() method that can return a value.

4. The initial state is runnable after the start() method isinvoked for a thread.

5. The synchronized keyword allows access to a code blockor method by only one thread at a time.

Self-Check 141. An applet is a small GUI application embedded in a Web

page. Unlike stand-alone applications, applets can’t runoutside the browser and are placed in a security sandbox.

2. The paint() method should be overridden to create visualelements for an AWT-based applet. The repaint() methodis invoked to update those visual elements.

Self-Check Answers206

Page 210: files.transtutors.com...INSTRUCTIONS TO STUDENTS 1 LESSON ASSIGNMENTS 5 LESSON 1: INTRODUCTION TO THE JAVA LANGUAGE 7 GRADED PROJECT—LESSON 1 29 LESSON 2: DATA TYPES AND PROGRAM

3. The drawOval() method is used to paint the outline of acircle, while the drawPolyline() is used to paint an openshape.

4. The event source is the visual component or input deviceon which an action occurs. The event listener is an objectthat’s notified by the source when a type of action occursby receiving an event object.

5. An anonymous inner class is one that’s defined “on-the-fly”without a name. The class definition is provided when anobject is instantiated, so that the class can’t be referencedoutside the object.

Self-Check 151. AWT relies heavily on native code for the visual elements,

while Swing uses pure Java components. Swing still usesAWT for events and graphics, however.

2. In MVC, a model represents the underlying object state,while the controller and view provide the input and out-put for that state, respectively. Swing modifies the MVCpattern by combining the controller and view into the UIdelegate.

3. The optimal layout manager would be GridBagLayout.Cells can span more than a single row or column in thislayout manager.

4. To instantiate a JFrame object on the event dispatcherthread, you should use the invokeLater() method. To display the JFrame object, you should invoke thesetVisible() method, specifying true.

5. JavaFX provides a greater range of visual customizationand multimedia support and doesn’t rely on AWT imple-mentations.

Self-Check Answers 207