Tasks & Solution of Java Language


1. Introduction to Java


1) Write a program that prints a mosque.

Output:
firstImage

Source Code:

public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.println("^ \t ^ \t ^");
System.out.println("//|/ \t /|/ \t /|/");
System.out.println("((&)) \t .((^)). \t ((&))");
System.out.println("|.| \t (((^))) \t |.|");
System.out.println("|.| \t ((((^)))) \t |.|");
System.out.println("|.| \t (((((^))))) \t |.|");
System.out.println("|.| \t ((((^)))) \t |.|");
System.out.println("|.| \t (((^))) \t |.|");
System.out.println("|.| \t (((^))) \t |.|");
System.out.println(" {**********************}");
System.out.println("*|*******************
***********|**");
System.out.println(" | \t \t \t \t|");
System.out.println(" | \t \t \t \t|");
System.out.println(" | \t \t _{#}_ \t \t|");
System.out.println(" | \t \t {####} \t|");
System.out.println(" | \t \t \t \t|");
System.out.println(" | \t \t {######} \t|");
System.out.println(" | \t \t {######} \t|");
System.out.println(" | \t \t {######} \t|");
System.out.println(" | \t \t {######} \t|");
System.out.println(" | \t \t {######} \t|");
System.out.println(" | \t \t_{######}_ \t|");
System.out.println(" (@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@)");
System.out.println(" (++++++++++/===========++++++++)");
System.out.println("[%%%%%%%%%%/==============/%%%%%]");
System.out.println("[^^^^^^^^^^/============/^^^^^^^]");}

2) Write a JAVA program, which receives the input of two integer numbers, operation (+,- ,*,/,%, power, square-root and factorial) and compute arthematic operations. Generate a menu for operations and ask user after every operation if they want to do another. (Hint use switch case).
Output:
firstImage

Source Code:

public static void main(String[] args){
int num1,num2,op;
double ans;
char res;
boolean con = true;
Scanner input = new Scanner(System.in);
do{
System.out.println("Select operator:\n1)Addition\n2)Subtraction\n
3)Multiplication\n4)Division\n5)Reminder
\n6)Power\n7)Square Root\n8)Factorial\n");
op = input.nextInt();
switch(op){
case 1:
System.out.println("Enter number 1:");
num1 = input.nextInt();
System.out.println("Enter number 2:");
num2 = input.nextInt();
ans = num1+num2;
System.out.println(num1+" + "+num2+" = "+ans);
break;
case 2:
System.out.println("Enter number 1:");
num1 = input.nextInt();
System.out.println("Enter number 2:");
num2 = input.nextInt();
ans = num1-num2;
System.out.println(num1+" - "+num2+" = "+ans);
break;
case 3:
System.out.println("Enter number 1:");
num1 = input.nextInt();
System.out.println("Enter number 2:");
num2 = input.nextInt();
ans = num1*num2;
System.out.println(num1+" x "+num2+" = "+ans);
break;
case 4:
System.out.println("Enter number 1:");
num1 = input.nextInt();
System.out.println("Enter number 2:");
num2 = input.nextInt();
ans = (double)num1/(double)num2;
System.out.println(num1+" / "+num2+" = "+ans);
break;
case 5:
System.out.println("Enter number 1:");
num1 = input.nextInt();
System.out.println("Enter number 2:");
num2 = input.nextInt();
ans = num1%num2;
System.out.println(num1+" % "+num2+" = "+ans);
break;
case 6:
System.out.println("Enter number 1:");
num1 = input.nextInt();
System.out.println("Enter number 2:");
num2 = input.nextInt();
ans = Math.pow(num1,num2);
System.out.println(num1+" ^ "+num2+" = "+ans);
break;
case 7:
System.out.println("Enter number 1:");
num1 = input.nextInt();
ans = Math.sqrt(num1);
System.out.println(num1+" ^ 0.5 = "+ans);
break;
case 8:
System.out.println("Enter number 1:");
num1 = input.nextInt();
num2 = num1;
ans = 1;
do{
ans*=num1;
num1--;
}while(num1>0);
System.out.println(num2+"! = "+ans);
break;
default:
System.out.println("Invalid operation!");
break;}
System.out.println("try again? (y/n)");
res = input.next().charAt(0);
}while(res == 'y' || res == 'Y');}

3) Make a program in JAVA in which take no. of items, price of items and name of items as input from the user and give the discount according to the following conditions:
a) If from Bahria University give discount of 30%.
b) Else if the total amount is greater then 50,000 and less than 100,000 give discount of 20%.
c) Else if the total amount is greater then 100,000 give discount of 30%.
Output:
firstImage firstImage firstImage

Source Code:

public static void main(String[] args){
int n,q,price,total = 0;
double d = 1,dtotal;
String name;
char res;
Scanner input = new Scanner(System.in);
System.out.print("Enter number of items: ");
n = input.nextInt();
for(int i = 1; i<=n; i++){
System.out.println("\n\t\tItem "+i);
System.out.print("Enter name of item "+i+": ");
name = input.next();
System.out.print("Enter price of item "+i+": ");
price = input.nextInt();
System.out.print("Enter quantity of item "+i+": ");
q = input.nextInt();
total += (q*price);}
if(total > 50000 && total < 100000){
d = 0.8;}
else if(total >= 100000){
d = 0.7;}
System.out.print("\nAre you from BUKC? (y/n): ");
res = input.next().charAt(0);
if(res == 'y' || res == 'Y'){
d = 0.7;}
dtotal = total*d;
if(d == 1){
System.out.println("\nYour total is :$"+dtotal);
}else{
System.out.println("\nTotal :$"+total);
System.out.println("Discount :$"+(total-dtotal));
System.out.println("Discounted Total :$"+dtotal);}}

4) Write a JAVA program which will implement the following formulae using methids.

a. Automobile Tire Pressure:
P = 0.37m(T + 460)/V P = pressure in psi.
V = volume in cubic feet
m = mass of air in pounds
T = temperature in Fahrenheit

b. Pulley formulas
i) calculate the speed of one pulley if there are 2 pulleys connected with a belt:
RPM2 = diameter1/diameter2 * RPM1
ii) calculate the amount of weight that can be lifted with a multiple pulley system: weight lifted = force exerted * number of up ropes

c. The body mass index (BMI), is a heuristic proxy for human body fat based on an individual's weight and height. BMI does not actually measure the percentage of body fat. We will be building a BMI calculator method. Body mass index (BMI) is computed using the the formula,

Where mass is the subject's weight in pounds (lb) and height is the height in inches (in). The value 703 is a factor to convert BMI to a value that matches the original BMI calculations done in metric units (i.e. kilograms-meters).
Output:
firstImage firstImage
firstImage firstImage

Source Code:

public static void main(String[] args){
int op;
boolean con = true;
Scanner input = new Scanner(System.in);
System.out.println("Select 1 option:\n1)Tyre pressure\n2)Pulley\n3)BMI");
op = input.nextInt();
switch(op){
case 1:
int m,t,v;
System.out.print("\nEnter mass of air in pounds: ");
m = input.nextInt();
System.out.print("Enter temperature in fahrenheit: ");
t = input.nextInt();
System.out.print("Enter volume in cubic feet: ");
v = input.nextInt();
calPressure(m,t,v);
break;
case 2:
do{
System.out.println("\nSelection 1 option:\n1)Speed\n2)Liftable weight");
op = input.nextInt();
if(op == 1){
int rpm1,dm1,dm2;
System.out.print("Enter speed of pulley 1 in RPM: ");
rpm1 = input.nextInt();
System.out.print("Enter diameter in meter of pulley 1: ");
dm1 = input.nextInt();
System.out.print("Enter diameter in meter of pulley 2 :");
dm2 = input.nextInt();
calPulleySpeed(rpm1,dm1,dm2);}
else if(op == 2){
int force,n;
System.out.print("Enter force exerted: ");
force = input.nextInt();
System.out.print("Enter number of ropes: ");
n = input.nextInt();
calLWeight(force,n);
}else{
System.out.println("\nInvalid option");
con = false;}
}while(!con);
break;
case 3:
int w,h;
System.out.print("\nEnter mass in pounds: ");
w = input.nextInt();
System.out.print("Enter height in inches: ");
h = input.nextInt();
calBMI(w,h);
break;
default:
System.out.println("Invalid option selected!");
break;}}
public static void calPressure(int m, int t, int v){
double p;
p = (0.37*m*(t+460))/v;
System.out.println("Tire pressure in = "+p+" Psi");}
public static void calBMI(int w, int h){
double bmi;
bmi = ((double)w/(h*h))*703;
System.out.println("\nBMI : "+bmi);}
public static void calPulleySpeed(int rpm1 , int dm1, int dm2){
double rpm2;
rpm2 = ((double)dm1/dm2)*rpm1;
System.out.println("\nSpeed of pulley 2: "+rpm2+" RPM");}
public static void calLWeight(int f, int n){
double lw;
lw = f*n;
System.out.println("\nTotal Liftabele Weight: "+lw+" N");}

2. Classes & Objects


1) Create a class student which contains the basic data about the student that takes the basic student data and displays it by using display method. An option of update is being provided to the user if he/she want to update the data, the required data being updated.
Output:
firstImage

