0% found this document useful (0 votes)
9 views13 pages

Java Lab Worksheet

This document is a Java Lab worksheet for ITSE-2831: Object-Oriented Programming I, detailing various programming exercises and concepts in Java. It covers topics such as creating classes, using variables and operators, control structures, and building a gradebook application. The document includes step-by-step instructions for students to practice coding and understand object-oriented programming principles.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views13 pages

Java Lab Worksheet

This document is a Java Lab worksheet for ITSE-2831: Object-Oriented Programming I, detailing various programming exercises and concepts in Java. It covers topics such as creating classes, using variables and operators, control structures, and building a gradebook application. The document includes step-by-step instructions for students to practice coding and understand object-oriented programming principles.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

2023

JAVA Lab - Student


Worksheet
ITSE-2831: Object-Oriented Programming I
Enjoy JAVA by practicing. Java is an open source programming language with many
advantages and ease of use. Mobile, desktop and internet applications developers
enjoy the power and flexibility of JAVA with the pleasure of more packages
released every time.

Yoseph Abate
Information Technology and Scientific Computing, Addis Ababa Institute of
Technology, Addis Ababa University
11/1/2023
November 1, 2023 [JAVA LAB - STUDENT WORKSHEET]

Java Lab 0: Hello World


1. Navigate to the c:\java folder on your computer and create a folder to store the work you will do
in this class. The name of the folder should have no spaces and include part of your name or a nickname,
so you will recognize it as yours in future classes.

2. Go to Start Menu->Programs->Accessories and click on Notepad. This opens up Notepad which is the
editor we’ll be using to write your source code for now. Type this code below into Notepad:

public class HelloWorld {


public static void main(String[] args) {
[Link]("Hello, World!");
}
}

3. Save the file as [Link] in your home directory you created in step 1. Navigate to your
home directory and make sure that the file ends with .java. If it ends with .[Link] then delete
the .txt part.

4. Go to Start Menu->Programs->Accessories and click on Command Prompt or MSDOS Prompt. This is


the command prompt where you’ll be running the commands to compile and run your programs. At the
prompt, change to your home directory by typing the following command and pressing enter (where
yourname stands for the name you gave your folder):

cd c:\java\yourname

5. Compile the source code you wrote in Step 2 by now typing the following command at the prompt
and pressing enter:

javac [Link]

If running this command prints any errors to the command prompt window, then you either did not
copy the code in Step 2 correctly or you did not give the file the right name in Step 3. Make sure each is
copied precisely, character by character, with correct capitalization, and then try to recompile. If it
compiles successfully, it will print out nothing and simply show the next prompt.

6. Now run your program by executing the following command at the command prompt:

java HelloWorld

What do you see?

7. Now change the HelloWorld code so that it prints out “Goodbye, World!” instead. This should be
done by changing only one line of your program. Compile and run your program and see what it prints
out.
Information Technology and Scientific Computing, Addis Ababa Institute of Technology, Addis 2
Ababa University | Yoseph Abate
November 1, 2023 [JAVA LAB - STUDENT WORKSHEET]

8. The command [Link] prints out its argument and then starts a new line. Change
your program so it prints out “Hello, World!” on one line and then prints out “Goodbye, World!” on the
next line. Compile and run.

9. Take a look at the code you have written. It begins by creating a class called HelloWorld. We’ll
learn more about what a class is in later lectures. After the word HelloWorld in your code, there is an
opening brace { which denotes the beginning of the class. Then all the way at the bottom of your code
there is a closing brace } which denotes the end of the class.

10. Every Java file contains a class with the same name as the file. See how the class we created called
HelloWorld is in a file called [Link]? If we had a Java file named [Link], in
it you would find a class called Racecar. If we were to create a class called Student, we would create
it in a file called [Link].

11. Inside some classes, you’ll find what’s called the main method. The main method always begins
with the text:

public static void main(String[] args)

After this text you’ll see an opening brace { which denotes the beginning of the main method and the
second-to-last closing brace } denotes the end of the main method. We’ll see a lot of things in Java
begin and end with braces.

12. Add these lines to your main method:

String name = "AITI";


[Link]("Hello,");
[Link](name);
[Link]("How are you today?");

Compile and run. How does [Link] differ from [Link]?

11. Change the text "AITI" to your name (for example, "Mark") and compile and run your code again.
How has the output changed?

12. Change the line

[Link](name)

to the line

[Link]("name");

Why are the outputs different?

Information Technology and Scientific Computing, Addis Ababa Institute of Technology, Addis 3
Ababa University | Yoseph Abate
November 1, 2023 [JAVA LAB - STUDENT WORKSHEET]

