Lab 231 Final-Modified
Lab 231 Final-Modified
Laboratory Workbook
Comp231
Advanced Programming
Prepared by:
Approved by:
Computer Science Department
2017/2018
Computer Science Department (Laboratory Work Book for Comp231) 2
Introduction
The aim of this lab manual is to help students of the “advanced programming” course to
understand and apply a variety of object oriented programming and design concepts. Every lab
session is provided with lab objectives, a brief discussion about the experiment’s topics or
concepts that strength the student understanding to the lab material; a Java language syntax for
the commands or statements that will be used; and some exercises that allow the student to
completely understand the topic. The exercises in this manual are carefully prepared, studied
and revised by several members of the academic staff in the computer science department at
Birzeit University.
The lab manual starts explaining Object Oriented Programming using Java language from
scratch. It allows the students to learn about the structure of the Java programs and provides
students with sufficient knowledge to understand object-oriented programming concepts using
Java language. Further, the manual covers all object-oriented programming concepts such as
the use of objects and classes, inheritance, polymorphism, abstract classes and interfaces. In
addition, students will learn how to make a graphical user interface programs and event driven
programming. Finally, this manual gives students a complete understanding to the above topics
in which they will be able to proceed with the advanced courses during their study.
Computer Science Department (Laboratory Work Book for Comp231) 3
Table of Contents
To check that you have installed the JDK, run command line interface (cmd). For example, in
windows 10 you can use Cortana to search for and lunch the command prompt, Inside Cortana’s
search field, enter command or cmd. Then click or tab on he command prompt result.
Then type the following command:
java –version
This command will show you the version of the JDK you have installed (Figure1.2),:.
2- After completing your source code, open cmd (run à cmd) then you have to compile it
using the following command (figure 1.4):
3- javac ClassName.java
4- If no compilation errors appear, this means that you can run your program using the
following command (figure 1.5):
java ClassName
The syntax new Scanner (System.in) creates an object of the Scanner type. The syntax
Scanner input declares that input is a variable whose type is Scanner. The whole line
An object has methods that can be invoked as functions in c programming language. When
someone invokes an object’s method, he/she is asking the object to perform a certain task. For
example, you can invoke the nextDouble() method to read a double value as follows:
double radius = input.nextDouble();
Exercises
1. Write a java application using notepad that prints your name, id, course name
(Which is “advanced programming comp231”) and your instructor’s name with the section
number next to it. Then from console use JDK to compile and run the program.
2. Use notepad to write a java application that asks the user to enter 10 numbers and calculates
their average then displays the result. From console use JDK to compile and run the program.
Computer Science Department (Laboratory Work Book for Comp231) 10
2. Multiple Selections
switch (expression) {
case constant-expression:
Statement(s);
break;
default:
Statement(s);
break;
}
2. do-while loop:
do {
Statement(s);
} while (expression);
3. for loop :
for (initial-action; expression ;action-after-each-iteration) {
Statement(s);
}
Computer Science Department (Laboratory Work Book for Comp231) 12
Eclipse IDE
This lab will introduce you to Eclipse, a full-featured and very versatile Integrated
Development Environment(IDE). During the assignments and labs in this course you will
be using Eclipse extensively to develop Java programs.
You can download it from the following link:
https://eclipse.org/mars/
Figure2.1 ( workspace )
If you want to change it, click brows and select new place for it as in figure 2.2. The new
place that we have chosen is myWorkspace, then click ok.
Computer Science Department (Laboratory Work Book for Comp231) 13
3- To create a new class, right click on your project name (HelloWorld), then New Class
4- After creating your class, you are ready to write your code inside it. Later on, to run your
program, right-click on your class that contains the main method
Choose run then choose java application as in figure 2.4
Methods:
Syntax
[modifiers] data-type method-name ([parameter-declaration]) {…}
Calling a Method
When creating a method, you give a definition of what the method is supposed to do. To
use a method, you have to call or invoke it.
There are two ways to call a method; the choice is based on whether the method returns a
value or not:
1. If the method returns a value, a call to the method is usually treated as a value.
For example:
data-type variable-name = method-name( passed-arguments);
Calls method-name (passed-arguments) and assigns the result of the method
to the variable variable-name.
Another example of a call that is treated as a return-value is:
System.out.println(method-name(passed-arguments));
Which prints the return value of the method call method-name( passed-
arguments)
2. If the method returns void it should be called using a statement. For example,
the method println returns void. The following call is a statement:
System.out.println("Welcome to Java!");
Computer Science Department (Laboratory Work Book for Comp231) 16
Exercises
1. The body mass index (BMI) is a ratio of person’s weight and height. The index can be used to
determine if a weight is unhealthy for certain height. Here is the formula:
𝑤𝑒𝑖𝑔ℎ𝑡(𝑝𝑜𝑢𝑛𝑑𝑠) × 703
𝐵𝑀𝐼 =
ℎ𝑒𝑖𝑔ℎ𝑡 ! (𝑖𝑛𝑐ℎ𝑒𝑠)
Write a java program that reads values for weight in kilograms and height in centimetres and
prints out the BMI.
Hence, the above formula uses pounds and inches, so you have to include the following two
methods to do the needed conversion.
- Converts from Kilograms to Pounds:
Your program should also print on screen an interpretation of the BMI. Use the following
scale.
BMI Interpretation
2. Write a java application that will determine the salary for each of several employees. The
company pays “straight-time” for the first 40 hours, if the employee worked more than 40
hours, we consider the extra hours as overtime and the employee gets 50% extra for each
overtime hour. You are given a list of employees of the company, each employee has a number
of worked hours and hourly rate.
Your application should input this information (worked hours and hourly rate) for each
employee then it should determine and display the employee’s salary.
The program will stop if we enter -1.
Output may appear as follow:
3. A prime number is a number that has no positive divisors other than 1 and itself. Your
program should stop if we entered a number less than 2. Write a java program that finds the
prime numbers between 2 and 500 using the following method signature, your program will
stop if the user enter a number less than 2
Now improve your program to allow the user to enter a number then check if it is prime or
not.
Computer Science Department (Laboratory Work Book for Comp231) 18
Lab 3: Methods
Objectives
• To practice more about methods (create, invoke and pass arguments).
• To determine the scope of variables.
Exercises
1. The exponential ex can be calculated using the following formula:
𝑥 𝑥 ! 𝑥# 𝑥$ 𝑥%
𝑒" = 1 + + + + +
1! 2! 3! 4! 5!
The factorial of non-negative integer n is written n! And is defined as follows:
𝑛! = 𝑛 ∙ (𝑛 − 1). (𝑛 − 2). ⋯ .1
𝑛! = 1 (𝑖𝑓 𝑛 = 0)
Write a java program that contains two methods factorial and exp according to the
formulas that we mentioned above. The main task for this program is to ask the user to
enter a number and calculate its exponential then display the result.
Ø Note that exp method will call factorial method.
2. An integer number is said to be perfect number if the sum of its factors including 1 (but
not the number itself) is equal to the number itself.
For example 6 is perfect because 6 = 1 + 2 + 3.
3. Write a java method that accepts a binary number and converts it to decimal then display
the result. For Example:
(110)2 = (6)10
(22 *1)+ (21 *1) + (20*0) = 6
Additional task: write a method that accepts a decimal and converts it to binary.
Computer Science Department (Laboratory Work Book for Comp231) 19
Syntax
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference.
Exercises
1. A building with n apartments is to be represented in an array.
Ø Write an application that reads the number of apartments and use it as the size of
the array. The apartment number will serve as the index of the array.
The values in the array represent the number of people who live in the apartment.
For example: a building which has 4 apartments can be represented as follows :
Building:
2 3
4 2
6
1
2
0
Now, create a building (array on integers) as above then print the following
information:
1- Number of people in the building.
2- The average number of people per apartment
3- The number of apartments with above-average occupancy, and the
number with below-average occupancy.
Computer Science Department (Laboratory Work Book for Comp231) 21
Ø Modify the above application to read the number of people in the apartment and
their ages. Still, the apartment number serves as an index into an array of
apartments. But, the values of the apartment represent the ages of people who live
in the apartment instead of their number. Add a new method averageAges() to
find the average age of the building residents.
Hint: use 2 dimensional arrays as in the following figure and build it at run time.
Building:
3 30 25
2 45 25 21 15
1 50 40 20 18 15 10
0 60 65
2. Write a java program that has a method called linearSearch as in the following signature
which accepts an array of integers and an integer number to search for it inside the array.
If the number is found in the array, it will return its index, else if the number is not found
it will return -1.
public static int linearSearch( int [ ] myArray , int number)
Computer Science Department (Laboratory Work Book for Comp231) 22
3. Write an application that creates a one dimensional array of 5 Students. Then write a test
program to print the student details in the list.
public Student() {
}
Objectives
• To understand objects and classes, and the differences between them.
• To use UML (Unified Modeling Language) graphical notations to describe classes and
objects.
• To understand and apply the role of constructors.
The following UML represents Student class that we have seen in our previous lab:
Computer Science Department (Laboratory Work Book for Comp231) 24
Exercises
1. Create an Employee class according to the following UML.
Write a driver class that creates an array of 4 Employees then passes the array to a method
named largestSalary which will return the employee object with the largest salary.
Computer Science Department (Laboratory Work Book for Comp231) 25
2. Develop MyArray class. The internal representation of this class is an array of integers.
The following methods should be included in the class to deal with the array:
MyArray(int []) // Constructor
min( ): int // returns the minimum element in the array
max( ): int // returns the maximum element in the array
average( ):double // returns the average of the elements
printArray( ):void // prints the elements of the array
getSize( ):int //returns the length of the array
Develop a driver class to create objects (array) from the created class and test their
behaviors.
Computer Science Department (Laboratory Work Book for Comp231) 27
Create a class City according to the above UML class diagram, then create an array of
cities which contains 4 city objects. Then pass the array to a method named
belowAverage that accepts an array of City objects and an integer which represents
certain temperature. This method shall print all information about all cities that have a
temperature below the given temperature.
Lab 6: Strings
Objectives
1. To be able to create and manipulate non-modifiable (immutable) string objects of class
String.
2. To be able to create and manipulate modifiable string objects of class StringBuffer/
StringBuilder class.
Syntax
Strings are Objects in Java and Strings can be declared and created using one of the following:
String stringName = new String(“String Litral”);
String stringName = new String(char [] arrayOfCharacters);
String stringName = “String Litral”;
Method Description
charAt() Returns the character at the specific index from this string.
trim() Returns a new string with whitespaces characters trimmed on both sides .
Computer Science Department (Laboratory Work Book for Comp231) 29
Method Description
equalsIgnoreCase(s1) Returns true if this string is equal to string s1; it is case insensitive.
indicate whether this string is greater than, equal or less than s1.
indexOf(ch, fromIndex) Returns the index of the first occurrence of ch after from Index in
indexOf(s) Returns the index of the first occurrence of string s in this string.
indexOf(s, fromIndex) Returns the index of the first occurrence of string s in this string
lastIndexOf(s, fromIndex) Returns the index of the last occurrence of ch in before fromIndex
lastIndexOf(s) Returns the index of the last occurrence of string s in this string.
lastIndexOf(s, fromIndex) Returns the index of the last occurrence of string s in this string
Exercises
1. You will create a class named MyString that will perform different processing on Strings
that are sent to it. All of the methods you create will be static, and the class should work in
a similar manner to the Math class. Only the four methods listed below should be public.
1) Create a method reverseString that receives a String and returns a String that is the
exact reversal of the characters in the first String.
2) Create a method isPalindrome that receives a String and returns a boolean value of true
if the String is a Palindrome and false if it is not. A word is a palindrome if it reads the
same forwards and backwards. For example, the word level is a palindrome.
The idea of a palindrome can be extended to phrases or sentences if we ignore details
like punctuation, so you need to create a method that cleans the sentence from
punctuation and spaces, then convert the sentence to lower or upper case after that we
can use the method isPalindrome with the new sentence. Here are two familiar
examples:
Madam, I'm Adam à madamimadam
A man, a plan, a canal: Panama à amanaplanacanalpanama
3) Create a method ShortHnaded that receives a String and returns the String converted
into shorthand. The simplified shorthand form of a string is defined as follows:
1. Replace these four words: "and" with "&", "to" with "2", "you" with "U",
and "for" with "4".
2. Remove all vowels ('a', 'e', 'i', 'o', 'u', whether lowercase or uppercase), do
not remove ‘u’ and ‘I’ if they did not occurred in a word.
Computer Science Department (Laboratory Work Book for Comp231) 31
2. Design a java program that we can use to encrypt a sentence by using the following
methods respectively:
As objects do not exist by themselves but are instances of a class, a class can inherit the features
of another class and add its own modifications. (This could mean restrictions or additions to its
functionality). Inheritance aids in the reuse of code.
Classes can have 'Children' that is, one class can be created out of another class. The original or
parent class is known as the SuperClass (or base class). The child class is known as the SubClass
(or derived class).
A SubClass inherits all the attributes and behaviors of the SuperClass, and may have additional
attributes and behaviors.
Syntax
In Java inheritance is represented using extends keyword as follows:
[modifiers] super-class-name { //Data members and methods …}
Computer Science Department (Laboratory Work Book for Comp231) 33
Exercises
1. Design a class named Account that represents a bank account and contains:
• An int data field named id for the account (default 0).
• A double data field named balance for the account (default 0).
• A Date data field named dateCreated that stores the date when the account was created.
• Two constructors:
1) No-arg constructor that creates a default account and initialize the dateCreated.
2) Constructor with arguments that accepts id and balance.
• The setter and getter methods for id and balance.
• Getter for dateCreated.
• A method named withdraw that withdraws a specified amount from the account.
• A method named deposit that deposits a specified amount to the account.
• toString method that returns id, balance and date created.
Create two subclasses for Checking and Saving accounts from Account class. A Checking
account has an overdraft limit equals to 1000, but a savings account cannot be overdrawn.
Step 1: Draw the UML diagram for the classes then implement the classes.
Step 2: Implement classes using eclipse.
Step3: Write a test program that creates different objects of Saving account, and Checking
account, and invokes their toString() methods and to call withdraw and deposit method.
Computer Science Department (Laboratory Work Book for Comp231) 34
Theory
Abstract classes are used to declare common characteristics of subclasses. An abstract class
cannot be instantiated. It can only be used as a superclass for other classes that extend the abstract
class. Abstract classes are declared with the abstract keyword. Abstract classes are used to provide
a template or design for concrete subclasses down the inheritance tree.
An interface defines one or more constant identifiers and abstract methods. A separate class
implements the interface class and provides the definition of the abstract methods. Interfaces are
used as a design technique to help organize properties (identifiers) and behaviors (methods) the
implementing classes may assume.
Computer Science Department (Laboratory Work Book for Comp231) 35
Syntax
Abstract Class
[modifier] abstract class Class-Name {
/** Body of the class */
}
Abstract Method
[modifier] abstract data-type method-name([parameters-declarations]) {…}
Interface
[modifier] interface InterfaceName {
/** Constant declarations */
/** Method signatures */
}
There are famous interface classes that you will use, such as Comparable which will help you in
comparing objects by implementing the compareTo method and Cloneable which will help you
cloning objects by implementing the clone method.
Computer Science Department (Laboratory Work Book for Comp231) 36
Exercises
1. Create the classes in the following inheritance hierarchy. An Employee should have a first
name, last name and ID number. In addition, the SalariedEmployee should have a weekly
salary; an HourlyEmployee should have a wage and a number of hours worked; a
CommissionEmployee should have a commission rate and gross sales; and a
BaseCommissionEmployee should have a base salary. Each class should have an appropriate
constructor, setters and getters. Each Employee should have an earning() and toString()
methods. Also make Employee comparable. The compareTo method compares between the
employees based on earnings.
• Write a method that finds the total earnings of all the employees in an array. The method
signature is:
public static double totalEarning(Employee[] a)
• Write another method that sorts an array of Objects using the compareTo method. The
signature of this method is:
public static void sort(Object[] a)
• Write a test program that creates an array of 5 employees and computes their total
earnings using the totalEarning method.
Computer Science Department (Laboratory Work Book for Comp231) 37
2. Implement the superclass Shape and its subclasses Circle, Rectangle and Square as shown
in the following UML class diagram, note that the compareTo method will compare based on
area:
Create an array list of 5 different shapes, then sort the list and print the type of each object
with its area.
Computer Science Department (Laboratory Work Book for Comp231) 38
Theory
A Runtime errors occur while a program is running if the JVM detects an operation that is
impossible to carry out, in java, the runtime errors are thrown as exception, so the exception is
an object that represents an error or condition that prevents execution from proceeding
normally. If the exception is not handled, the program will terminate abnormally.
Java exception handling model is based on three operations: declaring an exception, throwing an
exception, and catching an exception, as in the following figure.
Syntax
Try-catch block:
try{
statements;
}catch(Exception1 exVar1){
Handler for exception1;
} catch(Exception2 exVar2){
Handler for exception2;
}…
catch(ExceptionN exVarN){
Handler for exceptionN;
}
Computer Science Department (Laboratory Work Book for Comp231) 39
Exercises
2) Design a Circle class that has radius and color as attributes and allow the
setRadius method to throw an IllegalArgumentException if the radius is
negative.
3) Write a program that reads unknown number of students from file named
students.txt, the data stored in this file as following:
Ahmad 90 85 78
Musa 76 80 84
Salam 85 90 99
Then calculate the average of each student and save the results on a file named
output.txt as following:
Ahmad 84.3
Musa 80
Salam 91.3
Computer Science Department (Laboratory Work Book for Comp231) 40
Objectives
• To write a javaFX program and understand the relationship among stages, scenes, and
nodes.
• To create user interface using panes, UI controls, and shapes.
• To create a graphical user interface with various user-interface controls.
• Learn how to use several UI controls such as Button, Label, and TextField.
Theory
A graphical user interface (GUI) makes a system user-friendly and easy to use. Creating a
GUI requires creativity and knowledge of how UI controls work. Since the UI controls in
javaFX are very flexible and versatile, you can create a wide assortment of useful user interface
for rich Internet applications.
Computer Science Department (Laboratory Work Book for Comp231) 41
Exercises
1. Write a program that display the traffic light as in the figure below:
2. Write a java program that displays a checkboard in which each white and black cell is a
Rectangle with a fill color black or white as in the figure below:
JavaFX
Computer Science Department (Laboratory Work Book for Comp231) 42
Objectives
• To get the taste of event-driven programming.
• To describe events, even sources, and event classes.
• To define event handler classes using inner classes, and simplify event handling using
lambda expression.
To develop applications using MouseEvents and KeyEvents.
Theory
When you run a Java GUI program, the program interacts with the user, and the events drive
its execution. This is called event-driven programming. An event can be defined as a signal
to the program that something has happened. Events are triggered by external user actions,
such as mouse movements, mouse clicks, and keystrokes. The program can choose to respond
to or ignore an event.
Computer Science Department (Laboratory Work Book for Comp231) 43
Exercises
1. Write a program that displays the traffic light as in the figure below, the program will
simulate a traffic light, the user can select one of the three lights: red, yellow, or green.
When a radio button is selected, the light is turned on. Only one light can be on at a
time, No light is on when the program starts.
2. Write a java program that displays the following UI and sets the horizontal-alignment
and column-size properties of text field dynamically:
JavaFX
Computer Science Department (Laboratory Work Book for Comp231) 44
3. Write a complete Java program which will display a user interface (UI) as in the
following figure using javaFX to collect student information. The collected
information are:
a. Student number
b. Student name
c. Average
d. Department name
When your program started, it should display a UI that enables the user to
enter the required information and add button that will take information
and saves it in a file.
Computer Science Department (Laboratory Work Book for Comp231) 45
* Each line in the file consists of: student information: id, name, major, and average
marks, separated by a ( : ).
• Create a driver class named Driver that has an ArrayList of Students.
• The driver class does the following:
o At start, it reads the students.txt file records (line by line). Converts each line to a
specific student object with appropriate major and add it to the students ArrayList.
§ Notes:
• Only consider the students with CS or CSE major.
• Some student’s information are missing, in this case ignore this
student.
o Implement the following methods:
§ topStudent(major): returns the students that has the best average in his
major.
§ studentsAverage(major): returns the average of students in the major.
Computer Science Department (Laboratory Work Book for Comp231) 47
§ Clicking the “Top Major Student” button will execute the method
topStudent(major) and pass to it the value of selected Major radio button.
The output will be displayed in the TextFiled as follow: