7. •
•
•
•
•
2-1
Student Exercises for Unit 2
Exercise 1: Create a Java Project
In this exercise, you will create a Java project that points to the JavaBasics directory. This
root directory will contain your source code. Your compiled code will also remain in this
directory.
___ 1. Open the Eclipse IDE, if it is not already open.
___ 2. Select the New option or navigate to File > New in the main menu.
___ 3. Select Project.
15. •
•
•
•
•
3-1
Student Exercises for Unit 3
Exercise 1: Calculate an Average
In this exercise you will write a class to calculate the average of a variable number of
arguments.
The average of a set of numeric values is determined by adding all of the values together
and dividing the calculated sum by the number of values. For example, the average of 10,
4, 8, 6, 5, 10, and 13 is 8:
(10+4+8+6+5+10+13)/7 = 56/7 = 8
The class must include a main() method. Within the body of the main() method, convert
each argument to a numeric data type, calculate the average, and output the result.
___ 1. Select File > New > Package to create the exercises.calc package using the
Eclipse IDE.
___ 2. Select the exercises.calc package and right-click to access the context menu.
___ 3. Select New > Class from the context menu and create the Average class. Select
the option to include a main() method when creating your class.
___ 4. Within the main() method, write the code to calculate an average of the program
arguments.
– The program arguments are stored in the variable args, which is an array of
Strings.
– The variable args[0] returns the first argument, args[1] returns the second
argument, and so on.
– The variable args.length returns an integer value that represents the number
of arguments.
– Use the static method Double.parseDouble(String s) to convert an argument
from a String data type to a numeric value.
– The following example shows one possible way to iterate through the
arguments:
for (String v : args) {
System.out.print(v + “ “);
}
System.out.println();
23. •
•
•
•
•
4-1
Student Exercises for Unit 4
Exercise 1: Create the ModAdd Class
This exercise involves creating a class named ModAdd that belongs to the package
exercises.odd.
• The class ModAdd will receive two numeric arguments.
• Calculate the sum of the odd numbers that are multiples of 3 between those two
arguments, including the arguments that define the numeric limits for the
calculation.
• Calculate the sum with a for loop and a while loop.
• Use the modulus operator to determine if a number is a multiple of 3 or is an odd
number.
– A number is a multiple of 3 if num%3 equals zero.
– A number is a multiple of 2 if num%2 equals zero.
The following example shows a possible outline for the ModAdd class:
package exercises.odd;
public class ModAdd
{
// main program receives 2 arguments
public static void main(String[] args)
{
// Check if arguments are given
// If not, print error msg and System.exit(1);
//
// Get arguments and check if valid
// Calculate sum using for loop and print total
// Calculate sum using while loop and print total //
}
27. •
•
•
•
•
5-1
Student Exercises for Unit 5
Exercise 1: Create the ReverseArgs Class
This exercise involves creating a class named ReverseArgs that belongs to the package
exercises.str. You will print out the argument list in reverse.
• The ReverseArgs class will receive two or more arguments.
• The ReverseArgs class will contain a method to reverse the arguments letter by
letter.
• The ReverseArgs class will contain a method to reverse the arguments word by
word.
The following example shows a possible outline for the ReverseArgs class:
package examples.str;
public class ReverseArgs {
public static void main(String args[]){
if(args.length < 2) {
// print usage statement
return;
}
StringBuilder strArguments = new StringBuilder();
// Build a string using the args[]
reverseArguments(strArguments);
System.out.println ("strArguments = " + strArguments);
// return strArguments to its original state
reverseArguments(strArguments);
System.out.println ("strArguments = " + strArguments);
reverseWords(strArguments);
System.out.println ("strArguments = " + strArguments);
}
33. •
•
•
•
•
6-1
Student Exercises for Unit 6
Exercise 1: Implement Exception Handing
This exercise involves making a copy of the Perform.java file, renaming it Do.java, and
adding exception handling.
• Throw an exception if parameters are not provided or if the operation is invalid.
• Use try-catch blocks to catch exceptions when parsing arguments.
___ 1. Copy the contents of Perform.java and rename the file and class Do.java.
___ 2. Add exception handling to the class.
___ 3. Save and compile the Do.java file.
___ 4. Verify the results with the cases in the following table.
Exercise 2: Read and Write to Text Files
This exercise involves reading and writing to a text file using the FileReader,
BufferedReader, FileWriter, and BufferedWriter classes.
A useful class for this exercise is java.util.Scanner, which can be used for parsing fields
from a file. Regular expressions in the String class provide a replacement for the
deprecated java.util.StringTokenizer class.
Arguments Expected Result at Runtime
No arguments Invalid case
Add 1.0 two.2 Second operand is not a number
abc 2 3 Invalid operation
Sub 77 22 Valid case
37. •
•
•
•
•
7-1
Student Exercises for Unit 7
Exercise 1: Using an Interface
This exercise uses an interface to demonstrate polymorphism. It involves creating an
interface named HowAreYou and writing three classes that implement that interface. Each
class will print “How are you?” in its own language.
• Throw an exception if parameters are not provided or if the operation is invalid.
• Use try-catch blocks to catch exceptions when parsing arguments.
___ 1. Using the Eclipse IDE, create an interface named HowAreYou.java that contains
a single method named sayHowAreYou().
___ 2. Create three class files that implement the HowAreYou interface, such as:
– EnglishHowAreYou.java
– ItalianHowAreYou.java
– FrenchHowAreYou.java
___ 3. Each of the three classes must implement the sayHowAreYou() method and print
“How are you?” to the console in the appropriate language.
___ 4. Create a class named SayHowAreYou that contains main().
___ 5. The SayHowAreYou class contains an instance of the HowAreYou interface, sets
the language to the three different implementing classes, and prints “How are
you?” to the console in three different languages.
The following example shows a possible outline for the driver class:
package exercises.HowRU;
public class SayHowAreYou {
public HowAreYou howAreYou;
public void setLanguage(HowAreYou howAreYou) {
this.howAreYou = howAreYou;
}
47. •
•
•
•
•
8-1
Student Exercises for Unit 8
Exercise 1: Determine a Median
In this exercise you will write a class to determine the median of a variable number of
arguments. To find the median value, place the values in order and find the middle value.
If there is an even number of values, find the middle pair of values and calculate the average
of those two values.
___ 1. Create the new class Median in the exercises.calc package.
___ 2. Within the main() method, write the code to calculate the median of the program
arguments.
Hint: The java.util.Arrays.sort() method is useful for this exercise.
___ 3. Save and compile the Median class.
___ 4. Run the Median class and verify the results.
Exercise 2: Use a LinkedList
In this exercise you create a class that implements the LinkedList class and uses the
ListIterator to print a list in reverse.
• Throw any necessary IO exceptions.
• Use try-catch blocks to catch exceptions.
57. •
•
•
•
•
9-1
Student Exercises for Unit 9
Exercise 1: The Producer–Consumer
Classes
Threads that execute in parallel and share common resources must be synchronized at
certain points to ensure proper functioning of the system.
In this exercise you add code to a partially completed class. The code you add will
synchronize the data shared between the Producer and the Consumer classes so that the
two classes can work together.
The Producer-Consumer example is often used to illustrate thread synchronization
techniques. The Producer-Consumer classes were written to create a practical example.
The Producer and Consumer classes share a common resource: the SharedData class.
The Producer class contains an infinite loop that generates integer values in sequence and
places those integer values into the SharedData object. The Consumer class contains an
infinite loop that reads the integer values from the SharedData object.
The purpose of this exercise is to synchronize the classes so that consecutive integers are
not lost and duplicate integers are not retrieved.
The following example shows the contents of the Producer, Consumer, and SharedData
classes:
public class Producer implements Runnable
{
SharedData data;
int interval;
int identifier;
public Producer(SharedData data, int id, int interval) {
this.data=data;
this.interval=interval;
this.identifier=id;
}
public void run() {
int i;
for(i=0; ; i++) {
data.put(i);
System.out.println("Producer "+ identifier+ ": "+i);
try {
63. •
•
•
•
•
10-1
Student Exercises for Unit 10
Exercise 1: Create a Serializable Object
In this exercise you create a class that is serializable and write the object to a text file.
• Throw any necessary IO exceptions.
• Use try-catch blocks to catch exceptions.
___ 1. Create a class named SerialObject.java that belongs to the examples.serial
package and implements the Serializable interface.
___ 2. Add variables to the SerialObject class. Try adding a transient variable, a
primitive, a collection type of object, or any other type of object. For example:
public class SerialObject implements Serializable {
transient int transValue;
int value;
String stringValue;
ArrayList<String> lst;
___ 3. Write a constructor for the SerialObject class that assigns values to the variables
to define their state.
Exercise 2: Serialize an Object
___ 1. Create a class named SerializeDriver.java that belongs to the examples.serial
package.
___ 2. Create an instance of SerialObject object and assign values to all of the variables.
___ 3. Populate any collection type of objects in the SerialObject object.
___ 4. Using FileOutputStream and ObjectOutputStream objects, write the state of a
SerialObject object to a file.
69. •
•
•
•
•
A-1
Appendix A: Exercise Solutions
Unit 1 Exercise Solutions
No solutions are provided.
Unit 2 Exercise Solutions
//
// Solution for HelloWorld Exercise
//
package exercises.hello;
public class HelloWorld
{
public static void main(String[] args)
{
System.out.print("Hello World!n");
System.out.println("I am here!");
}
}
Unit 3 Exercise Solutions
Exercise 1
package exercises.calc;
public class Average {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("No arguments to compute average");
return;
}