Source Code:
Main Class:

import java.util.Scanner;
public class Task_2 {
public static void main(String[] args) {
char res;
boolean update = false;
Scanner input = new Scanner(System.in);
Student data = new Student();
System.out.print("Input student info?(y/n): ");
res = input.next().charAt(0);
if(res == 'y'){
System.out.print("\nEnter name :");
String name = input.next();
System.out.print("Enter subject :");
String subject = input.next();
System.out.print("Enter age :");
int age = input.nextInt();
data.studentSetter(name,subject,age);
update = true;}
if(update){
System.out.print("Update?(y/n): ");
res = input.next().charAt(0);
if(res == 'y'){
data.studentUpdate();}}}}

Sub Class:

import java.util.*;
public class Student {
String name = "null", subject = "null";
int age = 0;
Scanner input = new Scanner(System.in);
public void studentSetter(String name, String subject, int age){
this.name = name;
this.subject = subject;
this.age = age;
System.out.println("\nSuccess\n");}
public void studentUpdate(){
System.out.println("\nName : "+this.name+"\nSubject : "+this.subject+"\nAge : "+this.age);
System.out.print("Enter name: ");
this.name = input.next();
System.out.print("Enter subject: ");
this.subject = input.next();
System.out.print("Enter age: ");
this.age = input.nextInt();
System.out.println("\nSuccess\n");}}

2) Create a class “computer” which contains specifications of computer, the program shall ask the user does he/she wants to open the system, if the user press “yes” then the system starts shows the initial loading and then displays the basic configuration of a system (by calling the method of display () , update option is being provided by the user, values of the specified items are being updated once user decides to update that item.
Output:
firstImage

Source Code:
Main Class:

import java.util.Scanner;
public class Task_2 {
public static void main(String[] args) {
char res;
boolean sys = false;
Scanner input = new Scanner(System.in);
Computer comp = new Computer();
System.out.print("\nOpen system?(y/n) : ");
res = input.next().charAt(0);
if(res == 'y'){
comp.Display();
sys = true;
}else{
System.out.println("\nBye");}
if(sys){
System.out.print("Do you want to update specifications?(y/n) : ");
res = input.next().charAt(0);
if(res == 'y'){
System.out.println("\nWhat you want to update?\n1)Processor\n2)Graphics Card\n3)Generation\n4)RAM");
res = input.next().charAt(0);
switch (res){
case '1':
comp.updateCpu();
break;
case '2':
comp.updateGpu();
break;
case '3':
comp.updateGen();
break;
case '4':
comp.updateRam();
break;
default:
System.out.println("Invalid option selected");
sys = false;}
}else{
System.out.println("\nBye");}
if(sys){
comp.Display();}}}}

Sub Class:

import java.util.Scanner;
public class Computer {
String cpu = "Intel", gpu = "AMD";
int gen = 5, ram = 8;
Scanner input = new Scanner(System.in);
public void Display(){
System.out.println("\nLoading...\n");
System.out.println("Processor : "+cpu+"\t\tGraphics card : "+gpu+"\nGeneration : "+gen+"\t\tRAM : "+ram+"\n");}
public void updateCpu(){
System.out.print("Enter new Processor : ");
this.cpu = input.next();
System.out.println("Success!");}
public void updateGpu(){
System.out.print("Enter new Graphics Crad : ");
this.gpu = input.next();
System.out.println("Success!");}
public void updateGen(){
System.out.print("Enter new Generation : ");
this.gen = input.nextInt();
System.out.println("Success!");}
public void updateRam(){
System.out.print("Enter new RAM : ");
this.ram = input.nextInt();
System.out.println("Success!");}}

3) Create a class of Employee which contains basic information about an employee, employee name, father’s name and salary etc are being displayed by the display method and the salary of employees or the designation of the employees are being set/updated as per need.
Output:
firstImage

Source Code:
Main Class:

import java.util.Scanner;
public class Task_2 {
public static void main(String[] args) {
String name,fname,desig;
int sal;
char res;
boolean upd = false;
Scanner input = new Scanner(System.in);
Employee data1 = new Employee();
System.out.print("Enter details of employee 1:\nName :");
name = input.next();
System.out.print("Father Name : ");
fname = input.next();
System.out.print("Designation : ");
desig = input.next();
System.out.print("Salary : ");
sal = input.nextInt();
data1.setEmployee(name,fname,desig,sal);
data1.display();
System.out.print("\nDo you want to update Salary(s) or Designation(d) of Employee?(s/d/n) : ");
res = input.next().charAt(0);
if(res == 's'){
System.out.print("\nEnter new Salary : ");
sal = input.nextInt();
data1.updateSal(sal);
upd = true;
}else if(res == 'd'){
System.out.print("\nEnter new Designation : ");
desig = input.next();
data1.updateDesig(desig);
upd = true;
}else{
System.out.println("\n Bye");}
if(upd){
data1.display();}}}

Sub Class:

import java.util.Scanner;
public class Employee {
String name = "", fname = "", desig = "";
int sal = 0;
public void setEmployee(String name, String fname, String desig, int sal){
this.name = name;
this.fname = fname;
this.desig = desig;
this.sal = sal;
System.out.println("\nSuccess");}
public void display(){
System.out.println("\n\t\tEmployee\t\t\nName : "+name+"\tFather Name : "+fname+"\nDesignation : "+desig+"\tSalary : "+sal+"\n");}
public void updateDesig(String desig){
this.desig = desig;
System.out.println("\nSuccess");}
public void updateSal(int sal){
this.sal = sal;
System.out.println("\nSuccess");}}

4) Create a class of Automobile which contains specifications of a car, check whether the car is in - ON/start state if not them asks the user if he/she want to start the car, If the car is already in start state then first display the current status of the car which includes the horse power, color, made, engine type etc. providing an option to the user if he/she wants to update any of the mentioned part from the car, if user selects “YES” then it is updated according to the need of the user, else the program will be ended.
Output:
firstImage

Source Code:
Main Class:

import java.util.Scanner;
public class Task_2 {
public static void main(String[] args) {
String color,made,et;
int hp;
char res;
boolean upd = false;
Automobile car = new Automobile();
Scanner input = new Scanner(System.in);
System.out.print("Is car on?(y/n) : ");
res = input.next().charAt(0);
if(res == 'y'){
car.display();
}else{
upd = true;}
if(upd){
upd = false;
System.out.print("\nStart car? (y/n) : ");
res = input.next().charAt(0);}
if(res == 'y'){
System.out.print("\nDo you want to update any info of car? (y/n) : ");
res = input.next().charAt(0);
if(res == 'y'){
System.out.println("\nWhat do you want to update?\n1)Made\n2)Color\n3)Engine Type\n4)Horse Power");
res = input.next().charAt(0);
switch (res){
case '1':
System.out.print("\nEnter new Made : ");
made = input.next();
car.updateMade(made);
upd = true;
break;
case '2':
System.out.print("\nEnter new Color : ");
color = input.next();
car.updateColor(color);
upd = true;
break;
case '3':
System.out.print("\nEnter new Engine Type : ");
et = input.next();
car.updateEt(et);
upd = true;
break;
case '4':
System.out.print("\nEnter new Horse Power : ");
hp = input.nextInt();
car.updateHp(hp);
upd = true;
break;
default:
System.out.println("\nInvalid Option!");;
break;}}}
if(upd){
car.display();}
System.out.println("\nByee");}}

Sub Class:

public class Automobile {
String made = "Toyota",color = "Black", enginetype = "Petrol";
int hp = 120;
public void display(){
System.out.println("Made : "+made+"\t\tEngine Type : "+enginetype+"\nColor : "+color+"\t\tHorse Power : "+hp+"\n");}
public void updateMade(String made){
this.made = made;
System.out.println("\nSuccess");}
public void updateColor(String color){
this.color = color;
System.out.println("\nSuccess");}
public void updateEt(String et){
this.enginetype = et;
System.out.println("\nSuccess");}
public void updateHp(int hp){
this.hp = hp;
System.out.println("\nSuccess");}}

5) Implement a class Car, that has the following characteristics:
a) Brandname
b) PriceNew, which represents the price of the car when it was new
c) Color and
d) Odometer,which is milo meter shows number of milage travelled by car
The class should have:
A. A method getPriceAfterUse() which should return the price of the car after being used according to the following formula: car price after being used=priceNew*(1-(odometer/600,00))
B. A method updateMilage (double travelled distance) that changes the current state of the car by increasing its milage, and
D. A method outputDetails() that will output to the screen all the information of the car, i.e. brandname, priceNew,price used,color and odometer.
Output:
firstImage

Source Code:
Main Class:

import java.util.Scanner;
public class Task_2 {
public static void main(String[] args) {
Car car = new Car();
Scanner input = new Scanner(System.in);
System.out.print("Enter the Brand of car : ");
String bname = input.next();
System.out.print("Enter the Color of car : ");
String color = input.next();
System.out.print("Enter the Price of car brand new: ");
int pnew = input.nextInt();
System.out.print("Enter Mileage of car : ");
int mileage = input.nextInt();
car.setCar(bname,color,pnew,mileage);
System.out.println("\nPrice of car after running "+mileage+"Km its worth is : "+car.getPriceAfterUse()+"$");
System.out.print("Distance traveled : ");
int dis = input.nextInt();
car.updateMileage(dis);
car.outputDetails();}}