Java Lab 1: Variables & Operators


1. Correct the following statements:

a) boolean isGood = 1;
b) char firstLetter = p;
c) int 2way = 89;
d) String name = Manish;
e) int player score = 8976543;
f) Double $class = 4.5;
g) int _parents = 20.5;
h) string name = "Greg";

2. Without doing any programming, what do you think the following main method prints to the screen?

public static void main(String[] args) {


int x = 5;
int y = 3;
int z = x + x*y - y;
[Link]("The value of z is " + z);

int w = ++x + y + y--;


[Link]("The value of w is " + w);
[Link]("The value of x is now " + x);
[Link]("The value of y is now " + y);

boolean a = true;
boolean b = false;
boolean c = ((a && (!(x > y))) && (a || y >x ));
[Link]("c is " + c);
}

3. Create a new Java file with a class called UsingOperators and copy the above main method into
it. (Can you figure out what the name of the of the Java file must be? Hint: see step 10 of Lab 0.) Compile
and run. Does the output match what you thought?

4. Create a new Java class called TempConverter. Add a main method to TempConverter that
declares and initializes a variable to store the temperature in Celsius. Your temperature variable should
be store numbers with decimal places.

5. In the main method, compute the temperature in Fahrenheit according to the following formula and
print it to the screen: Fahrenheit = (9 ÷ 5) × Celsius + 32

6. Set the Celsius variable to 100 and compile and run TempConverter. The correct output is 212.0. If
your output was 132, you probably used integer division somewhere by mistake.

Information Technology and Scientific Computing, Addis Ababa Institute of Technology, Addis 4
Ababa University | Yoseph Abate
November 1, 2023 [JAVA LAB - STUDENT WORKSHEET]

Java Lab 2: Control Structures


1. Create a new class called UsingControlStructures.

2. Add a main method to the class, and in the main method declare and initialize a variable to represent
a person's age.

3. In the main method, write an if-else construct to print out "You are old enough to drive" if the
person is old enough to drive and "You are not old enough to drive" if the person is too young.

4. Write a for loop that prints out all the odd numbers from 100 to 0 in decreasing order.

5. Do Step 4 with a while loop instead of a for loop.

Java Lab 3: Gradebook – Part 1


1. Create a new class called Gradebook.

2. Add a main method of Gradebook. In the main method, declare and initialize an array of
doubles to store the grades of a student.

3. Write a loop to print out all the grades in the array. Make sure that your printout is readable with
spaces or new lines between each grade.

4. Write a new loop to find the sum of all the grades in the array.

5. Divide by the sum by the number of grades in the array to find the student's average.

6. Print a message to the user showing the average grade. If the average grade is 85.4, the output should
be "Your average grade is 85.4".

7. Your program should work if there are 4 grades in the array or 400 grades in the array. That is, you
should be able to change the number of grades in the initialized array and compile, and it should run
without any problems. Try it out. If it doesn't, figure out how to rewrite your program so it does.

8. (Optional) Add code to print out the letter grade the student earned based on the average grade. An
average in the 90's is an A, in the 80's is a B, 70's is a C, 60's is a D, and anything lower is an F.

Information Technology and Scientific Computing, Addis Ababa Institute of Technology, Addis 5
Ababa University | Yoseph Abate
November 1, 2023 [JAVA LAB - STUDENT WORKSHEET]

Java Lab 4: Gradebook 2


1. Add a method to Gradebook called printGrades that accepts an array of doubles as an
argument and prints out all the grades in the array. Replace the loop in the main method that prints out
all the grades with a call to the printGrades method. Compile and run.

2. Add a method to Gradebook called averageGrade that takes an array of doubles as an argument
and returns the average grade. Replace the loop and calculations in the main method that determines
the average grade with a call to the averageGrade method. Your main method should still print out
the user's average grade and the letter grade the user earned. Compile and run.

3. Change the main method of Gradebook so that it converts its String arguments into doubles
and initializes the grades in the array to those numbers. Use the method [Link] to
convert a String containing a double to an actual double. Compile and run and provide arguments
at the command line, like this:

java Gradebook 82.4 72.5 90 96.8 86.1

4. (Optional) Use the Scanner sc = new Scanner([Link])to read from the keyboard. Try
modifying your code so that instead of just taking the array of grades from the main method, the
program asks the user to enter the grades.

5. (Optional) Change the main method so that after asking the user to enter the grades, it prints out a
menu of two options for them: 1) print out all the grades or 2) find the average grade. It should ask the
user to enter the number of their choice and do what the user chooses.

Java Lab 5: GradebookOO – Part 1


