8/11/2019 JAVA Certification ORacle Training Manuals
1/108
Fundamentals of the Java
Programming Language,
Java SE 6
Volume I Activity Guide
SL-110-SE6 E.1 Rev E.1
D61796GC11
Edition 1.1
June 2010
D67897
8/11/2019 JAVA Certification ORacle Training Manuals
2/108
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
Disclaimer
This document contains proprietary information, is provided under a license agreement containing restrictions on use and
disclosure, and is protected by copyright and other intellectual property laws. You may copy and print this document solely for
your own use in an Oracle training course. The document may not be modified or altered in any way. Except as expressly
permitted in your license agreement or allowed by law, you may not use, share, download, upload, copy, print, display,
perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express
authorization of Oracle.
The information contained in this document is subject to change without notice. If you find any problems in the document,
please report them in writing to: Oracle University, 500 Oracle Parkway, Redwood Shores, California 94065 USA. This
document is not warranted to be error-free.
Sun Microsystems, Inc. Disclaimer
This training manual may include references to materials, offerings, or products that were previously offered by Sun
Microsystems, Inc. Certain materials, offerings, services, or products may no longer be offered or provided. Oracle and its
affiliates cannot be held responsible for any such references should they appear in the text provided.
Restricted Rights Notice
If this documentation is delivered to the U.S. Government or anyone using the documentation on behalf of the U.S.
Government, the following notice is applicable:
U.S. GOVERNMENT RIGHTSThe U.S. Governments rights to use, modify, reproduce, release, perform, display, or disclose these training materials are
restricted by the terms of the applicable Oracle license agreement and/or the applicable U.S. Government contract.
Trademark Notice
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective
owners.
8/11/2019 JAVA Certification ORacle Training Manuals
3/108
This page intentionally left blank.
8/11/2019 JAVA Certification ORacle Training Manuals
4/108
This page intentionally left blank.
8/11/2019 JAVA Certification ORacle Training Manuals
5/108
vCopyright 2007 SunMicrosystems, Inc. AllRightsReserved.SunServices, RevisionE.1
Table of Contents
Explaining Java Technology........................................................1-1Objectives ........................................................................................... 1-1Lab Overview ..................................................................................... 1-2Completing Review Questions ........................................................ 1-3Exercise Summary.............................................................................. 1-5
Analyzing a Problem and Designing a Solution............................2-1Objectives ........................................................................................... 2-1Lab Overview ..................................................................................... 2-2Completing Review Questions ........................................................ 2-3Exercise 1: Analyzing a Problem Domain ...................................... 2-4
Preparation................................................................................. 2-4Task Performing an Analysis ............................................... 2-4
Exercise 2: Designing a Solution...................................................... 2-6Task Producing a Design ...................................................... 2-6
Exercise Summary.............................................................................. 2-8
Developing and Testing a Java Technology Program..................3-1Objectives ........................................................................................... 3-1Lab Overview ..................................................................................... 3-2Completing Review Questions ........................................................ 3-3Exercise 1: Modifying, Compiling, and Executing a Java
Program............................................................................................ 3-4Preparation................................................................................. 3-4.Task Compiling and Executing a Java Program............... 3-4
Exercise 2: Creating, Compiling, and Executing a Java Class ..... 3-6
Task Creating a Java Class and Testing It .......................... 3-6Exercise Summary.............................................................................. 3-8
Declaring, Initializing, and Using Variables ...................................4-1Objectives ........................................................................................... 4-1Lab Overview ..................................................................................... 4-2
8/11/2019 JAVA Certification ORacle Training Manuals
6/108
vi Fundamentals of theJavaProgrammingLanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices, RevisionE.1
Completing Review Questions ........................................................ 4-3Exercise 1: Using Primitive Type Variables in a Program ........... 4-5
Preparation................................................................................. 4-5Task Creating a Class With Variables ................................. 4-5
Exercise 2: Using Operators and Type Casting ............................. 4-6
Preparation................................................................................. 4-6Task 1 Calculating Age Using Operators ........................... 4-6Task 2 Using Casting to Prevent Data Loss ....................... 4-7Task 3 Creating a Temperature Program ...........................4-8
Exercise Summary.............................................................................. 4-9
Creating and Using Objects............................................................ 5-1Objectives ........................................................................................... 5-1Lab Overview ..................................................................................... 5-2Completing Review Questions ........................................................ 5-3Exercise 1: Creating and Manipulating Java Technology
Objects............................................................................................... 5-4
Preparation................................................................................. 5-4Task 1 Initializing Object Instances ..................................... 5-4Task 2 Manipulating Object References.............................. 5-5
Exercise 2: Using theStringClass ................................................. 5-6Preparation................................................................................. 5-6Task Creating and UsingStringObjects .......................... 5-6
Exercise 3: Using the Java SE API Specification ........................ 5-7Task Examining the Java SE API Specification.................. 5-7
Exercise Summary.............................................................................. 5-8
Using Operators and Decision Constructs ................................... 6-1
Objectives ........................................................................................... 6-1Lab Overview ..................................................................................... 6-2Completing Review Questions ........................................................ 6-3Exercise 1: Usingifandif/elseConstructs............................... 6-5
Preparation................................................................................. 6-5Task 1 Writing a Class That Usesif/elseStatements.... 6-5Task 2 Writing Another Class That Usesif/else
Statements ............................................................................... 6-6Exercise 2: Using theSwitch Statement......................................... 6-7
Preparation................................................................................. 6-7Task Writing a class That Uses theswitchStatement..... 6-7
Exercise Summary.............................................................................. 6-8
Using Loop Constructs ................................................................... 7-1Objectives ........................................................................................... 7-1Lab Overview ..................................................................................... 7-2Completing Review Questions ........................................................ 7-3Exercise 1: Using thewhileLoop.................................................... 7-4
Preparation................................................................................. 7-4
8/11/2019 JAVA Certification ORacle Training Manuals
7/108
viiCopyright 2007 SunMicrosystems, Inc. AllRightsReserved.SunServices, RevisionE.1
Task 1 Writing a Class That Uses awhileLoop ............... 7-4Task 2 Writing Another Class That Uses awhileLoop .. 7-5
Exercise 2: Using theforloop ......................................................... 7-7Preparation................................................................................. 7-7Task 1 Writing a Class That Uses theforLoop................ 7-7
Task 2 Modifying awhileLoop to aforLoop.................7-8Exercise 3: Using thedo/whileLoop............................................. 7-9Preparation................................................................................. 7-9Task Writing a Class Using thedo/whileLoop............... 7-9
Exercise Summary............................................................................ 7-10
Developing and Using Methods......................................................8-1Objectives ........................................................................................... 8-1Lab Overview ..................................................................................... 8-2Completing Review Questions ........................................................ 8-3Exercise 1: Using Arguments and Return Values ......................... 8-4
Preparation................................................................................. 8-4
Task Writing a Method That Uses Arguments and ReturnValues ...................................................................................... 8-4
Exercise 2: Using Overloaded Methods.......................................... 8-6Preparation................................................................................. 8-6Task Developing a Class With an Overloaded Method... 8-6
Exercise Summary.............................................................................. 8-8
Implementing Encapsulation and Constructors............................9-1Objectives ........................................................................................... 9-1Lab Overview ..................................................................................... 9-2Completing Review Questions ........................................................ 9-3
Exercise 1: Writing Encapsulated Classes ...................................... 9-4Preparation................................................................................. 9-4Task 1 Implementing Encapsulation in a Class................. 9-4Task 2 Accessing Encapsulated Attributes of a Class....... 9-5
Exercise 2: Using Constructors......................................................... 9-8Preparation................................................................................. 9-8Task 1 Creating and Using Constructors............................ 9-8Task 2 Creating Constructors to Initialize Objects............ 9-9
Exercise Summary............................................................................ 9-11
Creating and Using Arrays ............................................................10-1
Objectives ......................................................................................... 10-1Lab Overview ................................................................................... 10-2Completing Review Questions ...................................................... 10-3Exercise 1: Creating and Using One-Dimensional Arrays......... 10-4
Preparation............................................................................... 10-4Task 1 Creating a Class With a One-Dimensional Array of
Primitive Types .................................................................... 10-4
8/11/2019 JAVA Certification ORacle Training Manuals
8/108
viii Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices, RevisionE.1
Task 2 Creating a Class With a One-Dimensional Array ofObjects.................................................................................... 10-5
Exercise 2: Using Loops and Arrays.............................................. 10-7Preparation............................................................................... 10-7Task Using a Loop to Initialize an Array.......................... 10-7
Exercise 3: Parsing theargs[]Array ........................................... 10-8Task Creating a Game Using theargs [ ]Array............10-8Exercise 4: Creating and Using Two-Dimensional Arrays ........ 10-9
Preparation............................................................................... 10-9Task 1 Creating a Class With a Two-Dimensional
Array .................................................................................... 10-10Task 2 Traversing a Two-Dimensional Array................ 10-10Task 3 Testing a Class Having a Two-Dimensional
Array .................................................................................... 10-12Exercise Summary.......................................................................... 10-13
Implementing Inheritance ............................................................. 11-1
Objectives ......................................................................................... 11-1Lab Overview ................................................................................... 11-2Completing Review Questions ...................................................... 11-3Exercise 1: Designing Superclasses and Subclasses .................... 11-4
Task 1 Identifying Superclasses and Subclasses.............. 11-4Exercise 2: Creating and Using Superclasses and Subclasses....11-6
Preparation............................................................................... 11-6Task Creating Classes.......................................................... 11-6
Exercise Summary............................................................................ 11-7
8/11/2019 JAVA Certification ORacle Training Manuals
9/108
1-1Copyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Lab 1
ExplainingJavaTechnology
Objectives
Upon completion of this lab, you should be able to complete the reviewquestions.
8/11/2019 JAVA Certification ORacle Training Manuals
10/108
Lab Overview
1-2 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Lab Overview
This lab does not have any exercises. You complete the review questionsin this module.
8/11/2019 JAVA Certification ORacle Training Manuals
11/108
Completing Review Questions
Explaining Java Technology 1-3Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Completing Review Questions
In this section, you answer questions about the material covered inModule 1 of the Student Guide.
Complete the following questions:
1. The Java programming language is said to be platform-independent because:
a. Compiles on several platforms without modification
b. Does not allow pointers to be used to manipulate memory
c. Allows developers to create applications once that execute onseveral platforms
d. Is multithreaded
2. State whether the following statement is true or false:An application runs within an operating system.
3. The Java programming language is loosely based upon which of thefollowing languages:
a. C++
b. C
c. Machine Language
d. Fortran
4. The Java technology product group designed for developingapplications for consumer devices is _______. Choose one from thelist to fill in the blank:
a. Java SE SDK
b. Java ES SDK
c. Java EE SDK
d. Java ME SDK
8/11/2019 JAVA Certification ORacle Training Manuals
12/108
Completing Review Questions
1-4 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
5. Which of the following is part of the Java SE SDK
a. The Java Runtime Environment
b. The Java Virtual Machine Specification
c. A C++ Compiler
d. A linker
6. In which stage of the PLC, developers create updates to theirproducts.
a. Analysis
b. Maintenance
c. EOL
d. Design
7. The implementation stage of PLC is usually synonymous with:
a. Selling your program
b. Executing your program
c. Compiling your program
d. Maintaining your program
8/11/2019 JAVA Certification ORacle Training Manuals
13/108
Exercise Summary
Explaining Java Technology 1-5Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Exercise Summary
?
!
Discussion Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercises.
Experiences
Interpretations
Conclusions
Applications
8/11/2019 JAVA Certification ORacle Training Manuals
14/108
8/11/2019 JAVA Certification ORacle Training Manuals
15/108
2-1Copyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Lab 2
AnalyzingaProblemandDesigningaSolution
Objectives
Upon completion of this lab, you should be able to:
Complete Review Questions Analyze a problem using object-oriented analysis (OOA)
Design classes from which objects will be created
8/11/2019 JAVA Certification ORacle Training Manuals
16/108
Lab Overview
2-2 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Lab Overview
In this lab, you complete review questions and two exercises.
The exercises are:
List the objects, attributes, and operations in a sample problemdomain
Model an object using an UML-like notation
8/11/2019 JAVA Certification ORacle Training Manuals
17/108
Completing Review Questions
Analyzing a Problem and Designing a Solution 2-3Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Completing Review Questions
Complete the following questions:
1. Which of the following terms refers to the scope of a problem or a
system:a. The problem context
b. The problem domain
c. The system context
d. The problem area
2. Which of the following terms represents two different characteristicsof an object:
a. Methods and operations
b. The problem domain
c. Attributes and operations
d. Variables and data
3. Which of the following statements is a criteria to test the validity ofan object relative to a problem domain:
a. Relevance to the problem domain
b. Operation order
c. Attribute type
d. If a class has a super class
4. Which of the following statements are true:
a. A class is an instance of an object.
b. An object is a blueprint for a class.
c. An object and a class are exactly the same.
d. An object is an instance of a class.
e. An attribute cannot be a reference to another object.
8/11/2019 JAVA Certification ORacle Training Manuals
18/108
Exercise1: Analyzing a Problem Domain
2-4 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Exercise 1: Analyzing a Problem Domain
This exercise is based on a small case study. You will identify the objects,their attributes and operations involved in the system domain.
Preparation
Read the following case study, and then model the system by choosingobjects and their attributes and operations.
Case Study
A soccer league has many players. Each year there are three seasons andthe league puts together teams for each season. Each team is comprised of15 players. The goals scored by each player during each season aretracked. The games played between the teams, their final scores, and eachteams standings based on its won and lost games are tracked.
Task Performing an Analysis
Your task is to produce an object-oriented analysis for a Java technologyapplication that tracks soccer scores. The program should track:
The list of players on each team
The number of goals that each player scores
The games played during a season, including the teams that playeach other, and the final score
The application should be able to generate statistics for teams, players,and seasons.
To finalize the analysis, complete the following steps:
1. Create a list of the potential objects.
2. Apply the rules in this module to decide if all your objects are valid.
3. Create a list of attributes and operations for each of your objects.
8/11/2019 JAVA Certification ORacle Training Manuals
19/108
Exercise 1: Analyzing a Problem Domain
Analyzing a Problem and Designing a Solution 2-5Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Notes
8/11/2019 JAVA Certification ORacle Training Manuals
20/108
Exercise2: Designing a Solution
2-6 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Exercise 2: Designing a Solution
In this exercise you will use UML notation to represent a class.
Task Producing a Design
Your task is to produce a design for each of the classes in the earliersystem for tracking soccer scores. Remember to:
Use short-hand to name your classes, attribute variables, andmethods
Identify a valid range of values for each attribute (where a range isknown)
Use the parentheses to identify methods
8/11/2019 JAVA Certification ORacle Training Manuals
21/108
Exercise 2: Designing a Solution
Analyzing a Problem and Designing a Solution 2-7Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Notes
8/11/2019 JAVA Certification ORacle Training Manuals
22/108
8/11/2019 JAVA Certification ORacle Training Manuals
23/108
3-1Copyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Lab 3
Developing andTestingaJava TechnologyProgram
Objectives
Upon completion of this lab, you should be able to:
Complete review questions Write, modify, compile, and execute Java technology classes
8/11/2019 JAVA Certification ORacle Training Manuals
24/108
Lab Overview
3-2 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Lab Overview
In this lab, you complete the review questions and two exercises.
In the first exercise, you compile and execute an existing Java
technology class. In the second exercise, you write, compile, and execute your first
Java technology class.
8/11/2019 JAVA Certification ORacle Training Manuals
25/108
Completing Review Questions
Developing and Testing a Java Technology Program 3-3Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Completing Review Questions
Complete the following questions:
1. Which of the following options is part of the class declaration syntax:
a. Class arguments
b. Method identifier
c. Modifier
d. //
2. Identify the statement below that best describes the main method:
a. Themainmethod is the starting point for all Java technologyapplets.
b. Themainmethod usually has a return type ofint.
c. Themainmethod is required in all Java classes.
d. Themainmethod is a special method that the Java VirtualMachine recognizes as the starting point for every Javatechnology program run from a command line or a prompt.
3. State whether the following statements are true or false:
a. Thejavacommand executes a class or bytecode file.
b. Every open curly bracket in a Java technology program musthave a corresponding closing curly brace.
c. */ is a valid starting delimiter for a comment.
d. Thejavaccommand reads class and interface definitions,written in the Java programming language, and compiles theminto bytecode class files.
8/11/2019 JAVA Certification ORacle Training Manuals
26/108
Exercise1: Modifying, Compiling, andExecuting a Java Program
3-4 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Exercise 1: Modifying, Compiling, and Executing a JavaProgram
A Java technology program is already created for you. You need to open
it, examine the lines of code, modify it, compile it, and then test it byexecuting the program.
Preparation
Ensure thatQuotationTest.javaandQuotation.javafiles exist inSL110/exercises/03_getstarted/exercise1directory
.Task Compiling and Executing a Java Program
In this task, you will modify a Java Program, save, compile and test it.
Complete the following steps:
1. Open a text editor.
2. Open the Quotation.java file located atSL110/exercises/03_getstarted/exercise1directory.
3. Examine the Quotation class and identify its member variable.
4. In thedisplaymethod, write code to display the value of themember variable.
5. Save and close theQuotation.javafile.
6. Open theQuotationTest.javafile located atSL110/exercises/03_getstarted/exercise1directory andexamine itsmainmethod. The main method creates an instance ofthe Quotation class and executes thedisplaymethod ofQuotation.Close the file.
7. Open the terminal window and navigate to the directorySL110/exercises/03_getstarted/exercise1
.8. CompileQuotation.javafile usingjavac. Foe example:
javac Quotation.java
8/11/2019 JAVA Certification ORacle Training Manuals
27/108
Exercise 1: Modifying, Compiling, andExecuting a Java Program
Developing and Testing a Java Technology Program 3-5Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
9. If required, modify theQuotation.javafile to correct anycompilation errors generated by the previous step. Save the file andrecompile it.
10. CompileQuotationTest.javafile usingjavac. For example:javac QuotationTest.java
11. Examine theSL110/exercises/03_getstarted/exercise1directory to verify if the compilation steps has created the followingclass files:
Quotation.class
QuotationTest.class.
12. ExecuteQuotationTest.class file using java and verify the output.For example: java QuotationTest
13. OpenQuotation.java file, modify the default value of the member
variable inQuotation.javafile to your own favourite quotation,and save the file.
14. CompileQuotation.javafile.
15. ExecuteQuotationTest.classfile and verify the changed output.
8/11/2019 JAVA Certification ORacle Training Manuals
28/108
Exercise2: Creating, Compiling, and Executing a Java Class
3-6 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Exercise 2: Creating, Compiling, and Executing a JavaClass
In this exercise you will create a Java class, and compile it. You will also
create another Java class to test the previous class.
Task Creating a Java Class and Testing It
In this task, you will create two classes and compile them. You willexecute one class file.
Complete the following steps:
1. Go to theSL110/exercises/03_getstarted/exercise2directory.
2. Open an editor, and enter in the Java technology syntax for theShirtclass shown inCode 3-1 on page 3-8of this module of theStudent Guide.
3. Save and close the file.
4. Open an editor, and enter theShirtTest class shown inCode 3-2 onpage 3-14this module of the Student Guide.
5. Save and close the file.
6. Open a terminal window and navigate to the directory for thismodule.
7. Type the command to compile theShirtclass into an executablebytecode file. For example:javac Shirt.java
8. Verify that the fileShirt.classis created in theSL110/exercises/03_getstarted/exercise2directory.
9. Type the command to compile theShirtTest class into anexecutable bytecode file.javac ShirtTest.java
10. Verify that the fileShirtTest.class
is created in theSL110/exercises/03_getstarted/exercise2directory.
11. Type the command to run theShirtTest.classfile and examinethe output of the program.java ShirtTest
12. Open theShirt.javafile in the editor again.
13. Modify the values of theShirtID andpricemember variables.
http://../SL110_IG/mod03_getstartedjava.pdfhttp://../SL110_IG/mod03_getstartedjava.pdfhttp://../SL110_IG/mod03_getstartedjava.pdfhttp://../SL110_IG/mod03_getstartedjava.pdfhttp://../SL110_IG/mod03_getstartedjava.pdfhttp://../SL110_IG/mod03_getstartedjava.pdf8/11/2019 JAVA Certification ORacle Training Manuals
29/108
Exercise 2: Creating, Compiling, andExecuting a Java Class
Developing and Testing a Java Technology Program 3-7Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
14. Save and close theShirt.javafile.
15. RecompileShirt.javafile at the terminal window.javac Shirt.java
16. Run theShirtTest.classfile at the terminal window.java Shirt
17. Examine the output of the program and verify if the output is differsfrom the output as seen in Step 9.
8/11/2019 JAVA Certification ORacle Training Manuals
30/108
Exercise Summary
3-8 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Exercise Summary
?
!
Discussion Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercises.
Experiences
Interpretations
Conclusions
Applications
8/11/2019 JAVA Certification ORacle Training Manuals
31/108
4-1Copyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Lab 4
Declaring, Initializing,andUsingVariables
Objectives
Upon completion of this lab, you should be able to:
Complete review questions
Perform variable declarations in a class
Perform type casting and use operators in a Java technologyprogram
8/11/2019 JAVA Certification ORacle Training Manuals
32/108
Lab Overview
4-2 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Lab Overview
In this lab, you complete review questions and two exercises.
In the first exercise, you create a Java class containing variable
declarations. In the second exercise, you write a Java technology program in
which you use operators and perform type casting.
8/11/2019 JAVA Certification ORacle Training Manuals
33/108
Completing Review Questions
Declaring, Initializing, and Using Variables 4-3Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Completing Review Questions
Complete the following questions:
1. State whether the following statements are true or false:
a. There are eight primitive types built into the Java programminglanguage.
b. In the Java programming language, the variable namesintgradeandintGradeare the same.
c. byte, short, int and long are the four integral primitive types inthe Java programming language.
d. A boolean type variable holds true, false and nil.
2. Which answer best describes the following variable declaration:final double PI = 3.14159;
a. This is the value assignment for an integral primitive type.
b. The name of the variable is a Java programming languagekeyword.
c. The variable is a constant.
d. The variable is incorrectly named, according to the namingguidelines.
3. Which of the following operations correctly illustrate operatorprecedence in the following calculation
X = 1 + 2 * 5 -8 +6 / 7 * 4;a. (1 + 2) * (5 - 8) + (6 / (7 * 4))
b. 1 + (2 * 5) - 8 + ((6 / 7) * 4)
c. (1 + 2) * (5 - ((8 + 6) / (7 * 4)))
d. 1 + (2 * (5 - 8)) + ((6 / 7) * 4)
8/11/2019 JAVA Certification ORacle Training Manuals
34/108
Completing Review Questions
4-4 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
4. Examine the following code, and select the correct output afterexecution:int a = 5;
int b = ++a;System.out.println("a = "+ a + "and b = "+ b);
a. a = 5andb = 5
b. a = 5andb = 6
c. a = 6andb = 6
d. a = 6andb = 5
8/11/2019 JAVA Certification ORacle Training Manuals
35/108
Exercise 1: Using Primitive Type Variables in a Program
Declaring, Initializing, and Using Variables 4-5Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Exercise 1: Using Primitive Type Variables in a Program
In this exercise, you create a class containing variable declarations.
Preparation
Ensure thatCustomerTest.javafiles exists in theSL110/exercises/04_variables/exercise1directory.
Task Creating a Class With Variables
In this task, you compile and execute aCustomerclass with severalvariables.
Complete the following steps to create yourCustomerclass:.
1. Go to theSL110/exercises/04_variables/exercise1directory.
2. Open a text editor, and create a file in this directory calledCustomer.java.
3. In theCustomer.java file, write a class calledCustomer that createsand assigns default values to the variables for the followinginformation (use constants if appropriate):
A customer ID The customer status of N for new or O for old
Total purchases for the year
4. Create a method within the class calleddisplayCustomerInfothatuses theSystem.out.printlnmethod to print each value to thescreen with a corresponding label (such as"Purchases are: ").
5. Compile and run the program using the providedCustomerTestclass file.
Note All of the examples and exercises in this course require a test class.In most situations, the test class is provided. However, in some situations,you will create the class.
6. Check the output to be sure that it contains the values you assigned
8/11/2019 JAVA Certification ORacle Training Manuals
36/108
Exercise2: Using Operators and Type Casting
4-6 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Exercise 2: Using Operators and Type Casting
The objective of this exercise is to give you practice using operators andtype casting.
This exercise has three tasks. In each of the tasks you create one Javatechnology program, compile it, and test it.
This exercise consists of the following tasks:
Task 1 Calculating Age Using Operators
Task 2 Using Casting to Prevent Data Loss
Task 3 Creating a Temperature Program
Preparation
Ensure that thePersonTest.java, OrderTest.java, andTemperatureTest.javafiles exists in theSL110/exercises/04_variables/exercise2directory.
Task 1 Calculating Age Using Operators
In this task, you use operators to calculate age in minutes and
milliseconds.
Follow these steps to create aPersonclass that calculates various ages:
1. Open a terminal window and go to theSL110/exercises/04_variables/exercisedirectory.
2. Open a text editor and create aPersonclass in a file.
3. Add the following code to yourPersonclass:
a. Create member variables to store age in years, days, minutes,seconds, and milliseconds.
b. Set an initial value of 1 to the variable which stores the age inyears.
8/11/2019 JAVA Certification ORacle Training Manuals
37/108
Exercise 2: Using Operators and Type Casting
Declaring, Initializing, and Using Variables 4-7Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Note Ensure that you assign the correct data types for each variable andprovide meaningful names to all the variables.
c. Create acalculateAgemethod in thePersonclass.
d. In the method, calculate the age in days, minutes, seconds, andmilliseconds and assign the new values to the correspondingmember variables.
e. In the method, print out all the ages in various units, each in aseparate line with an appropriate message. For example: Youare 31536000 seconds old.
f. Save and close thePerson.javafile.
g. Compile the Person.javaand PersonTest.javafiles. Removethe compilation errors if any and recompile.
h. Test the program using thePersonTestclass.i. Perform tests, by setting the value of age as 1, 24, and 80 in the
Personclass.
Note For one year, the results should be: You are 365 days old. You are31536000 seconds old. You are 525600 minutes old. You are 31536000000milliseconds old. For 24 years, the results should be: You are 8760 daysold. You are 756864000 seconds old. You are 12614400 minutes old. Youare 756864000000 milliseconds old.
Task 2 Using Casting to Prevent Data Loss
In this task, you use casting to ensure that data loss does not occur in yourprograms.
Perform the following steps:
1. Create a class called Order that contains three member variables asfollows:
a. long orderValue=0
b. int itemQuantity=10000000
c. int itemPrice=555500
2. Create acalculateTotalmethod that will calculate the total ordervalue and print it. Ensure that you type cast the result of themultiplication before storing it in order value.
8/11/2019 JAVA Certification ORacle Training Manuals
38/108
Exercise2: Using Operators and Type Casting
4-8 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
3. Save and close theOrder.javafile.
4. CompileOrder.javaandOrderTest.javafile.
5. Test the program by runningOrderTest.classfile. Verify theresult oforderValueby performing the calculation in a calculator.
6. OpenOrder.javaand remove and type casting done in thecalculateTotalmethod. Save and close the file.
7. RecompileOrder.javafile and run theOrderTestclass again.
8. Compare the current result oforderValuewith the one obtained inStep 5.
9. Test the program by replacing the value of the integer membervariables ofOrderclass by:
a. One-digitinttypes
b. Five-digitinttypes
c. Nine-digitinttypesEnsure that you get the same result with the program as you dowhen doing each calculation using a calculator.
Task 3 Creating a Temperature Program
In this task, you write a program to convert temperature from fahrenheitto Celsius.
Write code to complete the following steps:
1. Create aTemperature class with a member variable which stores thetemperature in fahrenheit. Declare the variable with an appropriatedata type, such as int, float, or double.
2. Create acalculateCelsius method.
3. In thecalculateCelsiusmethod, use the following information toconvert the temperature value from fahrenheit to Celsius.
To convert from Fahrenheit to Celsius, subtract 32, multiply by
5, and divide by 9.4. Test the program using theTemperatureTestclass.
5. Ensure that you get the same result with the program as you dowhen doing the calculation using a calculator.
6. Test the program using several values of temperature.
8/11/2019 JAVA Certification ORacle Training Manuals
39/108
Exercise Summary
Declaring, Initializing, and Using Variables 4-9Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Exercise Summary
?
!
Discussion Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercises.
Experiences
Interpretations
Conclusions
Applications
8/11/2019 JAVA Certification ORacle Training Manuals
40/108
8/11/2019 JAVA Certification ORacle Training Manuals
41/108
5-1Copyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Lab 5
CreatingandUsingObjects
Objectives
Upon completion of this lab, you should be able to:
Complete review questions
Create and manipulate objects
Use theStringclass
Use the Java SE API
8/11/2019 JAVA Certification ORacle Training Manuals
42/108
Lab Overview
5-2 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Lab Overview
In this lab, you complete review questions and three exercises.
In the first exercise, you create and manipulate Java technology
objects. In the second exercise, you create and use String objects.
in the third exercise, you get familiar with the Java API specification.
8/11/2019 JAVA Certification ORacle Training Manuals
43/108
Completing Review Questions
Creating and Using Objects 5-3Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Completing Review Questions
Complete the following questions
1. Which of the following lines of code instantiates aBoatobject and
assigns it to asailBoatobject reference?a. Boat sailBoat = new Boat();
b. Boat sailBoat;
c. Boat = new Boat()
d. Boat sailBoat = Boat();
2. Read the following code and identify the result from the optionsgiven below:
Clothing myHat = new Hat();
Clothing mySock = new Sock();myHat = mySock;
a. ThemyHatvariable now contains aSockobject.
b. ThemyHatvariable contains the same address as themySockvariable.
c. TheSockandHatvariables are the same.
d. ThemyHatvariable remains unchanged.
3. Which of the following statements are true?
a. The dot (.) operator creates a new object instance.
b. TheStringclass provides you with the ability to store asequence of characters.
c. The Java API specification contains documentation for all of theclasses in a Java technology product.
d. Stringtypes are unique because they are the only class thatallows you to build objects without using thenewkeyword.
8/11/2019 JAVA Certification ORacle Training Manuals
44/108
Exercise1: Creating andManipulating Java Technology Objects
5-4 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Exercise 1: Creating and Manipulating Java TechnologyObjects
In this exercise, you create instances of a class and manipulate these
instances in several ways.
This exercise consists of the following tasks:
Task 1 Initializing Object Instances
Task 2 Manipulating Object References
Preparation
Ensure thatCustomer.javafiles exists in theSL110/exercises/05_objects/exercise1directory.
Task 1 Initializing Object Instances
You have been provided with theCustomer class. In this task, you create,compile, and execute aCustomerTestclass. In theCustomerTestclass,you create objects of theCustomerclass and set values to its membervariables.
Complete the following steps:
1. Go to theSL110/exercises/05_objects/exercise1 directory andopen theCustomer.javafile.
2. Examine theCustomerclass, its member variables and its method.
3. Create new classCustomerTest and save it asCustomerTest.java.
4. Create the main method in theCustomerTestclass.
5. In the main method, perform the following:
a. Declare two instances ofCustomerclass.
b. Initialize the two instances of theCustomerclass using thenewoperator.
8/11/2019 JAVA Certification ORacle Training Manuals
45/108
Exercise 1: Creating and Manipulating Java Technology Objects
Creating and Using Objects 5-5Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
c. Assign values to the member variables of theCustomerinstance. Repeat the same for the secondCustomerobject butwith different values. For example:cObject1.customerID=1;
d. Invoke thedisplayCustomerInfomethod for each of the
Customerobjects
6. Save, compile and run the program.
7. Check the output to be sure that eachCustomerobject displays thedistinct values you assigned.
Task 2 Manipulating Object References
In this task, you assign the value of one object reference to another object
reference. Complete the following steps:1. OpenCustomerTest.java file, that you created and executed in the
previous task.
2. In themainmethod, go to the line where you invoke thedisplayCustomerInfomethod for both theCustomerinstances.
3. Assign one object reference to another object reference, before youcall thedisplayCustomerInfomethod for both the instances. Forexample:cObject2=cObject1. Assuming thatcObject1andcObject2are the two instances of theCustomerclass.
4. Save, compile and run the program.5. Check the output of thedisplayCustomerInfo methods for both
the objects.
8/11/2019 JAVA Certification ORacle Training Manuals
46/108
Exercise 2: Using the StringClass
5-6 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Exercise 2: Using the StringClass
The objective of this exercise is to create and initializeString objects andto print their contents.
Preparation
Ensure that thePersonTwoTest.javafile exists in theSL110/exercises/05_objects/exercise2directory. This is yourworking directory.
Task Creating and UsingStringObjects
In this task, you write a class calledPersonTwo that creates and initializestwoStringvariables and displays their values. Follow these steps tocreate your class:
1. Go to the working directory.
2. Create a class calledPersonTwothat creates and initializes twovariables:
The first variable stores a quotation.
The second variable stores the name of the person who said thequotation.
3. Use a method calleddisplayQuote to display the quotation and thename of the person to the screen.
4. Compile your class.
5. Execute your class using the providedPersonTwoTestclass.
8/11/2019 JAVA Certification ORacle Training Manuals
47/108
Exercise 3: Using the Java SE API Specification
Creating and Using Objects 5-7Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Exercise 3: Using the Java SE API Specification
The objective of this exercise is to allow you to become familiar with theJava SE API specification.
Task Examining the Java SE API Specification
Note The intent of this exercise is to become familiar with thedocumentation and how you look up classes and methods. You are notexpected to understand everything you look at. As you progress throughthis course, the Java API documentation should make more sense.
To view the Java API 6.0 specification:
1. Go to the following URL:
http://java.sun.com/javase/6/docs/
2. From the site listed, find the API specification.
3. Using the API specification, complete the following:
a. Find theMathclass under thejava.langpackage. How manymethods are there in this class?
b. What class does every class refer to at the top of the page?Hint: What class is the superclass to all classes?
4. Find theStringclass. Identify the methods ofStringclass, whichwill enable you to compare two strings.
8/11/2019 JAVA Certification ORacle Training Manuals
48/108
Exercise Summary
5-8 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Exercise Summary
?
!
Discussion Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercises.
Experiences
Interpretations
Conclusions
Applications
8/11/2019 JAVA Certification ORacle Training Manuals
49/108
6-1Copyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Lab 6
UsingOperatorsand DecisionConstructs
Objectives
Upon completion of this lab, you should be able to:
Complete review questions
Useifandif/elseconstructs in a Java program
Useswitchconstruct in a Java program
8/11/2019 JAVA Certification ORacle Training Manuals
50/108
Lab Overview
6-2 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Lab Overview
In this lab, you complete the review questions and two exercises.
In the first exercise, you create if and if/else constructs.
In the second exercise, you createswitchconstructs
8/11/2019 JAVA Certification ORacle Training Manuals
51/108
Completing Review Questions
Using Operators and Decision Constructs 6-3Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Completing Review Questions
Complete the following questions:
1. What is the purpose of the else block in an if-else statement?
a. To contain the remainder of the code for a method.
b. To contain code that is executed when the expression in anifstatement isfalse.
c. To test whether an expression isfalse.
2. Which of the following sentences is suitable for testing a value in aswitchconstruct?
a. Theswitchconstruct tests whether values are greater than orless than a single value.
b. Theswitchconstruct tests against a single variable.c. Theswitchconstruct tests the value of a float, double, or
boolean data type.
3. What relational operators and conditional operators are mentionedin the following paragraph?If the time is 8:00 a.m., then it is time for work and time for coffee. Ifthe time is greater than 12:00 p.m., it is time for lunch or time for tea.If the time is 5:00 p.m. or later, it is time to go home.
a. ==,>,=>
b. ==,&&,
d. ==,||,>
8/11/2019 JAVA Certification ORacle Training Manuals
52/108
Completing Review Questions
6-4 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
4. Read the following code snippet and identify the correct options:1 String clothing1;2 String clothing2;3 clothing1 = "socks";
4 clothing2 = "pants";
5 if (clothing1 == clothing2)a. Line 5 tests if the String literals pointed to by theclothing1
andclothing2references are equal
b. Line 5 tests the String objects' references in memory, not theircontents.
c. By replacing Line 5 with theif (clothing1.equals(clothing2)) statement, the stringliterals referenced byclothing1andclothing2are equal.
d. Line 5 always returnstrue
8/11/2019 JAVA Certification ORacle Training Manuals
53/108
Exercise 1: Usingifand if/elseConstructs
Using Operators and Decision Constructs 6-5Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Exercise 1: Using ifand if/elseConstructs
The objective of this exercise is to create classes that useifandif/elseconstructs.
Preparation
Ensure thatDateTwoTest.javaandClockTest.javafiles exists in theSL110/exercises/06_decision/exercise1directory. This is yourworking directory.
This exercise has two tasks. In each task you create a class and use theif/else statements where ever applicable. The tasks are:
Task 1 Writing a Class That Usesif/elseStatements Task 2 Writing Another Class That Usesif/elseStatements
Task 1 Writing a Class That Usesif/elseStatements
In this task, you write a class calledDateTwothat usesif/elsestatements to display the day of the week based on the value of a variable.Follow these steps to write your class:
1. Go to your working directory. Create a class calledDateTwowithone member variable calleddayNumber. Assign a value todayNumber between 1 and 7 where:
The number 1 represents Monday (beginning of the week).
The number 7 represents Sunday (end of the week).
2. In theDateTwo class, create adisplayDaymethod that usesif/elseconstructs to inspect the value of the dayNumber and displays thecorresponding day of the week. ThedisplayDaymethod shouldalso display an error message if an invalid number is found.
3. Save, compile, and execute your class using the providedDateTwoTestclass file.
4. Repeat Step 3 several times by assigning different values to theDateTwomember variabledayNumber in theDateTwoTest.java file.
8/11/2019 JAVA Certification ORacle Training Manuals
54/108
Exercise1: Using ifand if/elseConstructs
6-6 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Task 2 Writing Another Class That Usesif/elseStatements
In this task, you write a class calledClockthat usesif/elsestatements
to display the part of day depending on the time of day. Use the followingtable as a guideline.
Follow these steps to write your class:
1. Go to your working directory.
2. Create a class calledClockwith a variable calledcurrentTimethatcontains the hour of day.
3. In theClockclass, create adisplayPartOfDaymethod that usesif/else constructs to display the part of the day associated with thevalue of thecurrentTimevariable. For example, if the value of thecurrentTime variable is equal to 1504, your program would display
Afternoon.
4. Compile and execute your program using theClockTestclass file.
5. Repeat Step 4 several times by assigning different values to the Clockmember variablecurrentTimein theClockTest.javafile.
Note A leading zero indicates an octal value. Therefore, the programdoes not compile if you setcurrentTimeto 0800. You need to specifycurrentTime as 800 for 8:00 AM to successfully compile the program. Notests have been done for values that lie outside the range of 100 and 2400.
Time of Day Part of Day
8:01 to 12:00 Morning
12:01 to 17:00 Afternoon
17:01 to 24:00 Evening
0:01 to 8:00 Early Morning
8/11/2019 JAVA Certification ORacle Training Manuals
55/108
Exercise 2: Using the SwitchStatement
Using Operators and Decision Constructs 6-7Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Exercise 2: Using the SwitchStatement
The objective of this exercise is to practice using theswitchconstruct indecision-making programs. In this exercise, you create a program thatdisplays the name of the month based on the month number.
Preparation
Ensure that theMonthTest.java file exists in theSL110/exercises/06_decision/exercise2directory. The is yourworking directory.
Task Writing a class That Uses theswitchStatement
In this task you create a class calledMonththat uses switch statements todisplay the name of the month based on the numeric value of a variable.
Complete the following steps
1. In your working directory, create a class calledMonthand save thefile asMonth.java.
2. In theMonthclass, create a variable calledmonthNumber. Assign avalue to the variable that is between 1 and 12, where the number 1
represents the month of January and the number 12 represents themonth of December.
3. In theMonthclass, create adisplayMonthmethod that uses aswitchconstruct to inspect the value of themonthNumbervariableand displays the corresponding name of the month. ThedisplayMonthmethod should also display an error message if aninvalid number is used.
4. Save and compile the file.
5. Execute the program by running the MonthTest class file.
6. Repeat Step 5 several times assigning different values to the Monthmember variablemonthNumberin theMonthTest.javafile.
8/11/2019 JAVA Certification ORacle Training Manuals
56/108
Exercise Summary
6-8 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Exercise Summary
?
!
Discussion Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercises.
Experiences
Interpretations
Conclusions
Applications
8/11/2019 JAVA Certification ORacle Training Manuals
57/108
7-1Copyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Lab 7
UsingLoopConstructs
Objectives
Upon completion of this lab, you should be able to:
Complete review questions
Usewhileanddo/whileloops in a Java program
Useforloops in a Java program
8/11/2019 JAVA Certification ORacle Training Manuals
58/108
Lab Overview
7-2 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Lab Overview
In this lab, you complete the review questions and three exercises.
In the first exercise, you createwhileloop constructs.
In the second exercise, you createforloop constructs.
In the third exercise, you createdo/whileloop constructs.
8/11/2019 JAVA Certification ORacle Training Manuals
59/108
Completing Review Questions
Using Loop Constructs 7-3Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Completing Review Questions
Complete the following questions:
1. Fill in the blank of the following sentence with one of the options
given below. ________________ enables you to check and recheck adecision to execute and re-execute a block of code.
a. Classes
b. Objects
c. Loops
d. Methods
2. Which type of loop allows you to declare a variable as part of itsconstruct:
a. Thedo/whileloopb. Thewhileloop
c. The nestedwhileloop
d. Theforloop
3. Which of the following types of loops is a one/many iterative loop:
a. Thewhileloop
b. The nestedwhileloop
c. Thedo/whileloop
d. Theforloop
4. State whether the following statement is true or false:You should prefer to use the for loop to step through statements apre-defined number of times.
8/11/2019 JAVA Certification ORacle Training Manuals
60/108
Exercise 1: Using the whileLoop
7-4 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Exercise 1: Using the whileLoop
The objective of this exercise is to create classes that usewhileloopconstructs.
Preparation
Ensure thatCounterTest.java file andSequenceTest.java file exists intheSL110/exercises/07_loops/exercise1directory. This is yourworking directory.
This exercise has two tasks. In each task you create a class and use thewhile loops wherever applicable. The tasks are:
Task 1 Writing a Class That Uses awhileLoop Task 2 Writing Another Class That Uses awhileLoop
Task 1 Writing a Class That Uses awhile Loop
In this task, you write a class calledCounterand use awhileloop todisplay the value of a count variable that is incremental in steps of one.Follow these steps to create your class:
1. Open the terminal window and go to your working directory. Using
an editor, create a class calledCounterwith three member variablescalledMAX_COUNT,step, andcount. Assign the value 50 toMAX_COUNTand the value 1 to count andstep.Ensure thatMAX_COUNTis declared as afinalvariable.
2. Create apublic displayCountmethod in the class that does notaccept any argument and returnsvoid. For example:public void displayCount(){
3. Create awhile loop in the method with the following characteristics:
a. Boolean expression: Repeat if the value ofcountis less than or
equal to the value ofMAX_COUNTb. Code block:
Print the value of the count variable
Increment the value of count by step value. For example:count=count + step;
4. Save and compile theCounter.javafile.
8/11/2019 JAVA Certification ORacle Training Manuals
61/108
Exercise 1: Using the whileLoop
Using Loop Constructs 7-5Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
5. Compile theCounterTest.javafile that is provided in yourworking directory. Execute theCounterTestclass file.
6. Verify if your class prints all the numbers between 1 and 50.
7. You can modify the value of thestepvariable to modify the output
of theCounter
class. Perform the following steps:a. Open theCounterTest.javafile for modification.
b. Before thedisplayCountmethod is invoked, assign a value of2 to thestepmember variable of the Counter class. Use theobject of theCounterclass to access thestepmember variable.
c. Complete steps 3 - 4 and verify the output. The output shouldbe: 1 3 5 7.............49
8. Repeat Step 6, for thestepvalue of 3.stepis the member variableofCounterclass.
Task 2 Writing Another Class That Uses awhileLoop
In this task, you write a class namedSequence1that displays a sequencestarting with the numbers 0 and 1. Successive numbers in the sequenceare the sum of the previous two numbers. For example: 0 1 1 2 3 5 8 1321...... This sequence is also called the Fibonacci series.
Follow these steps to write your class:1. Go to your working directory and open an editor.
2. Create a class calledSequence1with three variables calledfirstNumber, secondNumber, andnextNumber. Assign the values of 0and 1 to the firstNumberand secondNumbervariables, respectively.
3. Create apublicmethod calleddisplaySequencewith no returntype and no argument, that will perform the following actions:
a. Print the value of firstNumber, secondNumberto start with thesequence.
b. Calculate the sum offirstNumberandsecondNumberandassign the sum to thenextNumbervariable.
8/11/2019 JAVA Certification ORacle Training Manuals
62/108
Exercise 1: Using the whileLoop
7-6 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
4. Create awhile loop in the method with the following characteristics:
Boolean expression: Repeat if the value ofnextNumber is less thanor equal to 100
Code block:
Print the value of thenextNumbervariable. Assign the value ofsecondNumber to firstNumberand the
value ofnextNumbertosecondNumbervariables.
Recalculate the value ofnextNumberto be the sum offirstNumber andsecondNumber.
5. Save and compile theSequence1.javafile.
6. Compile theSequenceTest.java file provided in your workingdirectory and execute theSequenceTestclass file.
7. Verify the output. The result should look like: 0 1 1 2 3 5 8 13 21 34 55
89
8/11/2019 JAVA Certification ORacle Training Manuals
63/108
Exercise 2: Using the for loop
Using Loop Constructs 7-7Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Exercise 2: Using the for loop
The objective of this exercise is to use theforloop in a class.
Preparation
Ensure that theCounterTwoTest.java file and theSequence2Test.javafile exist in theSL110/exercises/07_loops/exercise2directory. This is your workingdirectory.
This exercise has two tasks. In each task you create a class and use the forloop where ever applicable.
Task 1 Writing a Class That Uses theforLoop Task 2 Modifying awhileLoop to aforLoop
Task 1 Writing a Class That Uses thefor Loop
In this task, you write a class that counts from 1 to a constant number anddisplays all the numbers divisible by 12 between them.
Complete the following steps to write your class:
1. Go to the working directory and open an editor.
2. Write a class calledCounterTwo containing a member variable calledMAX_COUNT. Assign the values of 100 to the variable.
3. Create apublicmethod calleddisplayCountwith no argumentand no return type, which:
Counts from 1 to the value of theMAX_COUNTconstant, using aforloop. Increment the value of the loop variable by 1.
Displays the value of the loop variable if it is divisible by 12.
4. Save your class asCounterTwo.javafile and compile the class.5. CompileCounterTwoTest.java file and execute it to verify the
output. The result should look like: 12 24 36 48 60 72 84 96
8/11/2019 JAVA Certification ORacle Training Manuals
64/108
Exercise 2: Using the for loop
7-8 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Task 2 Modifying awhile Loop to afor Loop
In this task, you modify the class that you created in Exercise 1, Task 2and replace thewhileloop with aforloop.
Complete the following steps:
1. Create a classSequence2similar toSequence1as in Exercise 1,Task 2 and save it asSequence2.javain your working directory.
2. Create an additional final member variable,SEQUENCE_COUNT, andassign 10 to it. Ensure that the other member variables remainunchanged.
3. In thedisplaySequencemethod, modify thewhileloop to aforloop such that only the first 10 values of the fibonacci series aredisplayed. The result should look like: 0 1 1 2 3 5 8 13 21 34.
4. Save and compile theSequence2.javafile.
5. Compile the providedSequence2Test.java, execute it, and verifythe output.
8/11/2019 JAVA Certification ORacle Training Manuals
65/108
Exercise 3: Using the do/whileLoop
Using Loop Constructs 7-9Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Exercise 3: Using the do/whileLoop
The objective of this exercise is to write a class that uses ado/whileloop.
Preparation
Ensure that theDiceTest.java file exists in theSL110/exercises/07_loops/exercise3directory. This directory isyour working directory.
Task Writing a Class Using thedo/while Loop
In this task, you write a class that simulates a simple game of throwing
two dice. Follow these steps to write your class:
1. Go to the working directory.
2. Write a class calledDicecontaining two member variablesdiceNumber1anddiceNumber2to hold the dice numbers.
3. Create apublicmethod calledthrowDicewith no argument and noreturn type and add ado/whileloop with the followingcharacteristics:
Code block: Generate a random number between 1 and 6 andassign it todiceNumber1variable. Repeat the same fordiceNumber2variable. For example:diceNumber1=(int)(Math.random()*6) +1;Print the value ofdiceNumber1 anddiceNumber2 variables.
Boolean expression: Repeat ifdiceNumber1is equal todiceNumber2.
4. Save and compile theDiceclass.
5. Use theDiceTest.javafile to test the result of theDiceclass.
6. Verify that the values ofdiceNumber1anddiceNumber2aredisplayed.
8/11/2019 JAVA Certification ORacle Training Manuals
66/108
Exercise Summary
7-10 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Exercise Summary
?
!
Discussion Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercises.
Experiences
Interpretations
Conclusions
Applications
8/11/2019 JAVA Certification ORacle Training Manuals
67/108
8-1Copyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Lab 8
Developing and Using Methods
Objectives
Upon completion of this lab, you should be able to:
Complete review questions
Create methods and use the methods in a Java program
Use method overloading in a Java program
8/11/2019 JAVA Certification ORacle Training Manuals
68/108
Lab Overview
8-2 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Lab Overview
In this lab, you complete the review questions and two exercises.
In the first exercise, you create methods and invoke them.
In the second exercise, you create overloaded methods and use them.
8/11/2019 JAVA Certification ORacle Training Manuals
69/108
Completing Review Questions
Developing and Using Methods 8-3Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Completing Review Questions
Complete the following questions:
1. State which of the following statements are true:
a. A class can only contain one single method declaration.
b. The most basic form of a method is one that has a return typebut no arguments.
c. All calling methods can be worker methods and all workermethods can be calling methods.
d. Overloaded methods have the same number of arguments.
2. The main method accepts which of the following argument types:
a. AStringobject
b. Aninttype
c. An array of references toStringobjects
d. An array ofStringobjects
3. Which method corresponds to the following method call?
myPerson.printValues (100, 147.7F, "lavender");
a. public void printValues (int pantSize, floatageInYears)
b. public void printValues (pantSize, float
ageInYears, favoriteColor)c. public void printValues (int pantSize, float
ageInYears, String favoriteColor)
d. public void printValues (float ageInYears, StringfavoriteColor, int pantSize)
8/11/2019 JAVA Certification ORacle Training Manuals
70/108
Exercise1: Using Arguments and Return Values
8-4 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Exercise 1: Using Arguments and Return Values
The objective of this exercise is to write a class with a method that invokesa worker method in another class.
In this exercise, you create a small application that instantiates three shirtobjects and applies a different price to each.
Then the application instantiates a purchase receipt object that reports thetotal price as each shirt is added to the order.
Preparation
Ensure that theOrder.javafile andthe Shirt.javafile exists in the
SL110/exercises/08_methods/exercise1directory. This is yourworking directory.
Task Writing a Method That Uses Arguments andReturn Values
In this task, you write a test class that adds multipleShirtobjects to anOrder object and displays a total current amount, in dollars, for the order.Follow these steps to write your test class:
1. Go to the working directory and open an editor.
2. Open theShirt.javafile and examine the member variables andthe method in it.
3. Open theOrder.javafile and examine its member variables andmethod in it.
4. Write a new class calledOrderTestcontaining amainmethod.
5. In themainmethod:
a. Create and initialize an object of typeOrderand an object of
typeShirt. TheOrderclass (Order.java) and theShirtclass(Shirt.java) are provided in the exercise1 directory.
b. Declare a variable of type double, name it astotalCostandinitialize it by 0.0.
c. Assign thepricefor theShirtobject to 14.00.
8/11/2019 JAVA Certification ORacle Training Manuals
71/108
Exercise1: Using Arguments and Return Values
Developing and Using Methods 8-5Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
d. Invoke theaddShirtmethod of theOrderclass using theOrder instance to add theshirt instance to the order. Store thereturn value of theaddShirtmethod in the totalCost variable.The documentation for theaddShirtmethod is as follows:
public double addShirt (Shirt s)
Adds a shirt to a list of shirts in an order
Parameters:
s An object reference to aShirtobject
Returns:
A total current amount for the order
e. Display the return order amount. For example:
Total amount for the order is: 14.00
6. Compile and execute your program. Verify if the total order value isdisplayed.
7. In the main method ofOrderTestclass, create additionalShirtobjects, assign values to theprice variable of the newShirt objects,and add theShirtobjects to your order by invoking theaddShirtmethod.
8. Save and compile theOrderTest.javafile.
9. ExecuteOrderTestclass and verify that the total order value isdisplayed correctly.
8/11/2019 JAVA Certification ORacle Training Manuals
72/108
Exercise2: Using Overloaded Methods
8-6 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Exercise 2: Using Overloaded Methods
The objective of this exercise is to implement method overloading.
In this exercise, you create overloaded methods in a class and invoke themethods and test it.
Preparation
Ensure thatCustomerTest.javafile exists in theSL110/exercises/08_methods/exercise2directory. This is yourworking directory.
Task Developing a Class With an OverloadedMethod
In this task, you write aCustomer class with an overloaded method calledsetCustomerInfo.
Follow these steps to write your class:
1. Go to theworking directory and open an editor.
2. Create a class calledCustomer and save the file asCustomer.java
in the working directory.
3. Within theCustomerclass, add two overloaded methods calledsetCustomerInfo.
Depending on how thesetCustomerInfomethod is called, it doesone of the following:
Sets the ID, name, address, and phone number for aCustomerobject. (This is the minimum information needed for a newCustomer.)
Sets the ID, name, address, phone number, and email address
for aCustomerobject.
4. Create adisplay method to display the values of all the membervariables of theCustomerclass.
5. Save and close theCustomer.javafile.
6. Open the file calledCustomerTest.java to test the overloadedmethods of theCustomerclass.
8/11/2019 JAVA Certification ORacle Training Manuals
73/108
Exercise 2: UsingOverloaded Methods
Developing and Using Methods 8-7Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
7. In themainmethod ofCustomerTest class write code to perform thefollowing tasks:
a. Create two object references to differentCustomerobjects.
b. Use each variation of thesetCustomerInfo method to provide
information for eachCustomer
object.c. Display the contents of eachCustomerobject.
8. Save and compile the fileCustomerTest.javafile.
9. Execute theCustomerTestclass and view the output of the class.
8/11/2019 JAVA Certification ORacle Training Manuals
74/108
Exercise Summary
8-8 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Exercise Summary
?
!
Discussion Take a few minutes to discuss what experiences, issues, ordiscoveries you had during the lab exercises.
Experiences
Interpretations
Conclusions
Applications
8/11/2019 JAVA Certification ORacle Training Manuals
75/108
9-1Copyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Lab 9
ImplementingEncapsulationandConstructors
Objectives
Upon completion of this lab, you should be able to:
Complete review questions Use encapsulation in a Java technology class
Implement constructors in a class
8/11/2019 JAVA Certification ORacle Training Manuals
76/108
Lab Overview
9-2 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Lab Overview
In this lab, you complete the review questions and three exercises.
In the first exercise, you implement encapsulation in a Java
technology class. In the second exercise, you access encapsulated attributes of a class.
In the third exercise, you implement constructors in a Javatechnology class.
8/11/2019 JAVA Certification ORacle Training Manuals
77/108
Completing Review Questions
Implementing Encapsulation and Constructors 9-3Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
Completing Review Questions
Complete the following questions:
1. Which of the following statements defines an interface
a. The way a class completes its tasks within a method
b. The operations and attributes of an object
c. The way other objects interact with an object
d. The declaration of private attributes
2. State whether the following statements are true or false:
a. The private members of an object can be accessed throughpublic methods
b. Constructors cannot be overloaded
3. The scope of a variable refers to:
a. The lifetime of the variable
b. Where a variable can be used within a program, also known as,the extent of a variable.
c. The way other objects interact with an object
d. Whether the variable isprivateorpublic
4. What is the default constructor for the following class?
public class Penny {String name = "lane";
}
a. Penny()
b. public Penny()
c. class()
d. String()
8/11/2019 JAVA Certification ORacle Training Manuals
78/108
Exercise 1: Writing Encapsulated Classes
9-4 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Exercise 1: Writing Encapsulated Classes
The objective of this exercise is to write a class that uses encapsulation tohide data from other objects.
In this exercise, you create a class calledDateOne and modify its attributesto implement encapsulation and examine the output.
This exercise consists of two tasks:
Task 1 Implementing Encapsulation in a Class
Task 2 Accessing Encapsulated Attributes of a Class
Preparation
Ensure that theDateOneTest.java,DateTwoTest.java, andDateThreeTest.javafiles exists in theSL110/exercises/09_encapconstr/exercise1directory. This is yourworking directory.
Task 1 Implementing Encapsulation in a Class
In this task, you create a class containingprivateattributes and try to
access them in another class.
Follow these steps to write your test class:
1. Go to the working directory and open an editor.
2. Create a class calledDateOnethat contains three member variablesof typeintnamed:day,month,and year. Givepublicaccess to allthe member variables. Save the class with the nameDateOne.java.
3. Open theDateOneTest.java file provided in the working directoryand write the following in itsmainmethod:
a. Create and initialize an object of typeDateOne.b. Assign different numeric values to the member variables of the
DateOneinstance.
c. Display the value of the member variables of theDateOneinstance.
4. Save and compileDateOneTest.javafile.
8/11/2019 JAVA Certification ORacle Training Manuals
79/108
Exercise 1: Writing Encapsulated Classes
Implementing Encapsulation and Constructors 9-5Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
5. Execute theDateOneTestclass file and examine the output.
6. Create a new class calledDateTwosimilar toDateOnewith threemember variables and save it asDateTwo.java.
7. Modify the access specifier of the three member variables ofDateTwo
toprivate
.8. Open theDateTwoTest.java file provided in the working directory
and perform the same steps as in Step 3. However, in this case createan instance ofDateTwoclass instead ofDateOneclass. The otherlines of code will remain the same.
9. Save and compileDateTwoTest.java.
10. Examine the compilation errors and identify the reason of thecompilation errors.
Task 2 Accessing Encapsulated Attributes of a Class
In this task, you create a class with private attributes and enable them tobe manipulated from another class.
Complete the following steps:
1. Create a class calledDateThreeand save it withDateThree.javafile name.
2. DateThreeclass has the same three private member variables as
DateTwoclass.3. Add the following methods in theDateThreeclass:
a. getandsetmethods for all three member variables. Forexample:
public void setDay(int d) { day = d;
}public int getDay() { return day; }
8/11/2019 JAVA Certification ORacle Training Manuals
80/108
Exercise 1: Writing Encapsulated Classes
9-6 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
b. ThesetDatemethod It accepts three arguments of typeintand assigns the value of the arguments to theday,month, andyearmember variables of theDateThreeclass, respectively.Before assigning the parameters to the member variablesvalidate them such that the day is within 30, 31, 28, 29, and
month is between 1 and 12 and year is between 1000 and 10000.For example February 31 should not be accepted. Errormessages should be displayed whenever the validation fails.
Note Useswitch casestatements andif elsestatements forperforming the validations.
ThedisplayDatemethod Prints the date in the followingform:Todays Date is: 10/25/2006
4. Save and compileDateThree.java
5. Open theDateThreeTest.java file provided in the workingdirectoryand perform the following in themainmethod:
a. Create and initialize and instance ofDateThreeclass
b. Invoke thesetDay,setMonth, andsetYearmethods and passvalid values as arguments to these methods.
c. Display the values of theDateThreemember variables using itsgetDay,getMonth, andgetYearmethods. For example:System.out.println( The date is +dateObj.getMonth()+ / dateObj.getDay() + / +dateObj.getYear());
// dateObj is an instance of DateThree class
6. Save and compile theDateThreeTest.javafile.
7. Execute theDateThreeTestclass and examine the output.
8. Reopen theDateThreeTest.javafile.
9. In themainmethod, add code at the end which will do thefollowing:
a. Invoke thesetDatemethod using the instance ofDateThree
class and pass valid values as arguments to the method.
b. Invoke thedisplayDatemethod using the instance ofDateThreeclass.
8/11/2019 JAVA Certification ORacle Training Manuals
81/108
Exercise 1: Writing Encapsulated Classes
Implementing Encapsulation and Constructors 9-7Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
10. Save, compile, and execute theDateThreeTest.javafile.
11. Examine the output and see if any error messages are displayed.
12. In theDateThreeTest.java file, modify the value of the argumentspassed in thesetDatemethod, repeat Step 10 and Step 11.
?
!
Discussion You can discuss the possible error conditions while settingvalues for the month, day, and year in thesetDatemethod. Ask thestudents to test theDateThreeclass with all of them and verify the errormessages.
8/11/2019 JAVA Certification ORacle Training Manuals
82/108
Exercise 2: Using Constructors
9-8 Fundamentals of the Java Programming LanguageCopyright2007 SunMicrosystems, Inc. AllRights Reserved.SunServices,RevisionE.1
Exercise 2: Using Constructors
The objective of this exercise is to implement constructors in a class.
In this exercise, you create overloaded constructors in a class and usethem to initialize objects of that class.
You have two tasks in this exercise:
Task 1 Creating and Using Constructors
Task 2 Creating Constructors to Initialize Objects
Preparation
Ensure that theDateFourTest.java andRectangleTest.java file existsin theSL110/exercises/09_encapconstr/exercise2directory. This isyour working directory.
Task 1 Creating and Using Constructors
In this task, you write aDateFourclass with constructors and createobjects of the class to use the constructors appropriately.
Follow these steps to write your class:1. Go to your working directory and open an editor.
2. Create a class calledDateFour similar toDateThree as in Exercise 1and save the file asDateFour.javain the working directory.
3. Add a constructor, with no arguments, to theDateFour.javafilethat assigns the value ofmonthto 1, theday to 1, and theyear to2007.
4. Rename thesetDatemethod to be a constructor that accepts,verifies, and sets themonth,day, andyear.
5. Save and compile theDateFour.javafile.
6. Open theDateFourTest.javafile. In themainmethod createDateFourobjectsd1andd2, whered1is created using the no-argument constructor andd2is created using the three-argumentconstructor.
8/11/2019 JAVA Certification ORacle Training Manuals
83/108
Exercise 2: Using Constructors
Implementing Encapsulation and Constructors 9-9Copyright2007 SunMicrosystems, Inc. AllRightsReserved. SunServices,RevisionE.1
7. In yourDateFourTestclass, invoke thedisplaymethod to displaytheday,month, andyearvalues ford1andd2.
8. Compile theDateFourTest.javafile, execute it, and verify theoutput.
The output from theDateFourTest
class should be similar to thefollowing:
Todays Date is: 1/1/2007Todays Date is: 3/9/1967
Task 2 Creating Constructors to Initialize Objects
In this task, you create a class and use constructors to initialize objects.Follow these steps to create yo
Top Related