Sub Class:

public class Car {
String bname = "",color = "";
int pnew, odometer;
double pused;
public void setCar(String bname, String color, int pnew, int mileage){
this.bname = bname;
this.color = color;
this.pnew = pnew;
this.odometer = mileage;}
public double getPriceAfterUse(){
this.pused = pnew*(1-((double)odometer/600000));
return this.pused;}
public void updateMileage(int dis){
this.odometer += dis;
getPriceAfterUse();}
public void outputDetails(){
System.out.println("\n\t\tDetails\nBrand : "+this.bname+"\tColor : "+this.color+"\nPrice New : "+this.pnew+"$\tPrice Used : "+this.pused+"$\nOdometer : "+this.odometer+"Km");}}

3. Access Modifiers


1) Write a program to display the radius and color of a circle in Java. Use private Access modifiers for member variables of circle class and accessor and mutator methods to get and set the member values.
Output:
firstImage

Source Code:
Main Class

package task3;
import java.util.Scanner;
public class Task3 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
circle c=new circle();
System.out.print(" Enter Color of a Circle: ");
String color=input.next();
c.setcolor(color);
System.out.print(" Enter radius of a Circle");
double radius=input.nextDouble();
c.setradius(radius);
System.out.println(" *********************************");
System.out.println("The Color of a Circle is " + c.getcolor());
System.out.println("The radius of a Circle is: " + c.getradius());}}

Sub Class

package task3;
public class circle {
private String color;
private double radius;
public void setcolor(String color){
this.color=color;}
public String getcolor(){
return color;}
public void setradius(double radius){
this.radius=radius;}
public double getradius(){
return radius;}}

2) Create a class sphere and use getters and setters to set its radius and height. Also calculate surface area and volume of the sphere.

Source Code

Main Class

package com.mycompany.task33;
public class Task33 {
public static void main(String[] args) {
sphere c=new sphere();
c.setradius(8);
System.out.println("Radius is " + c.getradius());
c.setheight(10);
System.out.println(" Height is " + c.getheight());
System.out.println("The Volume is "+ c.volume());
System.out.println("The Surface Area is "+ c.surfacearea());}}

Sub Class

package com.mycompany.task33;
public class sphere {
private int radius;
private int height;
public void setradius(int radius){
this.radius=radius;}
public int getradius(){
return radius;}
public void setheight(int height){
this.height=height;}
public int getheight(){
return height;}
public double volume(){
return 3.142*radius*radius*height;}
public double surfacearea(){
return 2*3.142*radius*radius+2*3.142*radius*height;}}

3) Consider a computer system whose name, type, processor specification, ram, hard disk drives, mother board, optical drive etc are its member variables and its desired values cannot be accessed directly. They are entered by the user in a get method (that takes information from the user) and the displays the inputted information via display method. The user shall be asked to change any of the provided information if he/she agrees to change the information then new values shall be asked from the user.
Output:
firstImage
Source Code:
Main Class

package task3;
import java.util.Scanner;
public class Task3 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
computer c=new computer();
System.out.print(" Enter Name of a Computer: ");
String name=input.next();
c.setname(name);
System.out.print(" Enter Type of a Computer: ");
String type=input.next();
c.settype(type);
System.out.print(" Enter Processor Specification of a Computer: ");
String processor=input.next();
c.setprocessor(processor);
System.out.print(" Enter Ram of a Computer of a Computer: ");
int ram=input.nextInt();
c.setram(ram);
System.out.print(" Enter Hard Disk Drives of a Computer: ");
int hard_disk=input.nextInt();
c.sethard_disk(hard_disk);
System.out.print(" Enter Mother Board of a Computer: ");
String motherboard=input.next();
c.setmotherboard(motherboard);
System.out.print(" Enter Optical Drive of a Computer: (yes or no) ");
String optical=input.next();
c.setoptical(optical);
System.out.println("\n ******************* Computer Specification ********************");
System.out.println("The Name of a Computer is: "+ c.getname());
System.out.println("The Type of a Computer is: "+ c.gettype());
System.out.println("The Processor Specification of a Computer is: "+ c.getprocessor());
System.out.println("The Ram of a Computer is: "+ c.getram());
System.out.println("The Hard Disk Drives of a Computer is: "+ c.gethard_disk());
System.out.println("The Mother Board of a Computer is: "+ c.getmotherboard());
System.out.println("The Optical Drive of a Computer is: "+ c.getoptical());
System.out.println("\n Do you want to update information of computer again?");
String answer=input.next();
if(answer.equals("yes")){
System.out.print(" Enter Name of a Computer: ");
String name1=input.next();
c.setname1(name1);
System.out.print(" Enter Type of a Computer: ");
String type1=input.next();
c.settype1(type1);
System.out.print(" Enter Processor Specification of a Computer: "); String processor1=input.next();
c.setprocessor1(processor1);
System.out.print(" Enter Ram of a Computer of a Computer: ");
int ram1=input.nextInt();
c.setram1(ram1);
System.out.print(" Enter Hard Disk Drives of a Computer: ");
int hard_disk1=input.nextInt();
c.sethard_disk1(hard_disk1);
System.out.print(" Enter Mother Board of a Computer: ");
String motherboard1=input.next();
c.setmotherboard1(motherboard1);
System.out.println(" Enter Optical Drive of a Computer: (yes or no) ");
String optical1=input.next();
c.setoptical1(optical1);
System.out.println("\n ******************* Updated Computer Specification ********************");
System.out.println("The Name of a Computer is: "+ c.getname1());
System.out.println("The Type of a Computer is: "+ c.gettype1());
System.out.println("The Processor Specification of a Computer is: "+ c.getprocessor1());
System.out.println("The Ram of a Computer is: "+ c.getram1());
System.out.println("The Hard Disk Drives of a Computer is: "+ c.gethard_disk1());
System.out.println("The Mother Board of a Computer is: "+ c.getmotherboard1());
System.out.println("The Optical Drive of a Computer is: "+ c.getoptical1());}
else{
System.out.println(" Thank You");}}}

Sub Class

package task3;
public class computer {
private String name;
private String type;
private String processor;
private int ram;
private int hard_disk;
private String motherboard;
private String optical;
public void setname(String name){
this.name=name;}
public String getname(){
return name;}
public void settype(String type){
this.type=type;}
public String gettype(){
return type;}
public void setprocessor(String processor){
this.processor=processor;}
public String getprocessor(){
return processor;}
public void setram(int ram){
this.ram=ram;}
public int getram(){
return ram;}
public void sethard_disk(int hard_disk){
this.hard_disk=hard_disk;}
public int gethard_disk(){
return hard_disk;}
public void setmotherboard(String motherboard){
this.motherboard=motherboard;}
public String getmotherboard(){
return motherboard;}
public void setoptical(String optical){
this.optical=optical;}
public String getoptical(){
return optical;}
private String name1;
private String type1;
private String processor1;
private int ram1;
private int hard_disk1;
private String motherboard1;
private String optical1;
public void setname1(String name){
this.name1=name1;}
public String getname1(){
return name1;}
public void settype1(String type){
this.type1=type1;}
public String gettype1(){
return type1;}
public void setprocessor1(String processor){
this.processor1=processor1;}
public String getprocessor1(){
return processor1;}
public void setram1(int ram1){
this.ram1=ram1;}
public int getram1(){
return ram1;}
public void sethard_disk1(int hard_disk1){
this.hard_disk1=hard_disk1;}
public int gethard_disk1(){
return hard_disk1;}
public void setmotherboard1(String motherboard){
this.motherboard1=motherboard1;}
public String getmotherboard1(){
return motherboard1;}
public void setoptical1(String optical){
this.optical1=optical1;}
public String getoptical1(){
return optical1;}}

4. Constructors


1) Write a program using the concepts of a default constructor. Consider a computer system whose name, type, processor specification, ram, hard disk drives, mother board, optical drive etc, in a default constructor, desired values are entered by the user in a get method (that takes information from the user) and the displays the inputted information via display method. The user shall be asked to change any of the provided information if he/she agrees to change the information then new values shall be asked from the user.
Output:
firstImage firstImage
firstImage firstImage

Source Code:

2) Use constructor overloading to initialize a rectangle of length 4 and breadth 5 for using custom parameters.
Output:
firstImage

Source Code:
Main Class

Sub Class

3) Use Constructor to set the radius and height of cylinder and calculate surface area and Volume of cylinder.
Output:
firstImage

Source Code:
Main Class

package task4;
public class Task4 {
public static void main(String[] args) {
cylinder c=new cylinder();
System.out.println("Volume is " + c.volume());
System.out.println("Surface is " + c.surfacearea());}}

Sub Class

package task4;
public class cylinder {
private int radius;
private int height;
public cylinder(){
radius=15;
height=220;}
public double volume(){
return 3.142*radius*radius*height;}
public double surfacearea(){
return 2*3.142*radius*radius+2*3.142*radius*height;}}