1. In labs 3 and 4, we built a procedural gradebook program. In labs 5, 6 and 7, we're going to write a
new object-oriented gradebook program. Please look back as your Gradebook class as needed for help
in writing your new object-oriented gradebook.

2. Create a new class called GradebookOO (that's two O's for Object-Oriented). The class should have
a single field which is an array of doubles called grades. This class will have no main method.
Compile. Why can't you run this class?

3. Write two constructors for GradebookOO. This first should take no arguments and initialize the
grades field to an array of size zero. The second should take an argument that is an array of doubles
and assign that array to the field. Compile.

Information Technology and Scientific Computing, Addis Ababa Institute of Technology, Addis 6
Ababa University | Yoseph Abate
November 1, 2023 [JAVA LAB - STUDENT WORKSHEET]

4. Add a method to GradebookOO named printGrades that takes no arguments and prints out all
the grades in the grades field. Compile.

5. Add a method to GradebookOO named averageGrade that takes no arguments and returns the
average grade in the grades field. Compile.

6. Create a new class called GBProgram. Add a main method to GBProgram which instantiates a
Gradebook with an array of grades, prints out all the grades with a call to the printGrades
method, and finds the average grade with the averageGrade method. Compile and run.

7. (Optional) Use Use the Scanner sc = new Scanner([Link]) in the main method of
GBProgram to allow the user to enter in the grades.

8. (Optional) Print out a menu to the user, as described in Step 4 of the previous lab, that allows the user
to select whether they would like to print out all the grades or find the average grade.

Java Lab 6: GradebookOO – Part 2


1. Add appropriate access modifiers to all your fields and methods in GradebookOO and GBProgram.
Compile.

2. Add a method to GradebookOO called addGrade which accepts a double argument and adds it
to the array of grades. This is difficult. Two things you should note:

• arrays always have the same length, so you can't increase it the size of it
• arrays are objects not primitives, so variables of type array hold references to arrays
Here are the steps your addGrade method should follow:

a) When addGrade is called, the grades field holds a reference to an array of grades:

grades —————————————————————> [83.2, 97.4, 76.8]

b) Create a new array, maybe call it temp, that is a size 1 bigger than grades:

grades —————————————————————> [83.2, 97.4, 76.8]

temp —————————————————————> [ , , , ]

c) Copy over all the elements from grades into temp:

grades —————————————————————> [83.2, 97.4, 76.8]

temp —————————————————————> [83.2, 97.4, 76.8, ]

Information Technology and Scientific Computing, Addis Ababa Institute of Technology, Addis 7
Ababa University | Yoseph Abate
November 1, 2023 [JAVA LAB - STUDENT WORKSHEET]

d) Add the new grade into the last slot of temp:

grades —————————————————————> [83.2, 97.4, 76.8]

temp —————————————————————> [83.2, 97.4, 76.8, 90.5]

e) Change grades so it points to the temp array:

grades —————————————————————> [83.2, 97.4, 76.8, 90.5]

3. Delete the GradebookOO constructor that takes an array of doubles as an argument. And change
the main method of GBProgram so that it instantiates an empty GradebookOO and adds the grades
one-by-one to it with the addGrade method. Compile and run.

4. (Optional) If you have not done so in the past few labs, use EasyReader to read the grades from
the user and print out a menu to the user. See Steps 3 and 4 of Lab 4 for more details.

5. (Optional) Add a method deleteGrade to GradebookOO which accepts a grade as an argument


and removes it from the array if it's there. This is tricky. Compile and run.

Java Lab 7: GradebookOO – Part 3


1. Change the field in the GradebookOO program from an array to an ArrayList.

2. Rewrite all the methods to use the ArrayList instead of the array. Make sure you use an
Iterator for all the iterations through the ArrayList. Compile.

3. Do you have to make any changes to GBProgram so that it will compile and run successfully? Why or
why not?

4. Run GBProgram.

Java Lab 8: Racecar – Part 1


1. Create a new class called Racecar. Add two fields to Racecar: a field of type String to store the
name of the car and a field of type Color (from [Link]) to store the color of the car. Each
car can have a different name and color. Should the fields be static or non-static? Compile.

Information Technology and Scientific Computing, Addis Ababa Institute of Technology, Addis 8
Ababa University | Yoseph Abate
November 1, 2023 [JAVA LAB - STUDENT WORKSHEET]

2. Every one of our racecars will have the same top speed. Add a private constant of type double to
the Racecar class to store the top speed and initialize it to any number you want. Should this field be
static or non-static? Compile.

3. Add a constructor to Racecar which accepts a name and color argument and assigns the arguments
to the name and color fields of the class. Compile.

