THE UNIVERSITY OF DODOMA
COLLEGE OF INFORMATICS AND VIRTUAL EDUCATION
DEGREE PROGRAM: BSC-IDIT
COURSE NAME : INTRODUCTION TO OBJECT ORIENTED IN JAVA
PROGRAMMING
COURE CODE: CP 215
NAME: WAHABI GAMBA JUMA
REG NO: T21-03-12513
JAVA PRACTICAL_2
1. Write Java statements that accomplish each of the following tasks:
a) Display the message "Enter an integer: ", leaving the cursor on the same line.
Answer.
b) Assign the product of variables b and c to variable a.
Answer.
c) Use a comment to state that a program performs a sample payroll calculation.
Answer.
// A program perform a sample payroll calculation.
2. Write an application that displays the numbers 1 to 4 on the same line, with each pair of
adjacent numbers separated by one space. Use the following techniques:
a) Use one System.out.println statement.
Answer.
Output.
b) Use four System.out.print statements.
Answer.
Output.
c) Use one System.out.printf statement.
Answer.
Output.
3. Write an application that asks the user to enter two integers, obtain them from the user and
calculate and prints their sum, product, difference and quotient (division).
Answer.
Output.
4. Write an application that asks the user to enter two integers, obtains them from the user
and displays the larger number followed by the words "is larger". If the numbers are equal,
print the message "These numbers are equal".
Output
.
5. Write an application that inputs three integers from the user and displays the sum, average,
product, smallest and largest of the numbers.
Answer.
Output.
6. Write an application that inputs from the user the radius of a circle as an integer and prints
the circle’s diameter, circumference and area using the floating-point value 3.14159 for
π(You may also use the predefined constant Math.PI for the value of π). Use the following
formulas (r is the radius)
diameter = 2r
circumference = 2πr
area = πr2
Answer
.
Output.
7. Write an application that displays a box, an oval, an arrow and a diamond using asterisks
(*), as follows:
Answer.
Output.
8. Write a program that inputs five numbers and determines and prints the number of negative
numbers input, the number of positive numbers input and the number of zeros input.
Output.
9. (Body Mass Index Calculator) We introduced the body mass index (BMI) calculator in
Exercise 1.10. The formulas for calculating BMI are:
𝑤𝑒𝑖𝑔ℎ𝑡𝐼𝑛𝐾𝑖𝑙𝑜𝑔𝑟𝑎𝑚𝑠
BMI =
ℎ𝑒𝑖𝑔ℎ𝑡𝐼𝑛𝑀𝑒𝑡𝑒𝑟𝑠 × ℎ𝑒𝑖𝑔ℎ𝑡𝐼𝑛𝑀𝑒𝑡𝑒𝑟𝑠
Create a BMI calculator that reads the user’s weight in kilograms and height in meters, then
calculates and displays the user’s body mass index. Also, display the following information
from the Department of Health and Human Services/National Institutes of Health so the user
can evaluate his/her BMI:
BMI VALUES
Underweight: less than 18.5
Normal: between 18.5 and 24.9
Overweight: between 25 and 29.9
Obese: 30 or greater
Answer.
Output.
10. Research several car-pooling websites. Create an application that calculates your daily
driving cost, so that you can estimate how much money could be saved by carpooling, which
also has other advantages such as reducing carbon emissions and reducing traffic congestion.
The application should input the following information and display the user’s cost per day of
driving to work:
a) Total miles driven per day.
b) Cost per gallon of gasoline.
c) Average miles per gallon.
d) Parking fees per day.
e) Tolls per day.
Answer.
Output.
T21-03-12513
JAVA PRACTICAL_3
1. Write a program to calculate the grade of a student given the average. Use if-else
statement
Hints:
Marks < 0 or Marks > 100 give Error Message
0 <= Marks < 40 – Grade = C
40 <= Marks < 70 – Grade = B
70 <= Marks <= 100 – Grade = A
Answer:
Output
2.Write a program to output the following. Use switch
Grade = A – ‘Very Good’
Grade = B – ‘Good’
Grade = C – ‘Bad’
Answer
Output
3.Write a method to calculate the factorial of a given integer
• Using For loop
Answer.
• Using a While Loop
Answer.
• Using a Do-While Loop
Answer.
4.A program is required to read a customer’s name, a purchase amount, and a tax code. The
tax code has been validated and will be one of the following:
a. 0 tax exempt(0%)
b. 1 state sales tax only (3%)
c. 2 federal and state sales tax (5%)
d. 3 special sales tax (7%)
The program must then compute the sales tax and the total amount due, and print the
customer’s name, purchase amount, sales tax, and total amount due.
Answer.
5.Every day, a weather station receives 15 temperatures expressed in degrees Fahrenheit. A
program is to be written that will accept each Fahrenheit temperature, convert it to Celsius
and display the converted temperatures to the screen. After 15 temperatures have been
processed, the words ‘All temperatures processed’ are to be displayed on the screen.
Answer.
Output.
6.A program is required to read and print a series of names and exam scores for students
enrolled in a mathematics course. The class average is to be computed and printed at the end
of the report. Scores can range from 0 to 100. The last record contains a blank name and a
score of 999 and is not to be included in the calculations.
Answer.
output
7.Create a single dimensional array to store 20 integer elements supplied by user, then display
them using.
a) Normal For loop
b) Enhanced For loop
Answer.
The output of the program above is:
ENHANCED LOOP:
The output of the program above is:
.Create a 3 x 4, two dimensional array to store elements supplied by the user and display the
values stored.Answer.
Output.
9.Using single dimensional array and two dimensional do the following tasks:
Create and array of 100 integer elements
Perform summation of all elements
Perform average
Perform sorting of elements in ascending order
Perform sorting of elements in descending order
Answer.
Output
JAVA PRACTICAL_4
1. Write a java class containing main method and another method called display. The method
display shall be called within main method to output Hello Said to the screen. Method
display should not have parameters or return type.
Answer.
2. Write java class containing main method and other two methods called addition and
myMedthod. Method addition should display the sum of two integers passed through its
parameters a and b. myMethod should display title “Adding two Integers:” which is passed
through its string parameter called title. All the methods should be called within main
method. Note: Arguments should be hardcoded or embedded with the code.
Answer.
OUTPUT
3. Modify question 2 to allow a user to pass arguments to the methods using Scanner class.
Answer.
Output.
4. Write a java class containing three methods; main, display, and addition methods. Method
display should be responsible for outputting results to the screen. Method addition should
add two integers passed through its parameters a and b and return the sum to method
display. Method display should be called by the main method.
Answer.
Output.
5. Write a java class that contains two methods; main and addition. Method addition should
be overloaded to perform addition of two integers, addition of two double, addition of three
integers and concatenation of two strings. Results should be displayed in main method. All
values should be supplied by user via keyboard.
Answer.
Output.
6. Create a class called Student with four instance variables; name, regNumber, yearOfStudy,
and gender. Create set and get methods for inserting and returning values from the instance
variables respectively. Values to the variable should be hardcoded through the parentheses
of the method during the call.
Answer.
Output.
7. Modify question number 6 by separating it into two classes; Class Student and class
myMain. Class student should have four instance variables; name, regNumber,
yearOfStudy, and gender. While class myMain should be used to define main method,
create object of class student and display values. Values to the variable should be supplied
by the user and passed through the parentheses of the class’s object.
Answer.
Output.
8. Write java program(s) that illustrate declaration and usage of local variables, instance
variables, instance methods, class variables and class methods. Use comments to locate
local, instance, and class variables and methods declared.
Answer.
9. Write java class that has one instance variable, a programmer defined constructor which
initializes that instance variable of the class and one method that accepts an integer value.
Write another java class that instantiates an object of the class that was created and calls
the method defined in the class. Use comments to indicate a parameter and an argument.
Answer.
10. (Employee Class) Create a class called Employee that includes three instance variables—a
first name (type String), a last name (type String) and a monthly salary (double). Provide a
constructor that initializes the three instance variables. Provide a set and a get method for
each instance variable. If the monthly salary is not positive, do not set its value. Write a test
app named EmployeeTest that demonstrates class Employee’s capabilities. Create two
Employee objects and display each object’s yearly salary. Then give each Employee a 10%
raise and display each Employee’s yearly salary again.
Answer.
Output
11. (Invoice Class) Create a class called Invoice that a hardware store might use to represent
an invoice for an item sold at the store. An Invoice should include four pieces of
information as instance variables—a part number (type String), a part description (type
String), a quantity of the item being purchased (type int) and a price per item (double).
Your class should have a constructor that initializes the four instance variables. Provide a
set and a get method for each instance variable. In addition, provide a method named
getInvoiceAmount that calculates the invoice amount (i.e., multiplies the quantity by the
price per item), then returns the amount as a double value. If the quantity is not positive, it
should be set to 0. If the price per item is not positive, it should be set to 0.0. Write a test
app named InvoiceTest that demonstrates class Invoice’s capabilities.
Answer
Output.qn 11:
JAVA PRACTICAL_5
1. Write a java app that contains a version of class Account that maintains an instance
variables name and balance of a bank account. A typical bank services many accounts,
each with its own balance. Every instance (i.e., object) of class Account contains its
own copies of both the name and the balance. Provide constructor to initialize instance
variables. Provide method setName, getName, deposite and getBalance to set name, get
name, deposite money to balance and get balance respectively. Then provide another
class called AccountTest and create two objects to test the Account class.
Answer.
Output.
2. Modify class Account (in question 1) to provide a method called withdraw that
withdraws money from an Account. Ensure that the withdrawal amount does not
exceed the Account’s balance. If it does, the balance should be left unchanged and the
method should print a message indicating "Withdrawal amount exceeded account
balance." Modify class AccountTest to test method withdraw.
Answer.
Output.
3. Write a java program that declares two classes—Employee and EmployeeTest. Class
Employee declares private static variable count and public static method getCount. The
static variable count maintains a count of the number of objects of class Employee that
have been created so far. This class variable has to be initialized to zero. If a static
variable is not initialized, the compiler assigns it a default value—in this case 0, the
default value for type int. EmployeeTest method main instantiates two Employee
objects to test the Employee class.
Answer.
Output.
4. Create a class Rectangle with attributes length and width, each of which defaults to 1.
Provide methods that calculate the rectangle’s perimeter and area. It has set and get
methods for both length and width. The set methods should verify that length and width
are each floating-point numbers larger than 0.0 and less than 20.0. Write a program to
test class Rectangle.
Answer.
Output.
5. Create class SavingsAccount. Use a static variable annualInterestRate to store the
annual interest rate for all account holders. Each object of the class contains a private
instance variable savingsBalance indicating the amount the saver currently has on
deposit. Provide method calculateMonthlyInterest to calculate the monthly interest by
multiplying the savingsBalance by annualInterestRate divided by 12—this interest
should be added to savings-Balance. Provide a static method modifyInterestRate that
sets the annualInterestRate to a new value. Write a program to test class
SavingsAccount. Instantiate two savingsAccount objects, saver1 and saver2, with
balances of $2000.00 and $3000.00, respectively. Set annualInterestRate to 4%, then
calculate the monthly interest for each of 12 months and print the new balances for both
savers. Next, set the annualInterestRate to 5%, calculate the next month’s interest and
print the new balances for both savers.
Answer.
Output.
JAVA PRACTICAL_6
1. (Composition)Write a java program that contains classes Date, Employee and
EmployeeTest.Class Date declares instance variables month, day and year to represent
a date. Create a constructor that receives three int parameters for initializing the objects.
Provide a toString method to obtain the object’s String representation. Class Employee
has instance variables firstName, lastName, birthDate and hireDate. Members
firstName and lastName are references to String objects. Members birthDate and
hireDate are references to Date objects. Create Employee constructor that takes four
parameters representing the first name, last name, birth date and hire date for initializing
the objects. Provide a toString to returns a String containing the employee’s name and
the String representations of the two Date objects. Class EmployeeTest creates two Date
objects to represent an Employee’s birthday and hire date, respectively. It creates an
Employee’s object and initializes its instance variables by passing to the constructor
two Strings (representing the Employee’s first and last names) and two Date objects
(representing the birthday and hire date).\
Answer.
Output
2. (Composition)Modify question 1 to perform validation of the month and day. Validate
the month—if it’s out-of-range, display error report. Validate the day, if the day is
incorrect based on the number of days in the particular month (except February 29th
which requires special testing for leap years), display error report. Perform the leap year
testing for February, if the month is February and the day is 29 and the year is not a
leap year, display error report.
Answer
0utput
3. (Single Inheritance) Write a java app that contains classes Polygon, Rectangle, and
myMain. Class Polygon declares instance variables height and width and defines a
method setValues for setting height and width values supplied by user. Class rectangle
extends class Poygon and defines method area for calculating and returning area of a
rectangle. Class myMain defines main method, creates an object and calls other
methods for demonstrating their capabilities.
Answer.
Output.
4. (Multilevel Inheritance) Write a java app that contains classes EmployeeA,
EmployeeB, EmployeeC and EmployeesTest. Class EmployeeA should declare float
variable salary initialized with an arbitrary value. Class EmployeeB declares float
variable bonusB initialized with an arbitrary value and extends class EmployeeA. Class
EmployeeC declares float variable bonusC initialized with an arbitrary value and
extends class EmployeeB. Class EmployeesTest should define main method, create
object of class EmployeeC and display the earning of each employee.
Answer.
Output.
5. (Hierarchical Inheritance) Write a java app that contains classes Polygon, Rectangle,
Rectangle and myMain. Class Polygon declares instance variables height and width and
defines a method setValues for setting height and width values supplied by user. Class
Rectangle defines method areaR for calculating and returning area of a rectangle and
extends class Poygon. Class Triangle defines method areaT for calculating and
returning area of a triangle and extends class Polygon. Class myMain defines main
method, creates Rectangle and Triangle’s objects and calls the methods for
demonstrating their capabilities.
Answer.
Output.
6. (Abstraction and Overriding) Write a java app that contains classes Polygon, Rectangle,
Triangle and myMain. Class Polygon declares instance variables height and width and
defines a method setValues for setting height and width values supplied by user. It
should also define abstract method area. Class Rectangle extends class Polygon and
implements method area for calculating and returning area of a rectangle. Class
Triangle extends class Polygon and implements method area for calculating and
returning area of a triangle. Class myMain defines main method, creates Rectangle and
Triangle’s objects and calls the methods for demonstrating their capabilities.
Answer.
abstract public class Polygon {
double heigth;
double width;
public void setValues(double heigth,double width){
this.heigth=heigth;
this.width=width;
}
public abstract double areaR();
public abstract double areaT();
}
abstract public class Rectangle extends Polygon {
public double areaR(){
double areaR=this.heigth * this.width;
return(areaR);
}
}
public class Triangle extends Rectangle {
public double areaT(){
double areaT=(0.5 * this.heigth *this.width);
return(areaT);
}
}
Output.
7. (Hierarchical Inheritance) Write a java app that contains classes Employee,
Programmer, Accountant and MyMain. Class Employee should declare double variable
salary initialized with an arbitrary value. Class Programmer declares double variable
bonusP initialized with an arbitrary value and extends class Employee. Class
Accountant declares double variable bonusA initialized with an arbitrary value and
extends class Employee. Class MyMain should define main methdod, create objects of
classes Programmer and Accountant and display the earning of each employee.
Answer.
Output.
8. In this question we use an inheritance hierarchy containing types of employees in a
company’s payroll application to understand the relationship between a superclass and
its subclass. In this company, commission employees (who will be represented as
objects of a superclass) are paid a percentage of their sales, while base-salaried
commission employees (who will be represented as objects of a subclass) receive a base
salary plus a percentage of their sales. We divide our problem into five parts.
a. Declare class CommissionEmployee, which directly inherits from class Object
and declares as private instance variables a first name, last name, social security
number, commission rate and gross (i.e., total) sales amount.
b. Declare class BasePlusCommissionEmployee, which also directly inherits from
class Object and declares as private instance variables a first name, last name,
social security number, commission rate, gross sales amount and base salary.
You create this class by writing every line of code the class requires. What
problem did you note regarding relationship between class
BasePlusCommissionEmployee and CommissionEmployee?
c. Declare a new BasePlusCommissionEmployee class that extends class
CommissionEmployee (i.e., a BasePlusCommissionEmployee is a
CommissionEmployee who also has a base salary). Why the code is not
running?
d. Change CommissionEmployee’s instance variables to protected. Now
BasePlusCommissionEmployee subclass can access that data directly. What is
tha drawbacks of using protected instance variables?
e. Set the CommissionEmployee instance variables back to private to enforce good
software engineering. Then show how the BasePlusCommissionEmployee
subclass can use CommissionEmployee’s public methods to manipulate (in a
controlled manner) the private instance variables inherited from
CommissionEmployee. What are advantages of using private instance variables
in this case?
Answer.
Output.
9. (Abstraction)A company pays its employees on a weekly basis. The employees are of
four types: Salaried employees are paid a fixed weekly salary regardless of the number
of hours worked, hourly employees are paid by the hour and receive overtime pay (i.e.,
1.5 times their hourly salary rate) for all hours worked in excess of 40 hours,
commission employees are paid a percentage of their sales and base-salaried-
commission-employees receive a base salary plus a percentage of their sales. For the
current pay period, the company has decided to reward salaried-commission employees
by adding 10% to their base salaries. The company wants you to write an application
that performs its payroll calculations. Use an abstract superclass Employee that includes
firstName, lastName, socialSecurityNumber, getFirstName, getLastName,
getSocialSecurityNumber, toString, constructor and an abstract method earning. The
classes that extend Employee are SalariedEmployee, CommissionEmployee and
HourlyEmployee. Class BasePlusCommissionEmployee which extends
CommissionEmployee represents the last employee type. The inheritance hierarchy is
represented on the figure below.
Employee
HourlyEmployee CommissionEmployee SalariedEmployee
BasePlusCommissionEmploye
Answer. e
1. Abstract class Employee.
public abstract class Employee
private String firstName;
private String lastName;
private String socialSecurityNumber;
// three-argument constructor
public Employee( String first, String last, String ssn )
firstName = first;
lastName = last;
socialSecurityNumber = ssn;
} // end three-argument Employee constructor
// set first name
public void setFirstName( String first )
firstName = first; // should validate
} // end method setFirstName
// return first name
public String getFirstName()
{
return firstName;
} // end method getFirstName
// set last name
public void setLastName( String last )
lastName = last;} // should validate
// return last name
public String getLastName()
return lastName;
}// end method getLastName
// set social security number
public void setSocialSecurityNumber( String ssn )
socialSecurityNumber = ssn; // should validate
} // end method setSocialSecurityNumber
// return social security number
public String getSocialSecurityNumber()
return socialSecurityNumber;}
// return String representation of Employee object
//@Override
public String toString()
return String.format( "%s %s\nsocial security number: %s",
getFirstName(), getLastName(), getSocialSecurityNumber() );
} // end method toString
// abstract method overridden by concrete subclasses
public abstract double earnings(); // no implementation here
} // end abstract class Employee
2. Class CommissionEmployee.
public class CommissionEmployee extends Employee
private double grossSales; // gross weekly sales
private double commissionRate; // commission percentage
// five-argument constructor
public CommissionEmployee( String first, String last, String ssn,
double sales, double rate )
super( first, last, ssn );
setGrossSales( sales );
} // end five-argument CommissionEmployee constructor
// set commission rate
public void setCommissionRate( double rate )
if ( rate > 0.0 && rate < 1.0 )
commissionRate = rate;
else
throw new IllegalArgumentException(
"Commission rate must be > 0.0 and < 1.0" );
} // end method setCommissionRate
// return commission rate
public double getCommissionRate()
return commissionRate;
} // end method getCommissionRate
// set gross sales amount
public void setGrossSales( double sales )
if ( sales >= 0.0 )
grossSales = sales;
else
throw new IllegalArgumentException(
"Gross sales must be >= 0.0" );
} // end method setGrossSales
// return gross sales amount
public double getGrossSales()
return grossSales;
} // end method getGrossSales
// calculate earnings; override abstract method earnings in Employee
@Override public double earnings()
return getCommissionRate() * getGrossSales();
} // end method earnings
// return String representation of CommissionEmployee object
@Override
public String toString()
return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f",
"commission employee", super.toString(),
"gross sales", getGrossSales(),
"commission rate", getCommissionRate() );
} // end method toString
} // end class CommissionEmployee
3. Class HourlyEmployee.
public class HourlyEmployee extends Employee
private double wage; // wage per hour
private double hours; // hours worked for week
// five-argument constructor
public HourlyEmployee( String first, String last, String ssn,
double hourlyWage, double hoursWorked )
{
super( first, last, ssn );
setWage( hourlyWage ); // validate hourly wage
setHours( hoursWorked ); // validate hours worked
} // end five-argument HourlyEmployee constructor
// set wage
public void setWage( double hourlyWage )
if ( hourlyWage >= 0.0 )
wage = hourlyWage;
else
throw new IllegalArgumentException(
"Hourly wage must be >= 0.0" );
} // end method setWage
// return wage
public double getWage()
return wage;
} // end method getWage
// set hours worked
public void setHours( double hoursWorked )
if ( ( hoursWorked >= 0.0 ) && ( hoursWorked <= 168.0 ) )
hours = hoursWorked;
else
throw new IllegalArgumentException(
"Hours worked must be >= 0.0 and <= 168.0" );
} // end method setHours
// return hours worked
public double getHours()
{
return hours;
} // end method getHours
// calculate earnings; override abstract method earnings in Employee
@Override
public double earnings()
if ( getHours() <= 40 ) // no overtime
return getWage() * getHours();
else
return 40 * getWage() + ( getHours() - 40 ) * getWage() * 1.5 ;
} // end method earnings
// return String representation of HourlyEmployee object
@Override
public String toString()
return String.format( "hourly employee: %s\n%s: $%,.2f; %s: %,.2f",
super.toString(), "hourly wage" , getWage(),
"hours worked", getHours() );
} // end method toString
} // end class HourlyEmployee
4. BasePlusCommissionEmployee .
public class BasePlusCommissionEmployee extends CommissionEmployee
private double baseSalary; // base salary per week
// six-argument constructor
public BasePlusCommissionEmployee( String first, String last,
String ssn, double sales, double rate, double salary )
super( first, last, ssn, sales, rate );
setBaseSalary( salary ); // validate and store base salary
} // end six-argument BasePlusCommissionEmployee constructor
// set base salary
public void setBaseSalary( double salary )
if ( salary >= 0.0 )
baseSalary = salary;
else
throw new IllegalArgumentException(
"Base salary must be >= 0.0" );
} // end method setBaseSalary
// return base salary
public double getBaseSalary()
return baseSalary;
} // end method getBaseSalary
// calculate earnings; override method earnings in CommissionEmployee
@Override
public double earnings()
return getBaseSalary() + super.earnings();
}// end method earnings
// return String representation of BasePlusCommissionEmployee object
@Override
public String toString()
return String.format( "%s %s; %s: $%,.2f",
"base-salaried", super.toString(),
"base salary", getBaseSalary() );
} // end method toString
} // end class BasePlusCommissionEmployee
4.Main class.
public class PayrollCalculation {
public static void main(String args[]){
BasePlusCommissionEmployee obj=new
BasePlusCommissionEmployee("Frank","Oscar","TN123",250000.00,9.1,300000.00);
System.out.println(obj.toString());
5. output.