4) Design then implement a class to represent a Flight. A Flight has a flight number, a source, a destination and a number of available seats. This should be implemented using proper access modifier. The class should have:
a. A constructor to initialize the 4 instance variables. You have to shorten the name of the source and the destination to 3 characters only if it is longer than 3 characters by a call to the method in the ‘h’ part. b. An overloaded constructor to initialize the flight number and the number of available seats instance variables only.
(NOTE: Initialize the source and the destination instance variables to empty string, i.e." ")
c. An overloaded constructor to initialize the flight number instance variable only.
(NOTE: Initialize the source and the destination instance variables to empty string; and the number of available seats to zero)
d. A method public void reserve(int numberOfSeats) to reserve seats on the flight. (NOTE: You have to check that there is enough number of seats to reserve)
e. A method public void cancel(int numberOfSeats) to cancel one or more reservations
f. A toString method to easily return the flight information:
g. An equals method to compare 2 flights.
(NOTE: 2 Flights considered being equal if they have the same flight number)
Write a test class for the Flight class you wrote. You should try to use all the methods you wrote.
Output:
firstImage firstImage
firstImage firstImage

Source Code:

5. Static Classes & Members


1) Write a program to calculate area of rectangle by using static method.Use parameterized constructor to assign width and height to the instance. Use Output area method which uses the static method to calculate the area.
Output:
firstImage

Source Code:
Main Class:

public class Main {
public static void main(String[] args){
Rectangle r = new Rectangle(5,6);
r.displayArea();}}

Sub Class:

public class Rectangle {
Scanner input = new Scanner(System.in);
private static int area;
private static int bass,height;
public Rectangle(int bass,int height){
this.bass = bass;
this.height = height;}
public static void displayArea(){
area = bass*height;
System.out.println("The area is: "+area);}}

2) Write a program to display Name, Enrollment Number, University Name and ,Semester of students that are from same university and semester using static fields and methods.(Hint: first set the university name and semester:
Then use static variable counter to get unique roll numbers
Output:
firstImage

Source Code:
Main Class:

public class Main {
public static void main(String[] args){
University.setUni("Bahria");
University.setSem("3");
University u = new University();
u.setData("hamza","21");
u.displayData();}}

Sub Class:

public class University {
private static String university,semester;
private String name,age;
private static int enrNum = 10;
public static void setUni(String uni){
university = uni;}
public static void setSem(String sem){
semester = sem;}
public void setData(String name, String age){
this.name = name;
this.age = age;}
public static int setenrNum(){
enrNum++;
return enrNum;}
public void displayData(){
System.out.println("Name : "+name+"\nUniversity : "+University.university+"\nSemester : "+University.semester+"\nAge : "+age+"\nEnrollment Number : "+University.setenrNum());}}

3) Write a static method called printNTimes that takes an integer n and a string (in that order) as its parameters and prints the string n times.
Output:
firstImage

Source Code:
Main Class:

import java.util.Scanner;
public class Main {
public static void main(String[] args){
University.prinNTimes(5,"Static method"); }}

Sub Class:

import java.util.Scanner;
public class University {
public static String insult( int age,String name){
if(age>= 1 && age<=10){
return name+" is sweet";
}else if(age>10 && age <= 17){
return name+" is not dweebs";
}else if(age>17 && age <=20){
return name+" is illigal";
}else if(age == 21){
return name+" just became legal";
}else if(age >21 && age <=29){
return name+" is suffering";
}else if(age > 29){
return name+" is dying";
}else{
return name+" has stupid age";}}}

4) Write a static method called insult that has two paramaters, a String which represents a person’s name and an integer which represents the persons age. This method should create and return a String which is a personal insult based on the value of the argument age that was passed. Use the following age cuttoffs (or variations of your choosing) for creating your insults.
Output:
firstImage

Source Code:
Main Class:

import java.util.Scanner;
public class Main {
public static void main(String[] args){
System.out.println(University.insult(87,"Jack ma"));
System.out.println(University.insult(5,"Jelly beans"));
System.out.println(University.insult(15,"Teen Tweet"));}}

Sub Class:

import java.util.Scanner;
public class University {
public static String insult( int age,String name){
if(age>= 1 && age<=10){
return name+" is sweet";
}else if(age>10 && age <= 17){
return name+" is not dweebs";
}else if(age>17 && age <=20){
return name+" is illigal";
}else if(age == 21){
return name+" just became legal";
}else if(age >21 && age <=29){
return name+" is suffering";
}else if(age > 29){
return name+" is dying";
}else{
return name+" has stupid age";}}}

5) Write a static method called greetMe that greets you. The method should issue a prompt asking for your name, display a polite (or not so polite) greeting message and then prompt you to enter your age.
Output:
firstImage

Source Code:
Main Class:

import java.util.Scanner;
public class Main {
public static void main(String[] args){
University.greetMe();}}

Sub Class:

import java.util.Scanner;
public class University {
static Scanner input = new Scanner(System.in);
public static void greetMe(){
System.out.print("Enter your name : ");
String name = input.next();
System.out.print("Hello hamza u come again.\nTell me your age : ");
int age = input.nextInt();}}

6. Function Overloading


1) Write a program which contains a class ‘Calculator’ contains multiple sum method by using method overloading concept.
Output:
firstImage

Source Code:
Main Class:

public class Main {
public static void main(String[] args){
Calculator c = new Calculator();
System.out.println(c.sum(2,3));
System.out.println(c.sum(2,3,4));}}

Sub Class:

public class Calculator {
public int sum(int n1, int n2){
return n1+n2;}
public int sum(int n1, int n2, int n3){
return n1+n2+n3;}}

2) Create a class to print the area of a square and a rectangle. The class has two methods with the same name but different number of parameters. The method for printing area of rectangle has two parameters which are length and breadth respectively while the other method for printing area of square has one parameter which is side of square.
Output:
firstImage

Source Code:
Main Class:

public class Main {
public static void main(String[] args){
Calculator c = new Calculator();
System.out.println("Area of square = "+c.calArea(5));
System.out.println("Area of rectangle = "+c.calArea(5,6));}}

Sub Class:

public class Calculator {
public int calArea(int n1, int n2){
return n1*n2;}
public int calArea(int n1){
return n1*n1;}}

3) Create a class 'Student' with three data members which are name, age and address. The constructor of the class assigns default values name as "unknown", age as '0' and address as "not available". It has two members with the same name 'setInfo'. First method has two parameters for name and age and assigns the same whereas the second method takes has three parameters which are assigned to name, age and address respectively. Print the name, age and address of 4 students.
Output:
firstImage

Source Code:
Main Class:

public class Main {
public static void main(String[] args){
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
Student s4 = new Student();
s1.setInfo("Rizvi","21","karachi");
s2.setInfo("Shoaib","20","China");
s3.setInfo("Akhter","19");
s1.print();
s2.print();
s3.print();
s4.print();}}

Sub Class:

public class Student {
private String name,age,adress;
Student(){
name = "unknown";
age = "0";
adress = "not available";}
public void setInfo(String name, String age){
this.name = name;
this.age = age;}
public void setInfo(String name, String age, String adress){
this.name = name;
this.age = age;
this.adress = adress;}
public void print(){
System.out.println("\nName : "+name+"\tAge : "+age+"\nAdress : "+adress);}}

4) Implement the Circle class to overload the + operator so that you can add two Circle objects. Adding two Circle object should give another Circle whose radius is the sum of the radii of the two Circle objects.
Output:
firstImage

Source Code:
Main Class:

using System;
namespace Task_6{
class Program{
static void Main(string[] args)
{
Circle c1 = new Circle(5);
Circle c2 = new Circle(8);
Console.WriteLine("Radius of circle 1 : " + c1.displayRadius());
Console.WriteLine("Radius of circle 2 : " + c2.displayRadius());
Circle c3 = c1 + c2;
Console.WriteLine("Radius of circle 1+2 : " + c3.displayRadius());}}}

Sub Class:

using System;
namespace Task_6{
class Circle{
int radius;
public Circle(){
radius = 0;}
public Circle(int radius){
this.radius = radius;}
public string displayRadius(){
return string.Format("Radius : {0}", radius);}
public static Circle operator +(Circle c1, Circle c2){
Circle c3 = new Circle();
c3.radius = c2.radius + c1.radius;
return c3;}}}

5) Implement the Rectangle class to overload the + operator so that you can add two Rectangle objects. Adding two Rectangle objects should give another Rectangle object whose length is the sum of the lengths of the two Rectangle objects and whose breadth is the sum of the breadths of the two Rectangle objects.
Output:
firstImage

Source Code:
Main Class:

using System;
namespace Task_6{
class Program{
static void Main(string[] args){
Rectangle r1 = new Rectangle(5, 6);
Rectangle r2 = new Rectangle(7,8);
r1.PrintRectangle();
r2.PrintRectangle();
Rectangle r3 = r1 + r2;
r3.PrintRectangle();}}}

Sub Class:

using System;
namespace Task_6{
class Rectangle{
int breadth, height;
public Rectangle(){
breadth = 0;
height = 0;}
public Rectangle(int breadth, int height){
this.breadth = breadth;
this.height = height;}
public void PrintRectangle(){
Console.WriteLine("\nBreadth = {0}\theight = {1}",breadth,height);}
public static Rectangle operator +(Rectangle r1, Rectangle r2){
Rectangle r3 = new Rectangle();
r3.breadth = r1.breadth + r2.breadth;
r3.height = r1.height + r2.height;
return r3;}}}