4. Add a method called getName that returns the name of the car and a method called getColor
that returns the color of the car. Should these methods be static or non-static? Compile.

5. Add a method to Racecar called race which accepts two Racecars as arguments, simulates a
race between the two, and returns the car that one the race, or return null if the race is a tie. The
method should calculate a random speed for each car between 0 and the top speed. The car with the
higher speed wins the race, but if they both have the same speed they tie. The method random in
[Link] returns a random double between 0 and 1. If you multiply this random number by
the top speed, the product will be a random number between 0 and the top speed. Should this method
be static or non-static? Compile.

6. Add a main method to Racecar which creates two Racecars, races them against one another,
and prints out the winner's name. When instantiating the Racecar objects, pass one of the static fields
of the Color class (like RED or BLUE) as the color argument to the constructor. Should the main
method be static or non-static? Compile and run.

7. (Optional) Instead of having a constant top speed for all racecars, change the Racecar class so every
car has its own top speed.

8. (Optional) Program a better racing simulation in the race method.

Java Lab 9: Racecar – Part 2


1. Create a new package called race. Move [Link] into the package folder and add a
package statement to Racecar to declare it a member of that package. Compile and run.

Java Lab 10: Students – Part 1


1. Create a package called students. All the classes you create in this and the next lab will be created
in this package. You should compile after each of the following steps.

Information Technology and Scientific Computing, Addis Ababa Institute of Technology, Addis 9
Ababa University | Yoseph Abate
November 1, 2023 [JAVA LAB - STUDENT WORKSHEET]

2. Create a class called Student, which should have two properties, a name and a year and methods to
get the name and get the year of the student. Initialize these properties to arguments passed into the
constructor.

3. Create a subclass of Student called Undergrad. The Undergrad constructor should accept
name and year arguments. Add a method to Undergrad called description which returns a
String containing the name of the undergrad, then a space, then a capital 'U', then a space, and then
the year of the undergrad. For example, the description method of an Undergrad instance with
the name "Michael" and the year 2006, should return the String "Michael U 2006".

4. Create a subclass of Student called Grad. The Grad constructor should accept only the name of
the Grad as an argument, and it should always initialize the Grad's year to 5. Add a description
method to Grad which returns a String containing the name of the Grad, followed by a space and
then the letter 'G'. The description method of a Grad named "Jennifer" should return the String
"Jennifer G".

5. Create a subclass of Undergrad called Intern. In addition to the name and year properties,
Intern should have a wage and a number of hours that are initialized in the constructor. Add a
getPay method to Intern which returns the wage times the number of hours. Add a description
method to Intern which returns a String containing the result of calling Undergrad's description
method followed by the return value of the getPay method. The description method of an
Undergrad named "Elizabeth" whose year is 2005 and worked 20 hours at $10.32/hour, should return
the String "Elizabeth U 2005 206.4".

6. Create a subclass of Grad called ResearchAssistant. ResearchAssistant has a salary that


is initialized in the constructor and a getPay method that returns the salary. Add a description
method to ResearchAssistant which returns a String containing the result of Grad's
description method, followed by the result of getPay. The description method of a
ResearchAssistant with the name "Greg" and a $2000.00 salary would return the String
"Greg G 2000.0".

7. Create a class called StudentTest that has a main method. Use the main method to test the class
hierarchy you just built. Create some instances of Undergrad, Grad, Intern, and Research
Assistant. Print out the result of their description methods. Compile and run.

Java Lab 11: Students – Part 2

Information Technology and Scientific Computing, Addis Ababa Institute of Technology, Addis 10
Ababa University | Yoseph Abate
November 1, 2023 [JAVA LAB - STUDENT WORKSHEET]

1. A university tells you they want to use the student objects that you built in their new software
system. For the rest of the lab, you will be improving your student objects to meet the needs of the
university.

2. The university wants to be able to easily print out descriptions of every student. In the main method
of StudentTest, add the instances of Undergrad, Grad, Intern, and Research Assistant
that you created in the last lab to an ArrayList. Iterate through the ArrayList, cast each element
to a Student and print out the return value of the description method of each. Try to compile.
The call to the description method should generate a "cannot resolve symbol" error. Why?

3. Fix the error by adding a dummy description method to Student which returns null. Compile
and run.

4. The university tells you that they do not want the Student class to be instantiated, and they want to
guarantee that every subclass of Student implements the description method. Change the
Student class so it meets these two requirements. Compile and run.

5. The university wants to be able to use your objects in their student payroll system. They need to be
able to easily print out the pay of all the interns and research assistants. In the main method of
StudentTest, create an ArrayList with just Interns and ResearchAssistants. Is it
possible to iterate through the ArrayList, cast each to a Student, and call getPay on each?

