Java Programming Exercises
Java Programming Exercises
Table of Contents
Table of Contents....................................................................................................................... 1 Exercise 1................................................................................................................................... 3 Goal....................................................................................................................................3 Install the Java Development Kit (JDK)............................................................................3 Add the JAVA_HOME and Modify the PATH Environment Variables...........................3 Edit and Run a Simple Java Application............................................................................3 Exercise 2................................................................................................................................... 5 Goal....................................................................................................................................5 Description of the Order Entry Area of the Business.........................................................5 Understanding the Object-Oriented Principles...................................................................5 Identifying Business Classes, Attributes, and Methods.....................................................5 Exercise 3................................................................................................................................... 7 Goal....................................................................................................................................7 Understanding Objects, Classes, Methods, and Attributes................................................7 Exploring Code..................................................................................................................7 Questions About the Java Development Kit......................................................................8 Creating Order Entry Class Files........................................................................................8 Create and Compile the Application Class with a main() Method.....................................9 Exercise 4................................................................................................................................. 11 Goal..................................................................................................................................11 Your Assignment..............................................................................................................11 Create the OrderItem Class..............................................................................................11 Modify the Order Class....................................................................................................11 Modify the main() Method in the OrderEntry Class........................................................12 Exercise 5................................................................................................................................. 14 Goal..................................................................................................................................14 Your Assignment..............................................................................................................14 Create the Util Class.........................................................................................................14 Modify the Order Class....................................................................................................16 Test the Code by Using the OrderEntry Class..................................................................17 Exercise 6................................................................................................................................. 18 Goal..................................................................................................................................18 Your Assignment..............................................................................................................18 Refine the Customer Class...............................................................................................18 Create Customer objects...................................................................................................18 Refine the OrderItem Class..............................................................................................19 Refine the Order Class.....................................................................................................19 Modify OrderEntry to Associate a Customer to an Order................................................20 Exercise 7................................................................................................................................. 21 Goal..................................................................................................................................21 Your Assignment..............................................................................................................21 Modify the Customer Class..............................................................................................21 Modify the Order Class....................................................................................................21 Create the DataMan Class................................................................................................23 Modify OrderEntry to Use DataMan...............................................................................23 Exercise 8................................................................................................................................. 25 Page 1
Introduction to Java Programming Exercises Goal..................................................................................................................................25 Your Assignment..............................................................................................................25 Add Formatting Methods to the Util Class......................................................................25 Use the Util Formatting Method in the Order Class........................................................26 Use Formatting in the OrderItem Class............................................................................26 Use the Util.getDate() Method to Set the Order Date......................................................26 Exercise 9................................................................................................................................. 27 Goal..................................................................................................................................27 Your Assignment..............................................................................................................27 Part 1: Installing Eclipse...................................................................................................27 Part 2: Using Eclipse: Create a new workspace and project............................................27 Part 3: Create a Workspace and Project for the Course Application Files.......................29 Debugging Your Application Code..................................................................................30 Exercise 10............................................................................................................................... 32 Scenario............................................................................................................................32 Goal..................................................................................................................................32 Your Assignment..............................................................................................................32 Define a New Company Class..........................................................................................33 Define a New Individual Class as a Subclass of Customer..............................................34 Modify the DataMan Class to Include Company and Individual Objects........................34 Test Your New Classes in the OrderEntry Application...................................................34 Refine the Util and Customer Classes and Test Results..................................................35 Exercise 11............................................................................................................................... 37 Goal..................................................................................................................................37 Your Assignment..............................................................................................................37 Modify DataMan to Keep the Customer Objects in an Array..........................................37 Modify DataMan to Find a Customer by His or Her ID...................................................38 Modify the Order Class to Hold a List of OrderItem Objects..........................................39 Modify OrderItem to Handle Product Information..........................................................39 Modify Order to Add Products into the OrderItem List...................................................40 Modify Order to remove Products from the OrderItem List............................................41 Exercise 12............................................................................................................................... 42 Goal..................................................................................................................................42 Your Assignment..............................................................................................................42 Create an Abstract Class and Three Supporting Subclasses............................................42 Modify DataMan to Provide a List of Products and a Finder Method.............................43 Modify OrderItem to Hold Product Objects.....................................................................44 Modify Order to Add Product Objects into OrderItem....................................................44 Create and Implement the Taxable Interface....................................................................45 Exercise 13............................................................................................................................... 48 Goal..................................................................................................................................48 Your Assignment..............................................................................................................48 Create the NotFoundException Class...............................................................................48 Throw Exceptions in DataMan Find Methods and Handle Them in OrderEntry............48
Page 2
Exercise 1
Goal
The goal of this exercise is to install the Java Development Kit (JDK) and examine the development environment. You will set environment variables, and examine the JDK directory structure. You will then write, compile, and run a simple Java application. Finally, you will run and examine the solution application for the course.
Introduction to Java Programming Exercises install the Crimson Editor available in the C:\JavaCourse\installers directory.) 2. In the editor, enter the following code, placing your name in the comments (after the Author: label.) Also, make sure that the case of the code text after the comments is preserved, as Java is case-sensitive:
/** * File: HelloWorld.java * Author: <Enter your name> */ public class HelloWorld { public static void main(String[] args) { System.out.println(Hello, World!); } }
3. Save the file, make sure the file is called HelloWorld.java, keeping the editor running, in case compilation errors occur requiring you to edit the source to make corrections. 4. Compile the HelloWorld.java source file (file name capitalization is important.) a. In the Command Prompt, make sure the current directory is C:\JavaCourse\labs\hello. If not, issue the command: cd C:\JavaCourse\labs\hello. b. Check that the source file is there. Issue the command: dir c. Compile the file using the command: javac HelloWorld.java d. What file is created if you successfully compiled the code? 5. Run the HelloWorld application. Again, capitalization is important. a. Run the program using the command: java HelloWorld b. What was displayed in the window?
Page 4
Exercise 2
Goal
The goal of this exercise is to become familiar with object-oriented concepts, including classes, methods, and attributes. You will also learn how to read a UML class model showing the business objects for the course application.
Introduction to Java Programming Exercises 4. Define some behaviors (methods/operations) for each of the classes that you have found. 5. Look for classes that could inherit structure (attributes) and behavior (methods) from other classes. Modify your definitions to reflect the inheritance model.
Page 6
Exercise 3
Goal
The goal of this exercise is to create, examine, and understand the Java code. You will create a class representing a command line application for the Order Entry system that contains the application entry point in the form of a main() method. You will use the UML model from the previous lesson as a guide to creating additional class files for your application. You will run some simple Java applications, fixing any errors that occur. You will also discriminate standard compiler errors and learn how and where to fix them.
Exploring Code
2. Examine code in this HelloWorld.java class, and answer the questions that follow:
public class HelloWorld { private int age; private String address; private String telephone; public int getAge() { return age; } public void setAge(int newAge) { age = newAge; } public static void showMessage(String msg) { int messageNumber = 0; messageNumber = messageNumber + 1; System.out.println(msg + ' ' + messageNumber);
3. Answer the following questions for the source code: a. What is the name of the class? Page 7
Introduction to Java Programming Exercises b. List the instance (non-static) methods? c. List the instance (non-static) variables. d. Name the method variables. e. Which are the class (static) methods and variables? f. Identify method parameter names. g. Which methods return values?
Page 8
Introduction to Java Programming Exercises e. Where is the compiled .class file created? f. Repeat steps (b) to (d) for the Order.java file Sample Customer.java file:
package oe; public class Customer { int id; String name; String address; String phone; public public public public public public public public void void void void setId(int newId) { } setName(String newName) { } setAddress(String newAddress) { } setPhone(String newPhone) { }
int getId() { return id; } String getName() { return name; } String getAddress() { return address; } String getPhone() { return phone; }
int getId() { return id; } String getOrderDate() { return orderDate; } String getShipDate() { return shipDate; } String getShipMode() { return shipMode; } double getOrderTotal() { return orderTotal; }
10. Running the skeleton application: a. Execute the OrderEntry class file, as follows and explain the result:
java OrderEntry
b. Modify the CLASSPATH to include the application classes directory, and enter the following command:
set CLASSPATH=C:\JavaCourse\labs\OrderEntry\bin
c. Run the application again as in step (a). Explain the result. d. Finally, run the application but prefix the class name with its package name oe and a dot, as follows, and then explain the result:
java oe.OrderEntry
Page 10
Exercise 4
Goal
The goal of this exercise is to declare and initialize variables, and use them with operators to calculate new values. You will also be able to categorize the primitive data types and use them in code, and learn how to modularize code in methods. The business area for this exercise is the Order class and a new supporting class called OrderItem, showcasing some basic collaboration to assist with computations for the order total.
Your Assignment
You will create the OrderItem class to declare instance variables to hold the item line number, quantity, and costs. You also create the methods to get and set the OrderItem values and calculate the item total. You then modify the Order class to contain two OrderItems, set the item details, and then determine the sum of the item totals to calculate the order total. Finally, you use the main() method in the OrderEntry class to test your code by creating an Order and determining the order total, to which you add a tax amount to form the final order total.
c. Create a public get and set method for each of the instance variables, for example:
public int getLineNo() { return lineNo; } public void setLineNo(int newLineNo) { lineNo = newLineNo; }
d. Create a method to return the item total based on the quantity multiplied by the price, by using the following signature:
public double getItemTotal() { return <your calculation>; }
Introduction to Java Programming Exercises getOrderTotal() method in the Order class to return the sum of the items. 2. In the Order class, declare two item instance variables as follows:
OrderItem item1 = new OrderItem(); OrderItem item2 = new OrderItem();
This creates two OrderItem objects. You will learn the significance of the new keyword in a subsequent lesson. For now, just accept that these are needed for the task. 3. Modify the method called getOrderTotal() to add the item totals to the orderTotal. The steps (a) through (d) guide you through this process. a. Declare two local variables called item1Total and item2Total, both of type double, to hold the item totals, respectively. b. Set the line number, price, and the quantity for each item object, by calling its methods, according to the following table:
Item item1 item2 lineNo 1 2 quantity 2 2 unitPrice 2.95 3.50
For example:
item1.setLineNo(1); item1.setQuantity(2); item1.setUnitPrice(2.95);
c. Set each item total variables by calling the getItemTotal() method for each item variable, and display the item total as shown in the example:
item1Total = item1.getItemTotal(); System.out.println("Item 1 total: " + item1Total);
d. Add the two item totals and store the result in the orderTotal before it is returned from the method. Just use the orderTotal variable as itself as it is declared in the Order class. e. Save and compile the Order class.
b. Declare a variable of type double to hold the order total. c. Declare a Boolean variable to track if the purchase exceeds the $10.00 limit. d. Declare and initialize another variable to hold an 8.25% tax rate. e. Declare a variable to hold the tax value. Page 12
Introduction to Java Programming Exercises 5. Determine the order total. a. Call the Order objects getOrderTotal() method and store the result in the variable that is declared to hold its value. b. Display the order total before tax is added, by using the System.out.println() technique to display the contents of your variable. c. Calculate the tax of the order total and store in the tax value variable. Display the tax value calculated. d. Add the tax to the order total, and print the value. e. Set the Boolean variable, by using the relational and logical operators, to determine if the total cost exceeds the limit of $10.00 and print its Boolean value. Do not use any type of if statement in this step. 6. Save and compile OrderEntry. Test your logic by running the OrderEntry class.
Page 13
Exercise 5
Goal
The goal of this exercise is to make use of flow control constructs in a new class, called Util that provides methods to determine the number of days in a month, and handle leap years. Then you modify the Order class to set the order date and derive an expected ship date based on a shipping location.
Your Assignment
In this exercise, you create the Util class to contain methods to check if a year is a leap year, and then determine the number of days in a month for a given year, handle leap years, and return the number of days to ship an order to a specified region. The Order class will be modified to set the order date and have a new method added called getShipDate(). Determine the ship date for the order, based on the day it was ordered and how many days it takes for shipping.
c. Add the code to the main() method to test your leap year method as follows:
int year = 1900; System.out.println("Year: " + year + " leap year? " + isLeapYear(year));
Check the results for the following years: 1900, 1964, 1967, 1984, 1996, 1997, 2000, and 2001. The leap years from the list are: 1964, 1984, 1996, and 2000. d. Save, compile, and test your code:
javac d ..\..\bin Util.java java oe.Util
2. Add another public static method to Util class called lastDayInMonth() that returns the number of days in the months, for a specified month and year. a. Declare the parameters and return values as integers. In the method body, use a switch statement on the month, remembering how many days are in each month with this reminder (if you need it): Page 14
Introduction to Java Programming Exercises There are 30 days in September, April, June, and November. All the rest are 31, except for February, which has 28 or 29 if it is a leap year. Note: Handle leap years by making use of the isLeapYear() method. Return a zero if the month is invalid. b. Add code in the main() method to test your method by declaring two integer variables to hold a day and month in addition to the year (for example: 27 January 2002). Then print the date, using System.out.println(), in D/M/Y format looking like:
Date is: 27/1/2002 (and has 31 days in the month)
Repeat this test by using the date 20 February 2000. c. Save, compile, and run the Util class (as shown in step 1(d)). d. What happens if you choose the month with an invalid value, such as 13? 3. Write a public static method called getDaysToShip() that returns an integer representing the number of days to ship an order to a specified region. a. The region is supplied as a single case-sensitive character argument. Use a switch statement and the following table as your guide:
Region Americas Europe/Africa Asia pacific Character 'A' 'E' 'P' Days to Ship 3 5 7
b. Modify the main method to declare and set a variable to hold the number of days to ship an order to a specified location to test the method, for example:
int daysToShip = getDaysToShip('A');
Print the results. c. Save, compile, and run the Util class (as shown in step 1(d)). 4. Add a loop to the main() method of the Util class that starts at a specific order date and prints all the dates to the end of the month. Use the date: 27 January 2002. a. Use the day, month, and year variables that were previously declared to initialize the date and set the number of days in the month. b. Write the loop to print the date in D/M/Y format starting at the specified day and ending at the last day of the month. For example:
27/1/2002 28/1/2002 29/1/2002 30/1/2002 31/1/2002
c. Modify the loop to terminate either at the last day of the month, or at the day representing the ship date for a region of Americas ('A'). Terminate the loop at the earliest of date that occurs first. The output should produce the following results:
27/1/2002 28/1/2002 29/1/2002
Page 15
Introduction to Java Programming Exercises d. Compile and run the code. e. Test the example for the other regions, E for Europe/Africa, and P for Asia Pacific. Alter the start date to 10 February 2002 or any day that you like.
5. Modify the setOrderDate() method to accept three integer parameters for a day, month, and year (instead of a single string parameter) to set the order date. a. To store the date values comment out orderDate instance variable, and declare three integer instance variables to hold the order day, month, and year. b. In the setOrderDate() method, initialize the order day, month, and year to zero to indicate that it is invalid. Before setting these values based on the parameters perform the following validation checks: i. The day is between 1 and the last day of the month (inclusive). Use the Util.lastDayInMonth() method to help with this test as follows:
int daysInMonth; daysInMonth = Util.lastDayInMonth(month, year);
For now, accept that this is how you call a static method in a class. A subsequent lesson in the course will discuss this technique more formally. ii. iii. The month is from 1 to 12 (inclusive). The year is not less than 1.
c. Modify the getOrderDate() method to return the date string set in D/M/Y format. d. In the Order class, add a method to return the ship date as a string in D/M/Y format. The method uses the day, month, and year instance variable in the Order class, and a character parameter representing the region to ship the order to, to determine the ship date. Use the following method signature:
public String getShipDate(char region) { int daysToShip = Util.getDaysToShip(region); }
The code above shows how to use the Util.getDaysToShip() method to determine the number of days that are required to ship the order to the specified region. To calculate the date of expected shipping: Page 16
i. ii. iii.
Introduction to Java Programming Exercises Declare three method variables to hold the due date (dueDay, dueMonth, dueYear). Initialize dueDay to the order date plus the days to ship order, dueMonth and dueYear to the order month and year respectively. If the dueDay is beyond the end of the month, then adjust the dueDay and dueMonth appropriately. If the adjusted dueMonth indicates a change of year, then alter the dueMonth and dueYear appropriately. Return the result string formed by concatenating the due day, month, and year in D/M/Y format.
iv.
e. Save, compile, and run the OrderEntry class. f. Test the ship date calculation by using an order date of 27 February 2001. g. Try changing the region to E and/or P to check the results for the ship date.
Page 17
Exercise 6
Goal
The goal of this exercise is to complete the basic functionality for existing method bodies of the Customer, Order, and OrderItem classes. You will then create customer and order objects, and manipulate them by using their public instance methods. You display the Customer and Order information back to a command prompt.
Your Assignment
In this exercise, you begin refining the application for the Order Processing business area. These classes continue to form the basis for the rest of the application that you are building for the remainder of the course. After creating one or more Customer objects, you will associate a customer with an order. This will require changes to the Order class.
Note: The toString() method is a special method that is called any time a String representation of an object is needed. The toString() method is very useful to add to any class, and thus it is added to almost all the classes that you create. b. Save the Customer class, and compile to remove any syntax errors by using:
javac d ..\..\bin Customer.java
Introduction to Java Programming Exercises using the new operator, assigning each one to a different object reference (use customer1 and customer2). b. At the end of the main() method, initialize the state of each Customer object by calling its public setXXX() methods to set the ID, name, address, and phone. Use the table data below:
Id 1 2 Name Gary Williams Lynn Munsinger Address Houston, TX Orlando, FL Phone 713.555.8765 407.695.2210
c. Print the two customer objects created, under a printed heading of Customers: by calling the toString() method inside the argument of the System.out.println() method, for example:
System.out.println("\nCustomers:"); System.out.println(customer1.toString());
Note: Alternatively, you can just print the customer object reference variable to achieve the same result. For example:
System.out.println(customer1);
This latter technique is a feature of Java that is discussed in a subsequent lesson. d. Save the OrderEntry class, compile, and run the class to view the results.
Page 19
Introduction to Java Programming Exercises d. Add a public void showOrder() method with no arguments to display the details of the order. The first line of output should show the order details, by calling the toString() method from step 5(c). Then show the customer details followed by the two item details in the order. Check if the customer and items are associated to objects, for example:
if (item1 != null) System.out.println(item1.toString());
Page 20
Exercise 7
Goal
The goal of this exercise is to gain experience with creating and using constructors, class methods, and attributes. You will also create a new class called DataMan that will be used to provide a data access layer for finding customers and products in the OrderEntry application. Part of the exercise is to understand method overloading by creating more than one constructor and/or method with the same name in the same class.
Your Assignment
Create at least one or more suitable constructors to properly initialize the Customer and Order objects when instantiated. Create the DataMan class to provide class (static) attributes of customer objects to be used by the OrderEntry application when it associates a customer object to an order.
f. Modify the OrderEntry class and simplify the creation of customer1 and customer2 object by using the second constructor of the customer (with three arguments). Remove (or comment out) all calls to setXXX() methods made with the customer1 and customer2 object references. Remember: The constructor allocates the customer ID. g. Save, compile, and run the OrderEntry class to check the results.
Introduction to Java Programming Exercises 2. First change the way in which you manage the order date information. a. Uncomment the orderDate variable that had been commented out in an earlier exercise, and make it a private variable. b. After the package statement at the top of the class, add the following import statements (before the class declaration):
import java.util.Date; import java.util.Calendar;
c. Redefine the orderDate type to be Date instead of String, and remove the three integer variables day, month, year that are replaced by orderDate. 3. Alter the methods that depend on the three integer date variables to use orderDate. a. Replace the return type and value of the getOrderDate() method as follows:
public Date getOrderDate() { return orderDate; }
In addition, create an overloaded void setOrderDate() method that accepts a Date as its parameter and sets the orderDate variable accordingly. b. Change the getShipDate() method to use the Calendar class to calculate the ship date. Replace the body of getShipDate() with the following code:
int daysToShip = Util.getDaysToShip(region); Calendar c = Calendar.getInstance(); c.setTime(orderDate); c.add(Calendar.DAY_OF_MONTH, daysToShip); return c.getTime().toString();
c. Alter the setOrderDate() method body to set the orderDate by using the Calendar class methods, using the three input parameters. First, delete the following date initialization code:
day = 0; month = 0; year = 0;
d. Also in the setOrderDate() method, replace the following three bold lines or code:
if ((m > 0 && m <= 12) && (y > 0)) { day = d; month = m; year = y; }
Note: You must subtract one from the methods month argument, because the Java Calendar class starts numbering months from 0 for January through 11 for December. Consult the Java API documentation for details of the methods that are used in the Calendar class. 4. Create a no-arg constructor to initialize the order number, date, and total. Page 22
Introduction to Java Programming Exercises a. Create a class (private static int) variable called nextOrderId and initialize it to 100 (representing the starting number for order IDs.) b. In the no-arg constructor, set the ID of the order to the value in nextOrderId. Then increment nextOrderId. Set the orderTotal to 0. Set the orderDate as follows:
orderDate = new Date();
c. Create a second constructor that accepts an order date argument as a Date, and a ship mode as a String. Call the no-arg constructor from this constructor and use the orderDate and shipMode instance variable using the arguments. d. Update the toString() method to include the shipMode in the return value if it is not null. e. Save and compile the Order class, and run the OrderEntry class to verify that the code still runs unchanged but picks up the changes to the order. f. In OrderEntry create another order with the second Order constructor passing a java.util.Date object and overnight ship mode as parameters. Set the order customer to customer2 and print the details. Recompile and run OrderEntry.
Add a couple of customer objects of your own creation, calling the variables customer3 and customer4 respectively. c. Save and compile the DataMan.java class as follows:
javac -d ..\..\bin DataMan.java
Introduction to Java Programming Exercises customer1 and customer2. For example, change the code:
order.setCustomer(customer1);
to become:
order.setCustomer(DataMan.customer1);
Note: You are accessing a class variable using its class name; that is, there is no need to create a DataMan object. In addition, the customer variables in DataMan are visible to OrderEntry because they have default (package) access. b. Save, compile, and run the OrderEntry class to test if the code still works. Replace customer1 with customer3 or customer4 from DataMan to confirm that your code is using the customer objects from DataMan.
Page 24
Exercise 8
Goal
The goal of this exercise is to modify the Util class to provide generic methods to support formatting the order details, such as, presenting the total as a currency and controlling the date string format that is displayed. This should give you exposure in using some of the java.text formatting classes.
Your Assignment
You will create a method called toMoney() to return a currency formatted string for the order total. You will also create a method called toDateString() that formats the date in a particular way. You will then modify the Order class to use these methods to alter display of order details, such as, the order date and total.
c. Save and compile the Util class. 2. Add a static toDateString() method to format a date: a. Add the following import statements to the class:
import java.util.Date; import java.text.SimpleDateFormat;
c. Save and compile the Util class. 3. Create another static method called getDate() that accepts three integers representing the day, month, and year, and returns a java.util.Date object representing the specified date (month = 1 represents January on input.) Because many methods in the Date class that could have been used are deprecated, you use the GregorianCalendar class to assist you with this task. a. Import the java.util.GregorianCalendar class. b. Use the following for the method:
public static Date getDate(int day, int month, int year) {
Page 25
// Decrement month, Java interprets January as 0. GregorianCalendar gc = new GregorianCalendar(year, --month, day); return gc.getTime();
b. Save and compile the Order class, and then run the OrderEntry class to view the changes to the displayed order details. c. Now import the java.text.MessageFormat class and use this class to format the toString() return value, as follows:
Object[] msgVals = {new Integer(id), Util.toDateString(orderDate), shipMode, Util.toMoney(getOrderTotal())}; return MessageFormat.format("Order: {0} Date: {1} " + "Shipped: {2} (Total: {3})", msgVals);
d. Save and compile the Order class, and then run the OrderEntry class to view the results of displayed order. The change to the displayed total should appear.
b. Save and compile the OrderItem class, and then run the OrderEntry class to view the changes to the order item total.
b. Save, compile, and run the OrderEntry class to confirm that the order date has been set correctly. Page 26
Exercise 9
Goal
In this exercise, you explore using the Eclipse IDE to create a workspace and project to manage your Java files during the development process. You practice how to create one or more Java applications and classes by using the rapid code generation features, such as, the code editor and debugger.
Your Assignment
In part 1, you install Eclipse and create a shortcut to the Eclipse executable in order to make it easy to start the Eclipse workbench. In part 2, you explore Eclipse default rapid code generation features by creating a new workspace, and then create a Java project which will contain a simple command line application. In part 3, you create a workspace called OrderEntry that will hold a single project called OrderEntry that will contain the course application Java files. You run the application and test it by using the debugger.
Introduction to Java Programming Exercises how to start Eclipse. 4. Launch Eclipse using a new workspace and create a new project. a. Double-click the Eclipse icon. The Workspace Launcher dialog box is displayed. This dialog allows you to create a new workspace or open to an existing workspace. Since we have not created any workspace before, enter C:\JavaCourse\workspaces\Hello and press OK. b. Eclipse will restart with the new workspace created. Click the right-most icon (named Workbench) on the Welcome screen to show the workbench. If the title of the Eclipse window is Java EE, select Window | Open Perspective | Java. We will be working with plain Java applications and not Java Enterprise Edition (Java EE) in this course. Eclipse supports multiple perspectives depending on what you are working on. Each perspective will show the most common views for that particular task. c. The first thing to do is to create a new Java project. Select File | New | Java Project. Alternatively, you can click the New Java Project button on the toolbar (an open folder with a blue J on it.) d. When the New Java Project dialog box is displayed, you will notice the following items to be entered and selected (leave each in their default states): the project name, where to store the contents, the JRE to use, and the project layout (whether to put the source and class files together or separately.) e. Enter the project name as Hello and press Finish. f. In the Package Explorer view, you will see the new project named Hello listed. Expand the project by clicking the plus sign to the left of the project name. You will see a folder called src displayed. This is where all Java source files are kept. There is also a bin folder created but Eclipse hides it. This is where the compiled .class files are stored. You can use the Windows Explorer to check that the folder is really there. 5. Create a new command line application. g. Click the Hello project on the Package Explorer if it is not already highlighted. Select File | New | Class to display the New Java Class dialog box. Alternatively, you can click the New Java Class button on the toolbar (a white C in a green circle.) You can also right-click on the project name and select New | Class. h. The New Java Class dialog box opens up. You can see that the Source folder has been entered for you. Leave the Package empty for now. Enter the class name (remember that a class name must start with a capital letter) as Application1. Click the checkbox labeled public static void main() to let Eclipse automatically create the main() method for the class. Press Finish. i. Eclipse creates a source file called Application1.java which appears under default package on the Package Explorer view. The generated source code for the new class should be visible in an editor window. j. In the editor window, in the main() method, delete the line starting with // TODO and enter the following code:
System.out.println("Hello Eclipse World!");
Page 28
Introduction to Java Programming Exercises k. If you look at the file name on the tab at the top of the editor window, you can see an asterisk to the left of the name. This means the file have been changed but not saved. Save you work by right-clicking anywhere in the source window and selecting Save. You can also press CTRL+S. Eclipse will save and automatically compile the source file and will highlight any errors at the appropriate places in the source window. Where exactly is the file created and explain your observations? l. Run the application by either selecting Run | Run As | Java Application menu item, or right-clicking the Application1.java and choosing Run As | Java Application. m. Eclipse automatically opens a Console view showing the results of the execution of the application. Where are the .class files, and what command did Eclipse use to run the application code?
Part 3: Create a Workspace and Project for the Course Application Files
In this part of the exercises, you create a new workspace. Then you create a project in the workspace and at the same time populate the project with the Java files that you created in the previous lessons. 6. Create a new empty workspace called OrderEntry. a. Select File | Switch workspace | Other b. Change the workspace directory name to be C:\JavaCourse\workspaces\OrderEntry. c. Click OK to create the workspace directory. d. Select Window | Preferences | Java | Compiler and set the Compiler compliance level: to 1.4. Click OK to close the dialog box. 7. Create a new project called OrderEntry in the new workspace and populate the project with the existing Java files in C:\JavaCourse\labs\OrderEntry\src. a. Select File | New | Java Project menu item. (Or click the New Java Project button on the toolbar.) Enter the project name as OrderEntry and click Finish. b. Expand the OrderEntry project in the Package Explorer view. Right-click on the src folder and select Import c. In the Import dialog box, expand General and click File System. This means we are importing files directly from the Windows file system. You can also import from an existing Eclipse project in another workspace or even from a JAR or ZIP file (Archive File). Click Next. d. In the resulting Import dialog box, browse to C:\JavaCourse\labs\OrderEntry\src. Make sure you select the src folder and not oe. Click OK to close and redisplay the Import dialog box. e. In the left pane, expand the src folder and click on the oe folder under it. You should see the list of .java files listed in the right pane. Click the Select All button to select all the .java files listed. Click Finish. Page 29
Introduction to Java Programming Exercises f. In the Package Explorer, expand the Order Entry project, the src folder and the oe package. Confirm that all the files have been imported. If any of your files have errors in them, Eclipse will mark them with an error symbol (small red box with a white X in it.) g. Fix all the errors if any. You can edit each .java file by double-clicking the name on the package Explorer view. Make sure there are no error markers around. h. Run the OrderEntry application by either selecting Run | Run As | Java Application menu item, or right-clicking the OrderEntry.java and choosing Run As | Java Application. View the output results in the Console view.
Note: To set the breakpoint on this line, double-click on the graded bar to the left of the line until a green dot appears on the margin. c. Set two more breakpoints, one on the line associating a DataMan customer object to the first order, and another on the line that is calling the method to show the second order details: order2.showOrder(). d. In the Package Explorer, select the OrderEntry.java, right-click, and select Debug As | Java Application. The dialog box Confirm Perspective Switch pops up. Click the checkbox Remember my decision and press Yes. e. Eclipse opens the Debug perspective with five open views: Debug, Variables, Editor (OrderEntry.java), Outline, and Console. The execution of the code stops at your first breakpoint, as indicated by the highlighted line in the Editor view. The highlighted line indicates the next line to be executed when you resume debugging. The Debug view shows the exact point in the main() method where execution stops (line X). The Variables view shows the current values of all the variables in scope. The Breakpoints view shows all the breakpoints in the current source file. (You need to click the Breakpoints tab.) The Console view displays the output results that are generated by the application (so far.) f. In the Debug view, press the Resume (F8) button on the toolbar (or select Run | Resume menu item.) The highlight in the Editor view advances and highlights the line with the next breakpoint that is detected in the code execution sequence. g. Click the Variables tab if the view is not visible, since it is sharing the same window as the Breakpoints view. h. Locate the order variable in the Variables view, expand it, and find the customer instance variable of the order. What is its current value? i. Click the Step Over (F6) button on the toolbar (or select Run | Step Over menu Page 30
Introduction to Java Programming Exercises item) to execute the order.setCustomer() method. Note that the changes to the order customer instance variable in the Variables view. Expand the customer instance variable to examine its contents. j. The highlighted line should now point to the line to display the first orders details; that is, order.showOrder(). Click the Step Into (F5) button on the toolbar (or select Run | Step Into menu item.) Eclipse displays the highlight on the first line of the showOrder() method of the Order class. k. Expand the this variable. Press F6 (Step Over) for a few lines noticing the results being displayed in the Variables view (and the Console view.) l. Then step out of the method by choosing the Run | Step Return (or press F7 (Step Return), or click the toolbar icon.) Eclipse returns control to the main() method on the next executable line following the call to the order.showOrder() method. m. Continue selecting the Run | Resume menu (F8 key or click the toolbar button) until the program is completed (the Debug view says <terminated>OrderEntry [JavaApplication].) n. Remove the breakpoints from the OrderEntry.java source, by doubleclicking each breakpoint entry (green dot) in the margin for each line with a breakpoint. o. Switch back to the Java perspective by selecting Window | Open Perspective | Java or clicking the Java Perspective button on the toolbar at the upper right corner of the Eclipse workbench.
Page 31
Exercise 10
Scenario
In this exercise, you add a couple of new classes as subclasses. The new classes that are added are Company and Individual and they inherit from the Customer class. Here is a UML class diagram to show the relationship between Customer, Company, and Individual. Each box represents a class. The name of the class appears at the top of each box. The middle section specifies the attributes in the class, where underlined attributes represent class variables. The lower section specifies the methods in the class. Notice the arrow on the line connecting Company and Individual to Customer. This is the UML notation for inheritance.
Goal
The goal of this exercise is to understand how to create subclasses in Java, and use polymorphism with inheritance through the Company and Individual subclasses of the Customer class. Refine the subclasses and override some methods and add some new attributes, making use of the Class Editor in Eclipse.
Your Assignment
Add two classes, Company and Individual, which inherit from Customer. The owners of Acme Video have decided to expand their business and begin selling to companies as well as individuals. Because companies have slightly different attributes than individuals, you Page 32
Introduction to Java Programming Exercises have decided to create subclasses for each of these types of items. Each of the items will have a few of their own methods and will override the toString() method of Customer. In Eclipse, continue to use your workspace and project (OrderEntry) from the previous exercise containing the files from the previous exercises,
d. Save the file. e. In the Outline view, right-click on the Company and select Source | Generate Getters and Setters f. In the Generate Getters and Setters dialog box, select both attributes and click OK. Notice that the getters and setters for the attributes are now in the source file. 2. Alter the Company constructor to have arguments. a. Add the following constructor with arguments:
public Company(String name, String address, String phone, String contact, int discount) { }
You can manually enter the constructor skeleton to the class, or use Eclipse to generate the constructor as described in step 2(c). Skip step 2(c) if you manually enter the code. b. Use the arguments to initialize the object state (including the superclass state). Hint: Use the super() syntax to pass values to an appropriate superclass constructor to initialize the superclass attributes. For example:
super(name, address, phone); this.contact = contact;
c. In the Outline view, right-click the class name Company. Select Source | Generate Constructor using Fields In the drop-down list box Select super constructor to invoke: select Customer(String, String, String). Make sure both instance variables are selected. In the drop-down list box Insertion point: select After 'discount' and press OK. Notice that the constructor is inserted at the specified place. 3. Override the toString() method for Company to return the contact name and discount. Include in the return value the superclass details, and format as follows:
<company info> (<contact>, <discount>%)
Page 33
Introduction to Java Programming Exercises a. You can manually enter the toString() method signature to the class, or use Eclipse to generate the toString() method signature as described in step 3(b). Skip step 3(b) if you manually enter the method. b. In the Outline view, right-click the class name Company. Select Source | Override/Implement Methods From the list, select toString() then click OK. Scroll down to the end of the source code in the Company class to view the results. c. Add the return statement and save the Company class file.
b. Create an Individual variable called customer6, and initialize it by using the constructor from the Individual class. c. Save the DataMan class file.
order.setCustomer(DataMan.customer2);
c. Hint: Use CTRL+F to show a search dialog box. Replace customer2 with customer5 (the company in DataMan.) d. Save (and compile) the code, and if successful, explain why. e. Now replace customer4 in order2.setCustomer() argument with customer6 (the individual in DataMan.) f. Save and run the OrderEntry application. What is displayed in the customer details for each order? g. Explain the results that you see.
If you manually add the square-bracketed text string before the return values of the toString() methods in the respective classes, then it would produce a result that concatenates [Company] to [Customer], and [Individual] to [Customer] for the subclasses of Customer. Therefore, the solution is to use inherited code called from the Customer class that dynamically determines the run-time object type name. You can determine the run-time object type name of any Java object by calling its getClass() method, which is inherited from the java.lang.Object class. The getClass() method returns java.lang.Class object reference, through which you call a getName() method returning a String containing the fully qualified run-time object name. For example, if you add this line to the Customer class:
String myClassName = this.getClass().getName();
the variable myClassName will contain a fully-qualified class name that includes the package name. The value that is stored in myClassName would be oe.Customer. To extract the class name only, you must strip off the package name and the dot that precedes the class name. This can be done by using a lastIndexOf() method in the String class to locate the position of the last dot in the package name, and extract the remaining text thereafter. To do this, add the getClassName() method to the Util class, and call it from the toString() method in the Customer class. 7. Open Util.java in the Code Editor. a. Add a public static String getClassName() method to determine the run-time object type name, and returns only the class name.
public static String getClassName(Object o) { String className = o.getClass().getName(); return className.substring(className.lastIndexOf('.') + 1); }
Page 35
Introduction to Java Programming Exercises b. Save (and compile) Util.java. Note that Eclipse automatically recompiles other classes that are dependent on code in Util.java. Eclipse has a built-in class dependency checking mechanism. 8. Open Customer.java in the Code Editor. a. Prefix a call to the Util.getClassName() method before the rest of the return value data in the toString() method as follows:
return "[" + Util.getClassName(this) + "] " + id + ;
b. Save (and compile) Customer.java. c. Run the OrderEntry application to view the results. d. In the above code, what does the this represent? And, why do you pass a parameter value this to the Util.getClassName() method? Explain why the compiler accepts the syntax that is used.
Page 36
Exercise 11
Goal
The goal of this exercise is to gain experience with Java array objects, and work with collection classes like the java.util.ArrayList class. You will also work with command-line arguments.
Your Assignment
Continue to use Eclipse to build on the application classes from the previous practices. You enhance the DataMan class to hold a method to construct an array of Customer objects, and then provide a method to find and return a Customer object for a given ID. The Order class is modified to contain a list of order items, requiring a method to add items into the list, and (optionally) another to remove the items.
with:
customers[0] = new Customer();
The example here assigns the customer object to the first element of the array. Repeat this for each customer<n> object references in the code. c. Create a static block that invokes the buildCustomers() method to create and initialize the array of customer objects, when the DataMan class is loaded. d. Save (and compile) the DataMan class. Fix any errors in the DataMan class, if any. Page 37
with:
System.out.println(DataMan.findCustomerById(1).toString());
b. Save and run the OrderEntry application to test your changes. c. Modify OrderEntry.java to accept a list of customer IDs on the command line. Write a loop in the main() method to process the arguments converting each from a String into an int, using the Integer.parseInt() method. Use each integer value in the DataMan.findCustomerById() method parameter to locate and display the customer details. d. Save and run the OrderEntry application to test your changes, with the following command line arguments: 1 3 4 99 6 Hint: Right-click on OrderEntry.java and select Run As | Run Configurations In the Run Configurations dialog box, select OrderEntry (under Java Application), and click on the Arguments tab on the right pane. Enter the list of numbers above in the Program arguments: entry field. Click Run.
Page 38
d. In the Order no-arg constructor, add a line to create the item list, as follows:
items = new ArrayList(10);
Use Eclipse to add the import statement for java.util.Iterator by rightclicking on the Editor window and selecting Source | Organize Imports or pressing CTRL+SHIFT+O. d. Save (and compile) the Order class, and fix any syntax errors. e. Test your changes to the OrderItem and Order classes by modifying the OrderEntry class to add products 101 and 102 to the first order object. For example, before the call to showOrder(), enter the bold lines below:
order.setCustomer(DataMan.findByCustomerId(5)); order.addOrderItem(101); order.addOrderItem(102); order.addOrderItem(101);
Page 40
order.showOrder();
f. Save and run the OrderEntry class. Confirm that your results are accurate. For example, check that the order total is reported as $15.00.
Page 41
Exercise 12
Goal
The goal of this exercise is to learn how to create and use an abstract class and how to create and use an interface.
Your Assignment
The OrderItem class currently only tracks a product as an integer. This is insufficient for the business, which must know the name, description, and retail price of each product. To meet this requirement you create an abstract class called Product, and define three concrete subclasses called Software, Hardware, and Manual. To support the business requirement of computing a sales tax on the hardware products, you create an interface called Taxable that is implemented by the Hardware subclass. To test your changes you must modify: DataMan to build a list of Product objects, and provide a method to find a product by its ID. Modify OrderItem to hold an object reference for a Product, and not an integer for ID of product, and also change Order to find a Product by its ID value. Save and run OrderEntry class to test the changes. 1. Add a public abstract class called Product to OrderEntry project. Note: Remember to check the abstract checkbox in the New Java Class dialog box. a. Declare the following attributes and their getter and getter methods. Hint: Use Eclipse to rapidly generate the getters and getters.
private private private private private static int nextProductId = 2000; int id; String name; String description; double retailPrice;
b. Define a public no-arg constructor that assigns the nextProductId to the ID of a new product object, before incrementing nextProductId. c. Override the toString() method (hint: use Eclipse to generate the skeleton) to return the ID, name, and retailPrice. Prefix with the class name by using getClassName(this) from the Util class. Also, format retailPrice with Util.toMoney(). d. Save (and compile) the Product class. e. Use Eclipse (its New Java Class dialog and the code editor) to create three concrete subclasses of the Product class, each with attributes and initial values that are listed in the table below (generate/add the appropriate getter and setter methods):
Subclass Software Attributes String license = "30 Day Trial";
Page 42
Hardware Manual
f. Modify the no-arg constructor for Software, Hardware, and Manual subclasses so that the new constructors accept three parameters (product name, description, and price). Use this code example for the Software class as a guide:
public Software(String name, String desc, double price) { setName(name); setDescription(desc); setRetailPrice(price); }
d. Save (and compile) your DataMan class. What is the compiled class name of the inner class? (Hint: Use Windows Explorer to check the bin directory.) 3. Create a method to populate the ProductMap map object with a product object. a. Create the method called buildProducts() as follows:
public static void buildProducts() { if (products != null) return; products = new ProductMap(); products.add(new Product()); }
b. Save (and compile) your code. Explain the compilation error that is listed for the line adding the Product to the products map. c. Fix the compilation error by adding concrete subclasses of the Product class. Replace the line of code products.add(new Product()) with the following text.
products.add(new products.add(new products.add(new products.add(new Hardware("SDRAM 128MB", null, 299.0)); Hardware("GP 800x600", null, 48.0)); Software("Spreadsheet-SSP/V2.0", null, 45.0)); Software("Word Processor-SWP/V4.5", null, 65.0));
Page 43
Note: The descriptions are null for the moment. This code will be replaced later to populate the products from data in a file by using Java I/O classes. d. Save (and compile) the DataMan class. Your compilation should work this time. e. In the static block of DataMan, call the buildProducts() method. f. Add the following method called findProductsById() to return a Product object matching a supplied ID.
public static Product findProductById(int id) { String key = Integer.toString(id); return (Product) products.get(key); }
Note: Because products is a HashMap, you simply find the product object by using its key; that is, the ID of the product. g. Save (and compile) the changes to the DataMan class. h. Test the DataMan code, and additional classes, by printing the product that is found by its ID. Add the following line to OrderEntry class at the end of main():
System.out.println("Product is: " + DataMan.findProductById(2001));
i. Save (and compile) and run the OrderEntry application to test the code.
Introduction to Java Programming Exercises 5. Make the following changes to the addOrderItem() method: a. Rename the parameter to be productId, and in the for loop, replace:
productFound = (item.getProduct() == product);
with:
productFound = (item.getProduct().getId() == productId);
Hint: Use Eclipse to help you rename every occurrence of the parameter name. Highlight the word product and press SHIFT+ALT+R. Change product to productId and press ENTER. b. In the else clause of the if statement, call findProductById() from DataMan by using the productId value. If a product object is found, then create the OrderItem using with the product object, otherwise do nothing. For example:
item = new OrderItem(product, 5.0); items.add(item);
becomes:
Product p = DataMan.findProductById(productId); if (p != null) { item = new OrderItem(p); items.add(item); }
6. Make the following changes to the removeOrderItem() method. a. Rename the parameter to be productId, and in the for loop replace the following line:
productFound = (item.getProduct() == product);
with:
productFound = (item.getProduct().getId() == productId);
b. First, save (and compile) the Product class, and then save (and compile) the changes to the Order class. 7. Test the changes that are made to your code supporting the Product class and its subclasses, by modifying OrderEntry class to use the new product ID values. a. Because the ID of Product objects (or its subclasses) start at 2000, edit the file OrderEntry.java, replacing the argument values in all the calls to the order.addOrderItem() method, as shown in the following table: Replace
101 102
With
2001 2002
b. Save (and compile) and run the OrderEntry application, and check the changes to the printed items. Check that the price calculations are still correct.
Introduction to Java Programming Exercises from the pop-up menu. Enter Taxable for the name and click Finish. b. In the Code Editor, add the following variable and method definitions to the interface:
double TAX_RATE = 0.10; double getTax(double amount);
Note: Remember, all variables are implicitly public static final, and methods are all implicitly public. The implementer of the interface should multiply the amount, such as a price, by the TAX_RATE and return the result as a double. c. Save (and compile) the interface. 9. Edit the Hardware class to implement the Taxable interface. a. Add the bold text to the class definition to implement the interface, as shown:
public class Hardware extends Product implements Taxable {
b. Save (and compile) the Hardware class and explain the error. c. Add the following method to complete the implementation of the interface.
public double getTax(double amount) { return amount * TAX_RATE; }
Note: Use Eclipse to create the method skeleton by putting the cursor on the underlined class name Hardware and selecting Add unimplemented methods on the pop-up menu. d. Save (and compile) the Hardware class. 10. Change the OrderItem class to obtain the tax for each item. a. Add a public double getTax() method to determine if the Product in the item is taxable. If the Product is taxable, then return the tax amount for the item total (use getItemTotal() method), otherwise return 0.0. b. Modify the toString() method to display the tax amount for the item, if and only if the product is taxable. Use the getTax() method that you created, and format the value with Util.toMoney(). c. To view the changes, save the OrderItem class and run the OrderEntry application. 11. Modify the Order class to display the tax, and order total including the tax. a. In the showOrder() method, add a local double variable called taxTotal initialized to 0.0 that accumulates the total tax for the order. b. Modify the for loop using the Iterator to call the getTax() method for each item, and add the value to taxTotal. Hint: To do this you will have to cast the return value of iter.next() to OrderItem. c. Add three System.out.println() statements after the loop, one to print the Page 46
Introduction to Java Programming Exercises taxTotal, the second to print the orderTotal including taxTotal, and the last, without parameter to print a blank line. Use the method Util.toMoney() to format the totals. d. To view the results, save the Order class and run the OrderEntry application.
Page 47
Exercise 13
Goal
The goal of this exercise is to learn how to create you own exception classes, throw an exception object by using your own class, and handle the exceptions.
Your Assignment
Our application does not appropriately handle situations when an invalid customer ID is applied to the DataMan.findCustomerById() method, or an invalid product ID is given to DataMan.findProductById() method. In both cases, a null value is returned. Your tasks are to: Create a user-defined (checked) exception called oe.NotFoundException. Modify DataMan.findCustomerById() to throw the exception when an invalid customer ID is provided. Modify the DataMan.findProductById() method to throw the exception if the given product ID is not valid, that is, not found.
b. Save (and compile) the DataMan class. Explain the error. c. Fix the error by modifying the method declaration to propagate the exception. d. Save (and compile) the DataMan class again. What errors do you get this time? Page 48
Introduction to Java Programming Exercises Explain the errors? e. Fix the compilation errors by handling the exceptions with a try-catch block in the OrderEntry class. For simplicity, use one try-catch block to handle all the calls to the DataMan.findCustomerById() methods. Alternatively, if desired, then handle each call in its own try-catch block.
try { // calls to findCustomerById() here } catch (NotFoundException ex) { // handle the exception here }
In the catch block, you can use the exceptions inherited methods to display error information. Use the following two ways to display error information: ex.getMessage() to return the error message text as a String ex.printStackTrace() to display the exception, message, and the stack trace
Note: Use Eclipse to help you generate the try-catch block by putting the cursor on the first statement and selecting Surround with try/catch on the pop-up menu. Move the rest of the statements in error inside the try-catch block. f. Save (and compile) and run the OrderEntry application. Test your code with the errors. 3. Now modify the findProductById() method in the DataMan class to throw NotFoundException when the supplied product ID is not found in the product map. a. The findProductById() method calls get(key) to find a product from the items HasMap. If get(key) returns a null, throw a NotFoundException by using the following error message, otherwise return the product object found:
"Product with id " + id + " is not found"
b. Modify the findProductById() declaration to propagate the exception. Use Eclipse to help you generate the required declaration by putting the cursor on the statement and selecting Add throws declaration on the pop-up menu. c. Save (and compile) DataMan, and explain the error reported. d. In the Order class, modify the addOrderItem() method to propagate the exception. Hint: Use Eclipse as in step (b) above. e. Save (and compile) the Order class, and explain why it compiles successfully. f. In OrderEntry.java, use a value of 9999 as the product ID, in the first call to order.addOrderItem(2001). Save (and compile) and run OrderEntry. Explain why the application terminates immediately after adding product 9999. g. In Order.java, remove throws NotFoundException from the end of the addOrderItem() method declaration. Write a try-catch block to handle the exception in this method. Use Eclipse as described in step 2(e). Hint: You will need to return from the method in the catch block, to ensure the itemTotal is not affected. Page 49
Introduction to Java Programming Exercises h. Save (and compile) the Order class, and run the OrderEntry application. Explain the difference in output results. i. In OrderEntry, replace product ID 9999 with 2001. Save (and compile) and run OrderEntry.
Page 50