6) Write a class Time which represents time. the class should have three fields for hours, minutes and seconds. It should have constructor to initialize the hours, minutes and seconds. A method printTime() to print the current time. Overload the following operators: plus operator (+) (add two time objects based on 24 hour clock) and (compare two time objects)
Output:
firstImage

Source Code:
Main Class:

using System;
namespace Task_6{
class Program{
static void Main(string[] args){
DateTime dt = DateTime.Now;
Time t1 = new Time(dt.Hour,dt.Minute,dt.Second);
Time t2 = new Time(15,45,7);
Time t3 = t1+ t2;
t1.printTime();
t2.printTime();
t3.printTime();
if (t1 Console.WriteLine("Time 1 is small");}
else{
Console.WriteLine("Time 2 is small");}}}}

Sub Class:

using System;
namespace Task_6{
class Time{
int hours, minutes, seconds;
public Time(){
hours = 0;
minutes = 0;
seconds = 0;}
public Time(int hours, int minutes, int seconds){
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;}
public void printTime(){
Console.WriteLine("Time is : {0}h:{1}mm:{2}sec",hours,minutes,seconds);}
public static Time operator +(Time t1, Time t2){
Time t3 = new Time();
t3.hours = t1.hours + t2.hours;
t3.minutes = t1.minutes + t2.minutes;
t3.seconds = t1.seconds + t2.seconds;
if (t3.seconds > 60){
t3.minutes++;
t3.seconds -= 60;}
if (t3.minutes > 60){
t3.hours++;
t3.minutes -= 60;}
if (t3.hours > 24){
t3.hours -= 24;}
return t3; }
public static Boolean operator <(Time t1, Time t2){
if(t1.hours <= t2.hours && t1.hours!=t2.hours){
return true;}
else if(t1.minutes < t2.minutes && t1.minutes !=t2.minutes && t1.hours <=t2.hours){
return true;}
else if(t1.seconds<=t2.seconds && t1.seconds !=t2.seconds && t1.minutes <=t2.minutes && t1.hours>= t2.hours){
return true;}
return false; }
public static Boolean operator >(Time t1, Time t2){
if (t1.hours >= t2.hours && t1.hours != t2.hours){
return true;}
else if (t1.minutes >= t2.minutes && t1.minutes != t2.minutes && t1.hours >= t2.hours){
return true;}
else if (t1.seconds <= t2.seconds && t1.seconds !=t2.seconds && t1.minutes>= t2.minutes && t1.hours >= t2.hours){
return true;}
return false;}}}

7. Inheritance


1) Write the classes below containing the given instance variables and methods, following the inherited hierarchy.
Output:
firstImage

Source Code:
Main Class:

import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Enter the number which you want to compute the area");
System.out.print("(1) Triangle (2) Rectangle (3) Circle ? ");
switch (scan.nextInt()) {
case 1:
Triangle triangle = new Triangle();
System.out.print("Base: ");
triangle.setBase(scan.nextDouble());
System.out.print("Height: ");
triangle.setHeight(scan.nextDouble());
System.out.println("Area of triangle: " + triangle.getArea());
break;
case 2:
Rectangle rectangle = new Rectangle();
System.out.print("Width: ");
rectangle.setWidth(scan.nextDouble());
System.out.print("Height: ");
rectangle.setHeight(scan.nextDouble());
System.out.println("Area of rectangle: " + rectangle.getArea());
break;
case 3:
Circle circle = new Circle();
System.out.print("Radius: ");
circle.setRadius(scan.nextDouble());
System.out.println("Area of circle: " + circle.getArea());
break;
default:
System.out.println("What do u mean?");}}}}

Parent Class Shape:

public class Shapes {
protected double area;
public Shapes(){
area = 0;}
public double getArea(){
return this.area;}
public void onAreaChange() {}}

Child Class Cirlce:

public class Circle extends Shapes{
private double radius;
private double pi;
public Circle(){
radius = 0;
pi = Math.PI;}
public void setRadius(double radius){
this.radius = radius;
onAreaChange();}
public void onAreaChange(){
this.area = pi*(radius*radius);}}

Child Class Triangle:

public class Triangle extends Shapes{
private double height;
private double base;
public Triangle(){
height = 0;
base = 0;}
public void setHeight(double height){
this.height = height;
onAreaChange();}
public void setBase(double base){
this.base = base;
onAreaChange();}
public void onAreaChange(){
this.area = 0.5*this.height*this.base;}}

Child Class Rectangle:

public class Rectangle extends Shapes{
private double height;
private double width;
public Rectangle(){
height = 0;
width = 0;}
public void setHeight(double height){
this.height = height;
onAreaChange();}
public void setWidth(double width){
this.width = width;
onAreaChange();}
public void onAreaChange(){
this.area = this.height * this.width;}}

2) Write a program that inherits a class named Alien and Pirates from a parent class Human. The human class has its own features like, Human can sleep, walk, talk etc. the Alien and Pirates class inheriting these functionalities as well as they have their characteristics, thus explaining the concepts of inheritance.
Output:
firstImage

Source Code:
Main Class:

import java.util.PrimitiveIterator;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Human h = new Human();
Alien a = new Alien();
Pirate p = new Pirate();
System.out.println("\nHumans can do this:");
h.displayFeature();
System.out.println("\nAlien can do this:");
a.displayFeature();
System.out.println("\nPirate can do this:");
p.displayFeature();}}

Parent Class Human:

public class Human {
String[] featureH = {"Sleep","Walk","Talk","Write","Read"};
public void displayFeature(){
for (String feaure:featureH) {
System.out.print(feaure+",");}}}

Child Class Alien:

public class Alien extends Human{
String[] featureA = {"big eye","super strength","10 legs"};
public void displayFeature(){
super.displayFeature();
for (String feaure:featureA) {
System.out.print(feaure+",");}}}

Child Class Pirate:

public class Pirate extends Human{
String[] featureP = {"eye patch", "Parrot", "Sword", "Welth"};
public void displayFeature(){
super.displayFeature();
for (String feaure:featureP) {
System.out.print(feaure+",");}}}

3) Write a program that inherits a class named Produce, Cosmetics, Pharmacy, electronic Item and Cloth from a parent class Item. The Item class has its own features like, name and price etc. the Child classes inheriting these functionalities as well as they have their characteristics, thus explaining the concepts of inheritance. Chile classes like Produce, can have their own child classes i.e., Frozen and Fresh.
Output:
firstImage

Source Code:
Main Class:

import java.util.PrimitiveIterator;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
Hair h = new Hair("SunSilk",500,"hair product","shampoo");
Facial f = new Facial("Vita",100,"Facial product","face mask");
Produce p = new Produce("Zinger",250,"Burger");
Electronic e = new Electronic("Samsung", 20000, "Mobile");
h.display();
f.display();
p.display();
e.display();}}

Parent Class Item:

public class Item {
String name;
int price;
public Item(){
this.name = "";
this.price = 0;}
public Item(String name, int price){
this.name = name;
this.price = price;}
public void display(){
System.out.println("\n\nName : "+name+"\tPrice : "+price);}}

Child Class Electronic:

public class Electronic extends Item{
String type;
// comp,tv
public Electronic(){
this.name = "";
this.price = 0;
this.type = "";}
public Electronic(String name, int price, String type){
this.name = name;
this.price = price;
this.type = type;}
public void display(){
super.display();
System.out.println("Type : "+type);}}

Child Class Produce:

public class Produce extends Item{
String type;
//burger,sandwitch
public Produce(){
this.name = "";
this.price = 0;
this.type = "";}
public Produce(String name, int price, String type){
this.name = name;
this.price = price;
this.type = type;}
public void display(){
super.display();
System.out.println("Type : "+type);}}

Child-Parent Class Cosmetics:

public class Cosmetics extends Item{
String type;
//Facial,Hair
public Cosmetics(){
this.name = "";
this.price = 0;
this.type = "";}
public Cosmetics(String name, int price, String type){
this.name = name;
this.price = price;
this.type = type;}
public void display(){
super.display();
System.out.println("Type : "+type);}}

Child Class Hair:

public class Hair extends Cosmetics{
String product;
//oil,shampoo
public Hair(){
this.name = "";
this.price = 0;
this.type = "";
this.product = "";}
public Hair(String name, int price, String type, String product){
this.name = name;
this.price = price;
this.type = type;
this.product = product;}
public void display(){
super.display();
System.out.print("Product : "+product);}}

Child Class Facial:

public class Facial extends Cosmetics{
String product;
//Face wash,Soap
public Facial(){
this.name = "";
this.price = 0;
this.type = "";
this.product = "";}
public Facial(String name, int price, String type, String product){
this.name = name;
this.price = price;
this.type = type;
this.product = product;}
public void display(){
super.display();
System.out.print("Product : "+product);}}

4) Write a program that inherits a class named Pakistani, BBQ, Chines, Fast Food and Beverages etc. from a parent class Cuisines. The Cuisines class has its own features like, name, quantity and price etc. the Child classes inheriting these functionalities as well as they have their characteristics, thus explaining the concepts of inheritance. Child classes can have their own child classes.
Output:
firstImage