5. Create an Employee interface with a single method, getPay. Have Intern and
ResearchAssistant implement that interface. Now iterate through your list of employees and
print out the pay of each.

6. (Optional) Write a program that the university can use to manage its students. The program can do
whatever you want, so long as you think the university would find it useful. For example, it could print
out a menu of options and allow the user to create all different types of students and print out the
description of students and the pay of all the student employees. You can add new properties to your
students or create new types of students if you wish. Be creative.

Java Lab 12: MyStore – Part 1


1. In the next two labs you will write software to run a store. The store can sell any products you want –
it's up to you. Begin by creating a new package called store. All the classes you create in the next two
labs will go in this package.

2. Create a new class called Product. This will represent a product sold in your store. Add fields to the
Product class to store the name and price of the product. These fields should be assigned to values

Information Technology and Scientific Computing, Addis Ababa Institute of Technology, Addis 11
Ababa University | Yoseph Abate
November 1, 2023 [JAVA LAB - STUDENT WORKSHEET]

passed as arguments into the constructor. Add methods to Product to return the name and price of
the product. Compile.

3. Change the Product constructor so it throws a NullPointerException is the name is null


and an IllegalArgumentException if the price is negative. Compile.

4. Create a new class called MyStore. MyStore should have a list field to contain all the products in
your store. Initialize the field to an empty list in the MyStore constructor. Compile.

5. Add a method to MyStore called readProducts. This method should accept no arguments and
return nothing. In the readProducts method, print messages to the console that ask the user to
enter in a product name and price, and then read the name and price with EasyReader. Instantiate a
Product with that name and price and add that product to the list of products. Compile.

6. Add a main method to MyStore. In the main method, instantiate a MyStore object and call the
readProducts method on that object. Compile and run.

7. What happens when you type a word instead of a number when your program asks you to type in a
price?

8. Write a new checked exception called ProductException. Make sure you write both types of
exception constructors. Compile.

9. Change the readProducts method in MyStore so that it catches the


NumberFormatException thrown by EasyReader and throws a ProductException inside
the catch clause. Change the main method in MyStore so that it catches a ProductException and prints
out an appropriate message to the user. Compile and run.

Java Lab 13: MyStore – Part 2


1. Using Notepad, start a new text file and save it as [Link] to the parent directory of the
store package. On each line of the file, write the name of a product you want your store to sell, a '$'
symbol, and then the price of the product. For example, if you want your store to sell a computer for
1500.45 and a soccer ball for 37.23, make sure your [Link] file has the following two lines:

computer$1500.45
soccer ball$37.23

Your [Link] file should list at least 10 products.

2. Add a method to MyStore called readProductsFromFile. The method should accept one
argument, a String containing a filename. Open the file with that filename using a FileReader and
Information Technology and Scientific Computing, Addis Ababa Institute of Technology, Addis 12
Ababa University | Yoseph Abate
November 1, 2023 [JAVA LAB - STUDENT WORKSHEET]

wrap the FileReader in a BufferedReader to read the file line-by-line. For each line of the file,
create a StringTokenizer that will split the line at '$' characters. Use the tokenizer to get name and
price of the product. Then convert the price from a String to a number and instantiate a Product
object with that name and price. Finally, add that product to the store's list of products. Catch any
IOExceptions thrown by the above operations and throw a ProductException in the catch
clause. Compile.

3. In the main method of MyStore, call the readProductsFromFile method on the store
instance you created and pass the String "[Link]" as an argument to the method.
Compile and run.

4. (Optional) Write an interface called ProductSource which has a single method, getProducts
that accepts no arguments and returns a list of products. Write two classes that implement
ProductSource. The first, called KeyboardSource, should have an empty constructor. Its
getProducts method should ask the user to type in some products the same way your
readProducts method does, and it should return a list of products that the user typed in. The second
class, FileSource, should accept a filename argument, and its getProducts method should read
products from the file like the readProductsFromFile method and return a list of products in the
file. Compile.

7. (Optional) Replace the readProducts and readProductsFromFile method with a single


method loadProducts method that accepts a ProductSource argument. The loadProducts
method should call getProducts on the ProductSource and add the products returned by the
ProductSource to the store's list of products. Hint: using the addAll method provided by lists
should make your life easier. Compile.

8. (Optional) Change the main method of MyStore to use KeyboardSource, FileSource, and
the loadProducts method instead of the readProducts and readProductsFromFile
methods. Why is this a better design?

Information Technology and Scientific Computing, Addis Ababa Institute of Technology, Addis 13
Ababa University | Yoseph Abate

You might also like