Oop Exercises
Oop Exercises
// filename: Name.java
// Class containing display() method, notice the class doesnt have a main() method
public class Name {
public void display() {
System.out.println("Medipol University");
}
}
// filename: DisplayName.java
// place in same folder as the Name.java file
// Class containing the main() method
public class DisplayName {
public static void main(String[] args) {
Name myname = new Name(); // creating a new object of Name class
myname.display(); // executing the display() method in the Name class
}
}
2. Write a program that calculates and prints the product of three integers.
// filename: Q1.java
import java.util.Scanner; // import Scanner libraries for input
public class Q1 {
int number1;
int number2;
int number3;
1
3. Write a program that converts a Fahrenheit degree to Celsius using the formula:
// filename: Q2.java
import java.util.*;
public class Q2 {
4. Write an application that displays the numbers 1 to 4 on the same line, with each pair of adjacent numbers
separated by one space. Write the application using the following techniques:
a. Use one System.out.println statement.
b. Use four System.out.print statements.
c. Use one System. out. printf statement.
// filename: Printing.java
public class Printing {
System.out.println(num1 + " " + num2 + " " + num3 + " " + num4);
System.out.print(num1 + " " + num2 + " " + num3 + " " + num4);
System.out.printf("\n%d %d %d %d",num1,num2,num3,num4);
}
2
5. Write an application that asks the user to enter two integers, obtains them from the user and prints their sum,
product, difference and quotient (division).
// File: NumberCalc1.java
import java.util.Scanner; // include scanner utility for accepting keyboard input
// display the sum, product, difference and quotient of the two numbers
System.out.printf(" -------------------------- \n");
System.out.printf("\tSum =\t\t %d\n", num1+num2);
System.out.printf("\tProduct =\t %d\n", num1*num2);
System.out.printf("\tDifference =\t %d\n", num1-num2);
System.out.printf("\tQuotient =\t %d\n", num1/num2);
}
}
6. 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 “These numbers are equal”
3
7. Write an application that inputs three integers from the user and displays the sum, average, product, smallest
and largest of the numbers.
// display the sum, average, product, smallest and the biggest of all three numbers
System.out.printf("\t ------------------------ \n");
System.out.printf("\t\t\tSum =\t\t %d\n", num1+num2+num3);
System.out.printf("\t\t\tAverage =\t %d\n", (num1+num2+num3)/3);
System.out.printf("\t\t\tProduct =\t %d\n", num1*num2*num3);
System.out.printf("\t\t\tBiggest =\t %d\n", bigger);
System.out.printf("\t\t\tSmallest =\t %d\n", smaller);
}
}
8. Write an application that reads two integers, determines whether the first is a multiple of the second and print
the result. [Hint Use the remainder operator.]
4
9. The process of finding the largest value (i.e., the maximum of a group of values) is used frequently in computer
applications. For example, a program that determines the winner of a sales contest would input the number of
units sold by each sales person. The sales person who sells the most units wins the contest. Write a Java
application that inputs a series of 10 integers and determines and prints the largest integer. Your program should
use at least the following three variables:
a. counter: A counter to count to 10 (i.e., to keep track of how many numbers have been input and to
determine when all 10 numbers have been processed).
b. number: The integer most recently input by the user.
c. largest: The largest number found so far.
// File: Question4.java
10. Write a Java application that uses looping to print the following table of values:
// File: Question5.java
5
11. Write a complete Java application to prompt the user for the double radius of a sphere, and call method
sphereVolumeto calculate and display the volume of the sphere. Use the following statement to calculate the
volume:
// File: Question6.java
import java.util.Scanner; // include scanner utility for accepting keyboard input
public class Question6 {
// part a
int array[]={0,0,0,0,0,0,0,0,0,0}; // declaring and setting 10 elements in the array with zero
// part b
int bonus[];
bonus=new int[15]; // declaring array bonus with 15 elements
// part c
int bestScores[]={10,20,30,40,50}; // declaring the array bestScores of 5 elements
for (int j=0;j<5;j++){
System.out.printf("%d\t", bestScores[j]); // displaying them in a column format
}
}
}
6
13. Write a Java program that reads a string from the keyboard, and outputs the string twice in a row, first all
uppercase and next all lowercase. If, for instance, the string “Hello" is given, the output will be “HELLOhello"
public static void main(String[] args) {// begin the main method
Scanner input=new Scanner(System.in); //create a new Scanner object to use
String str; //declaring a string variable str
System.out.printf("Enter String: ");
str=input.nextLine();// store next line in str
14. Write a Java application that allows the user to enter up to 20 integer grades into an array. Stop the loop by
typing in ‐1. Your main method should call an Average method that returns the average of the grades. Use the
DecimalFormat class to format the average to 2 decimal places.
public static double Average(int grades[], int max ) {// begin Average method
int sum=0; // initialize variables
double average=0.0;
public static void main(String[] args) {// begin the main method
7
15. Modify class Account (in the example) to provide a method called debit that withdraws money froman Account.
Ensure that the debit 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 ―Debit amount exceeded account balance.
Modify class AccountTest (intheexample) to test method debit.
//filename: Account.java
public class Account {
private double balance;
//filename: AccountTest.java
import java.util.Scanner;
// display balances
System.out.printf( "Account1 balance: $%.2f\n", account1.getBalance() );
System.out.printf( "Account2 balance: $%.2f\n\n", account2.getBalance() );
// display balances
System.out.printf( "Account1 balance: $%.2f\n", account1.getBalance() );
System.out.printf( "Account2 balance: $%.2f\n", account2.getBalance() );
8
if (account1.getBalance()>=debitAmount) {
account1.debit( debitAmount );
System.out.printf( "Account1 balance: $%.2f\n", account1.getBalance() );
System.out.printf( "Account2 balance: $%.2f\n\n", account2.getBalance() );
}
else {
System.out.printf("!!! Debit amount exceeded account balance!!!\n\n");
}
// display balances
System.out.print( "Enter debit amount for account2: " );
debitAmount = input.nextDouble();
System.out.printf( "\nSubtracting %.2f from account2 balance\n\n", debitAmount );
if (account1.getBalance()>=debitAmount) {
account1.debit( debitAmount );
System.out.printf( "Account1 balance: $%.2f\n", account1.getBalance() );
System.out.printf( "Account2 balance: $%.2f\n\n", account2.getBalance() );
}
else {
System.out.printf("!!!Debit amount exceeded account balance!!!\n\n");
}
}
}
9
16. 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 getInvoice Amount 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 application named InvoiceTest that demonstrates class Invoice’s capabilities.
//filename: Invoice.java
public class Invoice {
private String partNumber;
private String partDescription;
private int quantity;
private double price;
//filename: InvoiceTest.java
10
public class InvoiceTest {
public static void main (String args[]){
Invoice invoice1=new Invoice ("A5544", "Big Black Book", 500, 250.00);
Invoice invoice2=new Invoice ("A5542", "Big Pink Book", 300, 50.00);
11
17. Create a class called Employee that includes three pieces of information as instance variables—a first name
(typeString), a last name (typeString) and a monthly salary (double). Your class should have 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, set it to 0.0. Write a test application 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.
//filename: Employee.java
public class Employee {
private String firstName;
private String lastName;
private double salary;
//filename: EmployeeTest.java
public class EmployeeTest {
12
System.out.printf("2:\t %s %s\t\t$%.2f\n", employee2.getFirstName(),
employee2.getLastName(), employee2.getSalary());
13
18. Create a class called Date that includes three pieces of information as instance variables—a month (typeint), a
day (typeint) and a year (typeint). Your class should have a constructor that initializes the three instance
variables and assumes that the values provided are correct. Provide a set and a get method for each instance
variable. Provide a method displayDate that displays the month, day and year separated by forward slashes(/).
Write a test application named DateTest that demonstrates classDate’s capabilities.
//filename: Date.java
// Date class
public class Date {
private int month;
private int day;
private int year;
//filename: DateTest.java
// Date testing class with the main() method
import java.util.*;
public class DateTest {
14
System.out.println("Enter the Year");
int myYear = input.nextInt();
myDate.setYearDate(myYear);
myDate.displayDate();
}
}
15
19. 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 tosavingsBalance. 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 and print the new balances for both savers. Then set the annualInterestRate to 5%, calculate the next
month’s interest and print the new balances for both savers.
//filename: SavingAccount.java
public class SavingsAccount {
public static double annualInterestRate;
private double savingsBalance;
public SavingsAccount() {
annualInterestRate = 0.0;
savingsBalance = 0.0;
}
//filename: SavingsAccountTest.java
public class SavingsAccountTest {
saver1.setSavingsBalance(2000.00);
saver2.setSavingsBalance(3000.00);
SavingsAccount.modifyInterestRate(0.04);
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
16
System.out.printf("New Balance for Saver2=%f\n",saver2.getSavingsBalance());
SavingsAccount.modifyInterestRate(0.05);
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
}
}
17
20. Create a class called Book to represent a book. A Book should include four pieces of information as instance
variables‐a book name, an ISBN number, an author name and a publisher. Your class should have a constructor
that initializes the four instance variables. Provide a mutator method and accessor method (query method) for
each instance variable. Inaddition, provide a method named getBookInfo that returns the description of the
book as a String (the description should include all the information about the book). You should use this keyword
in member methods and constructor. Write a test application named BookTest to create an array of object for 30
elements for class Book to demonstrate the class Book's capabilities.
//filename: Book.java
public class Book {
private String Name;
private String ISBN;
private String Author;
private String Publisher;
public Book() {
Name = "NULL";
ISBN = "NULL";
Author = "NULL";
Publisher = "NULL";
}
//filename: SavingsAccountTest.java
// SavingsAccount testing class with the main() method
18
Book test[] = new Book[13];
test[1] = new Book();
test[1].getBookInfo();
19
21.
a. Create a super class called Car. The Car class has the following fields and methods.
◦ intspeed;
◦ doubleregularPrice;
◦ Stringcolor;
◦ doublegetSalePrice();
//filename: Car.java
public class Car {
private int speed;
private double regularPrice;
private String color;
}
b. Create a sub class of Car class and name it as Truck. The Truck class has the following fields and methods.
◦ intweight;
◦ doublegetSalePrice(); //Ifweight>2000,10%discount.Otherwise,20%discount.
//filename: Truck.java
// Truck class, subclass of Car
public class Truck extends Car {
private int weight;
//filename: Ford.java
// Ford class, subclass of Car
public class Ford extends Car {
private int year;
private int manufacturerDiscount;
20
this.manufacturerDiscount = manufacturerDiscount;
}
d. Create a subclass of Car class and name it as Sedan. The Sedan class has the following fields and methods.
◦ intlength;
◦ doublegetSalePrice();//Iflength>20feet,5%discount,Otherwise,10%discount.
//filename: Sedan.java
// Sedan class, subclass of Car
public class Sedan extends Car {
private int length;
e. Create MyOwnAutoShop class which contains the main() method. Perform the following within the main()
method.
◦ Create an instance of Sedan class and initialize all the fields with appropriate values. Use super(...) method in
the constructor for initializing the fields of the superclass.
◦ Create two instances of the Ford class and initialize all the fields with appropriate values. Use super(...)
method in the constructor for initializing the fields of the super class.
◦ Create an instance of Car class and initialize all the fields with appropriate values.
Display the sale prices of all instance.
//filename: MyOwnAutoShop.java
// Testing class with the main() method
public class MyOwnAutoShop {
(int Speed,double regularPrice,String color, int year, int manufacturerDiscount)
21