Source Code:
Main Class:

import java.util.PrimitiveIterator;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
HotDrink hd = new HotDrink("Chai",2,50,"Bevrage","cup");
ColdDrink cd = new ColdDrink("Pepsi",1,150,"Bevrage","can");
FastFood ff = new FastFood("Zinger",1,250,"Burger");
BBQ bbq = new BBQ("Tikka",1,150,"Chicken");
Pakistani p = new Pakistani("Biryani",1,180,"Beef");
hd.display();
cd.display();
ff.display();
bbq.display();
p.display();}}

Parent Class:

public class Cuisines {
private String name;
private int quantity;
private double price;
public Cuisines(){
name = "";
quantity = 0;
price = 0;}
public Cuisines(String name, int quantity, double price){
this.name = name;
this.price = price;
this.quantity = quantity;}
public void display(){
System.out.print("\n\nName : "+this.name+"\tPrice : "+this.price+"\nQuantity : "+this.quantity);}}

Sub Class:

public class Pakistani extends Cuisines{
String foodtype;
Pakistani(){
super();
foodtype = "";}
Pakistani(String name, int quantity, double price, String type){
super(name,quantity,price);
this.foodtype = type;}
public void display(){
super.display();
System.out.print("\tFood-Type : "+foodtype);}}

Sub Class:

public class BBQ extends Cuisines{
String meattype;
BBQ(){
super();
meattype = "";}
BBQ(String name, int quantity, double price, String type){
super(name,quantity,price);
this.meattype = type;}
public void display(){
super.display();
System.out.print("\tMeat-Type : "+meattype);}}

Sub Class:

public class FastFood extends Cuisines{
String meal;
FastFood(){
super();
meal = "";}
FastFood(String name, int quantity, double price, String type){
super(name,quantity,price);
this.meal = type;}
public void display(){
super.display();
System.out.print("\tType : "+meal);}}

Sub Class:

public class Beverages extends Cuisines{
String drinktype;
public Beverages(){
super();
drinktype = "";}
public Beverages(String name, int quantity, double price, String type){
super(name,quantity,price);
drinktype = type;}
public void display() {
super.display();
System.out.print("\tType : "+drinktype);}}

Sub Class:

public class HotDrink extends Beverages{
String hotdrinksize;
HotDrink(){
super();
hotdrinksize = "";}
HotDrink(String name, int quantity, double price, String type, String hotdrinksize){
super(name,quantity,price,type);
this.hotdrinksize = hotdrinksize;}
public void display(){
super.display();
System.out.print("\nSize : "+hotdrinksize);}}

Sub Class:

public class ColdDrink extends Beverages{
String colddrinksize;
ColdDrink(){
super();
colddrinksize = "";}
ColdDrink(String name, int quantity, double price, String type, String colddrinksize){
super(name,quantity,price,type);
this.colddrinksize = colddrinksize;}
public void display(){
super.display();

5) Write code according to given guide.You must draw a class diagram first to start writing your code. Consider a superclass Items which models customer’s purchases. This class has:
• Two private instance variables name (String) and unitPrice (double).
• One constructor to initialize the instance variables.
• A default constructor to initialize name to “no item”, and unitPrice to 0. use this()
• A method getPrice that returns the unitPrice.
• Accessor and mutator methods.
• A toString method to return the name of the item followed by @ symbol, then the unitPrice.
Consider two subclasses WeighedItem and CountedItem. WeighedItem has an additional instance variable weight (double) in Kg while CountedItem has an additional variable quantity (int) both private.
• Write an appropriate constructor for each of the classes making use of the constructor of the superclass in defining those of the subclasses.
• Override getPrice method that returns the price of the purchasedItem based on its unit price and weight (WeighedItem), or quantity (CountedItem). Make use of getPrice of the superclass
• Override also toString method for each class making use of the toString method of the superclass in defining those of the subclasses.
toString should return something that can be printed on the receipt. For example
Banana @ 3.00 1.37 Kg 4.11 PKR (in case of WeighedItem class)
Pens @ 4.5 10 units 45 PKR (in case of CountedItem class)
Output:
firstImage

Source Code:
Main Class:

import java.util.PrimitiveIterator;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
WeighedItem w = new WeighedItem("Bnana",50,2.5);
CountedItem c = new CountedItem("Apple",10,5);
System.out.println(w.toString());
System.out.println(c.toString());}}

Parent Class Item:

public class Item {
private double unitprice;
private String name;
Item(){
unitprice = 0;
name = "";}
Item(String name, double unitprice){
this.unitprice = unitprice;
this.name = name;}
public void setUnitprice(double price){
this.unitprice = price;}
public void setName(String name){
this.name = name;}
public double getPrice(){
return this.unitprice;}
public String getName(){
return this.name;}
public String toString(){
return this.name+" @ "+this.unitprice;}}

Child Class WeighedItem:

public class WeighedItem extends Item{
private double weight;
public WeighedItem(){
weight = 0;}
public WeighedItem(String name, double price, double weight){
super(name,price);
this.weight = weight;}
public double getPrice(){
return super.getPrice()*this.weight;}
public String toString(){
return super.toString()+" "+this.weight+"Kg "+getPrice()+"PKR";}}

Child Class CountedItem:

public class CountedItem extends Item{
private int quantity;
public CountedItem(){
quantity = 0;}
public CountedItem(String name, double price, int quantity){
super(name,price);
this.quantity = quantity;}
public double getPrice(){
return super.getPrice()*this.quantity;}
public String toString(){
return super.toString()+" "+this.quantity+"Units "+getPrice()+"PKR";}}

8. Association, Composition & Composition


1) Write a program and create the objects of classes in class car to explain the concept of composition. Create several classes as engine, doors, capacity and wheel having their individual methods attributes. The object of these classes are created in a car class and they are set as public. The object of this car class is created in Main method and this with the help of this object we can call other classes as well and can use their functionalities and design UML class diagram.
Output:
firstImage

Source Code:
Main Class:

public class Main {
public static void main(String[] args){
Car car = new Car("Toyota","Petrol",1300,4,5,4);
car.display();}}

Class car:

public class Car {
private String name;
public Engine engine;
public Doors doors;
public Capacity capacity;
public Wheel wheel;
public Car(){
engine = new Engine();
doors = new Doors();
capacity = new Capacity();
wheel = new Wheel();}
public Car(String name,String type, int cc, int doorQuantity, int capacityQuantity, int wheelQuantity){
this.name = name;
engine = new Engine(cc,type);
doors = new Doors(doorQuantity);
capacity = new Capacity(capacityQuantity);
wheel = new Wheel(wheelQuantity);}
public String getName() {
return name;}
public void setName(String name){
this.name = name;}
public void display(){
System.out.println("Name : "+name+"\nCar has a Engine of "+engine.getCC()+"cc of Type : "+engine.getType()+"\nCar has "+doors.getQuantity()+" doors and "+wheel.getQuantity()+" wheels and it has capacity of "+capacity.getQuantity());}}

Class Engine:

public class Engine {
private int cc;
private String type;
public Engine(){
cc = 0;
type = "";}
public Engine(int cc, String type){
this.cc = cc;
this.type = type;}
public int getCC() {
return cc;}
public void setCC(int cc){
this.cc = cc;}
public String getType() {
return type;}
public void setType(String type){
this.type = type;}}

Class Doors:

public class Doors {
private int quantity;
public Doors(){
quantity = 0;}
public Doors(int quantity){
this.quantity = quantity;}
public int getQuantity() {
return quantity;}
public void setQuantity(int quantity){
this.quantity = quantity;}}

Class Wheels:

public class Wheel {
private int quantity;
public Wheel(){
quantity = 0;}
public Wheel(int quantity){
this.quantity = quantity;}
public int getQuantity() {
return quantity;}
public void setQuantity(int quantity){
this.quantity = quantity;}}

Class Capacity:

public class Capacity {
private int quantity;
public Capacity(){
quantity = 0;}
public Capacity(int quantity){
this.quantity = quantity;}
public int getQuantity() {
return quantity;}
public void setQuantity(int quantity){
this.quantity = quantity;}}

2) Write complete program for Flight's class, Time's class and Passenger's class with the concept of association and aggregation and design UML class diagram. Functions information also been given in the table below:
Output:
firstImage

Source Code:
Main Class:

import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args){
Pasanger p1 = new Pasanger(852);
Pasanger p2 = new Pasanger(456);
Pasanger p3 = new Pasanger(987);
Pasanger p4 = new Pasanger(741);
Pasanger p5 = new Pasanger(369);
Time t1 = new Time(5,30);
Time t2 = new Time(8,00);
List p = new ArrayList();
p.add(p1);
p.add(p2);
p.add(p3);
p.add(p4);
p.add(p5);
Flight f1 = new Flight("F-456", "Lahore","Hyderabad", t1, t2, p);
f1.display();}}

Class Flight:

import java.util.ArrayList;
import java.util.List;
public class Flight {
private String flightNo,destination,origin;
private Time arrival,departure;
private List pasanger;
public Flight(){
flightNo = "";
destination = "";
origin = "";
arrival = new Time();
departure = new Time();
pasanger = new ArrayList();}
public Flight(String flightNo, String destination,String origin, Time arrival, Time departure, List pasanger){
this.flightNo = flightNo;
this.destination = destination;
this.origin = origin;
this.arrival = arrival;
this.departure = departure;
this.pasanger = pasanger;}
public void setFlightNo(String flightNo){
this.flightNo = flightNo;}
public String getFlightNo(){
return flightNo;}
public void setDestination(String destination){
this.destination = destination;}
public String getDestination(){
return destination;}
public void display(){
System.out.println("Flight number : "+flightNo+"\nDestination : "+destination+"\nOrigin :"+origin+"\nArrival : "+arrival.getHoure()+":"+arrival.getMinute()+
"\nDeparture : "+departure.getHoure()+":"+departure.getMinute()+
"\nList of pasanger :");
int cnt = 0;
for (Pasanger p:pasanger) {
System.out.println(p.getId());
cnt++;}
System.out.println("Total pasanger : "+cnt);}}

Class Time:

public class Time {
private int houre,minute;
public Time(){
houre = 0;
minute = 0;}
public Time(int houre, int minute){
this.houre = houre;
this.minute = minute;}
public void setHoure(int houre){
this.houre = houre;}
public int getHoure(){
return houre;}
public void setMinute(int minute){
this.minute = minute;}
public int getMinute(){
return minute;}}

Class Pasanger:

public class Pasanger {
private int id;
public Pasanger(){
id = 0;}
public Pasanger(int id){
this.id = id;}
public void setId(int id){
this.id = id;}
public int getId(){
return id;}}

3) : A company manages many stores. Each Store contains many Products. Implement Product, Store and Company classes using association and aggrigation concepts and design UML class diagram.
Output:
firstImage

Source Code:
Main Class:

import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args){
Product p1 = new Product("Shampoo",400);
Product p2 = new Product("Comb",50);
Product p3 = new Product("Bag",1500);
Product p4 = new Product("Mobile",25000);
Product p5 = new Product("Apple",20);
List p = new ArrayList();
p.add(p1);
p.add(p2);
p.add(p3);
p.add(p4);
p.add(p5);
Store s1 = new Store("Hyderabad",p);
Store s2 = new Store("Karachi",p);
Store s3 = new Store("Quetta",p);
List s = new ArrayList();
s.add(s1);
s.add(s2);
s.add(s3);
Company c = new Company("Arslan Traders",s);
c.display();}}

Class Store:

import java.util.ArrayList;
import java.util.List;
public class Store {
private String name;
private List product;
public Store(){
name = "";
product = new ArrayList();}
public Store(String name, List product){
this.name = name;
this.product = product;}
public void setName(String name){
this.name = name;}
public String getName(){
return name;}
public List getProduct(){
return product;}}

Class Product:

public class Product {
private String name;
private double price;
public Product(){
name = "";
price = 0;}
public Product(String name, double price){
this.name = name;
this.price = price;}
public void setName(String name){
this.name = name;}
public void setPrice(double price){
this.price = price;}
public String getName(){
return name;}
public double getPrice(){
return price;}}

Class Company:

import java.util.ArrayList;
import java.util.List;
public class Company {
private String name;
private List stores;
public Company(){
name = "";
stores = new ArrayList();}
public Company(String name, List stores){
this.name = name;
this.stores = stores;}
public void setName(String name){
this.name = name;}
public String getName(){
return name;}
public void display(){
System.out.println("Company name : "+name);
for (Store store: stores) {
System.out.println("-------------------------\nStore name : "+store.getName()+"\nProducts :
\nItem\tPrice");
for (Product p: store.getProduct()) {
System.out.println(p.getName()+"\t"+p.getPrice());
}}}}

9. Abstract Class


1) Write a program for exam department which provide abstract class and method of Exam type which contains general methods related to exams and can be used by different department for conducting exams.
Output:
firstImage

Source Code:
Main Class:

public class JavaApplication9 {
public static void main(String[] args) {
Exam bse=new BSE();
bse.examDate();
bse.fees();
bse.universityName();
Exam bba=new BBA();
System.out.println();
bba.examDate();
bba.fees();
bba.universityName();
bba.name();}}

BBA Class:

package javaapplication9;
public class BBA extends Exam{
public void examDate(){
System.out.println("The Exam date is 10/03/2022");}
public void fees(){
System.out.println("The fees per Semester is 30000");}
public void display(){
examDate();
fees();} }

BSE Class:

package javaapplication9;
public class BSE extends Exam{
public void examDate(){
System.out.println("The Exam date is 20/12/2022");}
public void fees(){
System.out.println("The fees per Semester is 45000");}}

Exam Class:

package javaapplication9;
public abstract class Exam {
abstract void examDate();
abstract void fees();
void name(){
System.out.println("University Name is Bahria University");}
public void universityName(){
System.out.println("University Name is Bahria University");}}

2) You have to implement the UML diagram given below.Also Design and implement a subclass “EquilateralTriangle” having a double variable side denoting the three sides of the equilateral triangle [Note that since all the 3 sides are equal, the constructor will have only one parameter]. The area and perimeter of the equilateral triangle are given as follows:
Area = ¼*3 *(side)2
Perimeter = 3*side
Provide accessor methods for the sides. Test your class using the TestShapes and DownCastingShapes classes.
Output:
firstImage firstImage

Source Code:
Main TestShape Class:

import java.util.Random;
public class TestShape {
public static Shape[] createShape() {
final int SIZE = 5;
final double DIMENSION = 100;
final int NUMBEROFSHAPES = 4;
Random generator = new Random();
//create an array having b/w 1 and SIZE entries
Shape[] randomShapes = new Shape[generator.nextInt(SIZE) + 1];
for(int i = 0; i < randomShapes.length; i++){
//randomly generate values b/w 0 and NUMBEROFSHAPES - 1
int assigner = generator.nextInt(NUMBEROFSHAPES);
switch(assigner) {
case 0:
randomShapes[i] = new EquilateralTriangle(generator.nextDouble()*
DIMENSION);
break;
case 1:
randomShapes[i] = new Circle(generator.nextDouble()*DIMENSION);
break;
case 2: randomShapes[i] = new Square(generator.nextDouble()*DIMENSION);
break;
case 3: randomShapes[i] = new Rectangle(generator.nextDouble()*DIMENSION, generator.nextDouble()*DIMENSION); break;}}
return randomShapes;}
public static void main(String[] args) {
Shape[] randomShapes = TestShape.createShape();
for(int i = 0; i < randomShapes.length; i++)
System.out.println(randomShapes[i].toString());}}

Class DownCastingShape:

public class DownCastingShapes {
public static void main(String[] args){
Shape[] randomShapes = TestShape.createShape();
for(int i = 0; i < randomShapes.length; i++){
System.out.println(randomShapes[i]);
if(randomShapes[i] instanceof Circle)
System.out.println("Radius= " + ((Circle) randomShapes[i]).getRadius());
else if(randomShapes[i] instanceof Square)
System.out.println("Length= " + ((Square) randomShapes[i]).getLength());
else if(randomShapes[i] instanceof Rectangle)
System.out.println("Length= " + ((Rectangle) randomShapes[i]).getLength() + "\nWidth= " + ((Rectangle) randomShapes[i]).getWidth());
else if(randomShapes[i] instanceof EquilateralTriangle)
System.out.println("Length= " + ((EquilateralTriangle) randomShapes[i]).getSide());}}}

Class Shape:

public abstract class Shape {
public String name(){
return getClass().getName();}
public abstract double area();
public abstract double perimeter();
public String toString() {
return "\n" +name() +"\n Area=" +area() +"\nPerimeter=" +perimeter();}}

Class Square:

public class Square extends Rectangle{
public Square(double length){
super(length, length);}}

Class Rectangle:

public class Rectangle extends Shape{
private double length;
private double width;
public Rectangle(double length, double width){
this.length = length;
this.width = width;}
public double area(){
return length * width;}
public double perimeter(){
return 2*(length+width);}
public double getLength(){
return length;}
public double getWidth(){
return width;}}

Class Circle:

public class Circle extends Shape{
private double radius;
public Circle(double r){
radius = r;}
public double area(){
return Math.PI * (radius * radius);}
public double perimeter(){
return 2.0 * Math.PI * radius;}
public double getRadius(){
return radius;}}

Class EquilateralTriangle:

public class EquilateralTriangle extends Shape{
private double side;
public EquilateralTriangle(double side){
this.side = side;}
public double area(){
return (0.25*Math.sqrt(3)*(side*side));}
public double perimeter() {
return side*side*side;}
public double getSide(){
return side;}}

10. Interfaces


1) Write a program which implements a interface of Banking System by having all standard functionalities and will be implemented by branches.
Hint:(Interface Methods)
CreateAccount()
Search Account details()
Update CustInfo()
Cash Withdraw()
Cash Deosit()
Output:
firstImage

Source Code:
Main Class:

package com.mycompany.lab11;
public class Lab11 {
public static void main(String[] args) {
Banking obj=new Banking();
obj.CreateAccount();
obj.AccountDetails();
obj.UpdateCustInfo();
obj.CashDeposit();
obj.CashWithdraw();}}

Interface Class:

package com.mycompany.lab11;
public interface IBankingSystem {
void CreateAccount();
void AccountDetails();
void UpdateCustInfo();
void CashWithdraw();
void CashDeposit();}

Derived Class:

package com.mycompany.lab11;
import java.util.Scanner;
public class Banking implements IBankingSystem{
String name,fatherName,cnic,answer,answer2;
int number;
Scanner obj=new Scanner(System.in);
public void CreateAccount(){
System.out.println(" ********* Create Account ********* ");
System.out.println("Do you want to create your account?");
answer=obj.next();
if("yes".equals(answer)){
System.out.println(" Enter your Full Name");
name=obj.next();
System.out.println(" Enter your Father Name");
fatherName=obj.next();
System.out.println(" Enter your CNIC");
cnic=obj.next();
System.out.println(" Enter your phone Number");
number=obj.nextInt();
System.out.println("Congratulation! Your account has been created. ");}
else{
System.out.println(" ********* Thank you ********* ");}}
public void AccountDetails(){
System.out.println("\n ********* Search Account Details ********* ");
System.out.println("Do you want to search account details?");
answer2=obj.next();
if("yes".equals(answer2)){
System.out.println("\nThe name is "+ name);
System.out.println("The father name is "+fatherName);
System.out.println("The CNIC is "+cnic);
System.out.println("The number is "+ number);}}
public void UpdateCustInfo(){
System.out.println("\n ********* Update Cust Information ********* ");
System.out.println("Do you want to update cust information?");
String answer1=obj.next();
if("no".equals(answer1)){
System.out.println("Thank you");}}
public void CashWithdraw(){
System.out.println("\n ********* Cash Withdraw ********* ");
System.out.println(" How many rupees do you want to withdraw? ");
int withdraw=obj.nextInt();
if(withdraw<500){
System.out.println("Please withdraw amount more than 500 rupees");}}
public void CashDeposit(){
System.out.println("\n ********* Cash Deposit ********* ");
System.out.println(" How many rupees do you want to deposit? ");
int deposit=obj.nextInt();
if(deposit<500){
System.out.println("Please deposit amount more than 500 rupees");}}}

2) By looking at the formulae for an ellipse, provide the missing code for all of the methods in the class Ellipse including the toString() method. Test your program using the TestShapes.java class. Your output should look as follows (for an ellipse with a = 10 and b = 7) (values are randomly generated).
Output:
firstImage firstImage
firstImage firstImage

Source Code:
Main Class:

public static void main(String[] args) {
Scanner q = new Scanner(System.in);
do {
System.out.println("Select option to calculate ...");
System.out.println("1) Ellipse");
System.out.println("2) Circle");
System.out.println("3) Rectangle");
System.out.println("4) Square");
System.out.println("5) Exit");
char d = q.next().charAt(0);
switch (d) {
case '1': Shape e=new Ellipse(12,23);
e.area();
e.eccentricity();
e.perimeter();
System.out.println(e.toString());
break;
case '2': Shape c=new Circle(12);
c.area();
c.eccentricity();
c.perimeter();
System.out.println(c.toString());
break;
case '3': Shape r=new Rectangle(23,46);
r.area();
r.eccentricity();
r.perimeter();
r.toString();
System.out.println(r.toString());
break;
case '4': Shape v=new Square(12,12);
v.area();
v.eccentricity();
v.perimeter();
v.toString();
System.out.println(v.toString());
break;
case '5':
break;
default:
break; } }
while (true); }

Interface Eccentric :

public interface Eccentric {
double eccentricity();}

Shaoe Class:

public class Shape {
double perimeter, area, eccentricity;
public double perimeter() {
return perimeter; }
public double area() {
return area; }
public double eccentricity() {
return eccentricity; }
public String toString() {
return " " + area + "\n " + perimeter + "\n " + eccentricity; }}

Ellipse Class:

public class Ellipse extends Shape implements Eccentric {
double a, b;
public Ellipse(double s1, double s2) {
if (s1 < s2) { a = s2; b = s1; }
else { a = s1; b = s2; } }
public double perimeter(){
perimeter=3.142*(Math.sqrt(2*(a*a+b*b)-(a*a+b*b-2*a*b)/2));return perimeter; }
public double area() { area=Math.PI*a*b; return area; }
public double eccentricity() {
eccentricity= Math.sqrt(1 - b/a); return eccentricity; }
public String toString() { return "Ellipse\narea: " + area + "\nperimeter: " + perimeter + "\neccentricity: " + eccentricity; }}

Circle Class:

public class Circle extends Ellipse {
double radius; public Circle(double radius) {
super(radius, radius); }
public double perimeter() {
perimeter=2*Math.PI*radius; return perimeter; }
public double area() {
area=Math.PI*radius*radius; return area; }
public double eccentricity() {
eccentricity=0; return eccentricity; }
public String toString() {
return "Circle\narea: " + area + "\nperimeter: " + perimeter + "\neccentricity: " + eccentricity; }}

Rectangle Class:

public class Rectangle extends Shape {
double length,width;
public Rectangle(double length, double width) {
this.length = length; this.width = width; }
public double perimeter() {
perimeter=length+width; return perimeter; }
public double area() {
area=length*width; return area; } public String toString() {
return "Rectangle\narea: " + area + "\nperimeter: " + perimeter; }}

Square Class:

public class Square extends Rectangle {
public Square(double length, double width) { super(length, width); }
public double perimeter() {
perimeter=4*length; return perimeter; }
public double area() { area=length*width; return area; }
public String toString() { return "Rectangle\narea: " + area + "\nperimeter: " + perimeter; }}

11. Exception Handling


1) Write a Fraction class that has a constructor that takes a numerator and a denominator. If the user passes in a denominator of 0, throw an exception of type std::runtime_error (included in the stdexcept header). In your main program, ask the user to enter two integers. If the Fraction is valid, print the fraction. If the Fraction is invalid, catch a std::exception, and tell the user that they entered an invalid fraction.
Output:
firstImage firstImage
firstImage firstImage

Source Code:
Main Class:

package lab12;
import java.io.*;
import java.util.Scanner;
public class LAB12 {
public static void main(String[] args) throws Exception {
Scanner input=new Scanner(System.in);
int numerator,denumerator;
System.out.println("Enter Numerator");
numerator=input.nextInt();
System.out.println("Enter denumerator");
denumerator=input.nextInt();
Fraction num=new Fraction(numerator, denumerator);
num.print();}}

Sub Class:

package lab12;
import java.io.*;
import java.util.*;
public class Fraction {
int denomerator,numerator;
public Fraction(int numerator,int denumerator) throws Exception{
this.denomerator=denumerator;
this.numerator=numerator;
if(denomerator<=0){
throw new Exception("Enter number but greater than 0");}}
public void print(){
System.out.println("The answer is "+ numerator/denomerator);}}

2) Write a program which implements Banking System by having all standard functionalities and will be implemented by branches. Try to identify and implement user defined exceptions for the system.
Hint:
Create Bank Class
public void Create Account(){}
public void deposit() throws Exception{
System.out.println(“Enter Amount to be deposited:);
If(deposit>100000)
throw new Exception(“\n you cant deposit this big amount”);
Else
balance=balance+deposit;
}
Public void withdraw() throws Exception{} (same logic as deposit)
Output:
firstImage firstImage
firstImage firstImage

Source Code:
Main Class:

package lab12;
import java.io.*;
import java.util.Scanner;
public class LAB12 {
public static void main(String[] args) throws Exception {
Scanner input=new Scanner(System.in);
UBL obj=new UBL();
Bank obj1=new HBL();
obj.createAccount();
obj.deposit();
obj.withDraw();
obj1.createAccount();
obj1.deposit();
obj1.withDraw();}}

Bank Class:

package lab12;
import java.io.*;
import java.util.Scanner;
public class Bank {
int deposit,balance=0,withDraw;
Scanner input=new Scanner(System.in);
public void createAccount(){
System.out.println("Enter your name");
String name=input.next();
System.out.println("Enter your father name");
String fatherName=input.next();
System.out.println("Enter your phone Number");
int num=input.nextInt();
System.out.println("Enter your CNIC");
int cnic=input.nextInt();}
public void deposit() throws Exception{
System.out.println("Enter Amount to be deposited:");
deposit=input.nextInt();
if(deposit>100000){
throw new Exception("\n YOu cannot deposit this big amount");}
else {
balance=balance+deposit;}}
public void withDraw() throws Exception{
System.out.println("Enter Amount to be withdraw:");
withDraw=input.nextInt();
if(withDraw>balance){
throw new Exception("\n YOu cannot withdraw because you donot have big balance");}
else if(withDraw<500){
throw new Exception("You cannot withdraw because your amount is less than 500");}
else{
System.out.println("Congratulation!");}}}

UBL Class:

package lab12;
public class UBL extends Bank{
public void createAccount(){
System.out.println("UBL Bank System");
super.createAccount();}
public void deposit() throws Exception{
super.deposit();}
public void withDraw() throws Exception{
super.withDraw();}}

HBL Class:

package lab12;
public class HBL extends Bank{
public void createAccount(){
System.out.println("\nHBL Bank Account");
super.createAccount();}
public void deposit() throws Exception{
super.deposit();}
public void withDraw() throws Exception{
super.withDraw();}}