Oops Solutions Lab PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 167

OOPs Lab Solution Document

OOPS LAB - 1

1) You were given two problems by the teacher to be solved. (Use overloaded methods)
a) There are ‘m’ students registered in the class with a capacity of ‘n’ seats. Your goal is to
find out the number of ways students can be seated assuming there is no deficiency with
the seats.
b) You are supposed to calculate the area of a polygon based on number of inputs given by
the user. Polygon can be a square, a rectangle or a scalene triangle. [LO - 1,2]

Solution :
a)

import java.io.*;

import java.math.*;

import java.util.*;

class Main

public static int fact(int num)

int f=1;

if(num==0)

return 1;

else

return num*fact(num-1);

public static void main(String[] args)

int std_count = 4;

int seat_count = 5;
int seat_fact=fact(n);

int std_seat_fact=fact(n-m);

float cal=(seat_fact/std_seat_fact);

System.out.println("the number of ways are"+cal);

b)

import java.util.*;

public class Main

public static double Calc_area(double a)

double area=a*a;

return area;

public static double Calc_area(double a,double b)

double area=a*b;

return area;

public static double Calc_area(double a,double b,double c)

double s=(a+b+c)/2;

double area=Math.sqrt(s*(s-a)*(s-b)*(s-c));

return area;

public static void main(String[] args)

{
double area,n1=5,n2=3,n3=3;

area=Calc_area(n1);

System.out.println("Area of the Square is:"+area);

area=Calc_area(n1,n2);

System.out.println("Area of the Rectangle is:"+area);

area=Calc_area(n1,n2,n3);

System.out.println("Area of the Scalene Triangle is:"+area);

2) Tony is appointed as a billing administrator in a Restaurant. According to the norms of the


new government, GST and maintenance charges are to be displayed on the bill. Restaurant
also offers a discount to their loyal customers of 10% if the bill is greater than 1000 rupees,
else 5% for all other bills. Help him to calculate the total bill while displaying all the
components separately. [LO - 4]

Solution :

import java.io.*;

import java.math.*;

import java.util.*;

import java.lang.*;

class Main

{
public static void main(String[] args)

float amount=1000,gst=5,main_tax=4,total_tax,dis_amount=0,total_bill,dis_per;

if(amount >=1000)

dis_per=10;

else

dis_per=5;

total_tax=((gst+main_tax)/100)*amount;

dis_amount=(dis_per/100)*amount;

total_bill=amount+total_tax-dis_amount;

System.out.println("your original bill is Rs:"+amount);

System.out.println("your total tax is Rs:"+total_tax);

System.out.println("your discount is Rs:"+dis_amount);

System.out.println("your final bill is Rs:"+total_bill);

3)A microbiologist wants to calculate the remaining amount of the bacteria after 5 minutes.
Initially, there are ‘n’ number of bacteria. After her analysis on the given bacteria, she finds
the decreasing rate of bacteria to be 0.0028 per minute. She approaches you, considering
you to solve it through your java program. [LO - 4]

Solution :

import java.util.*;

class Main

public static void main(String[] args)

int count=5;

double init_bact=32.8;

while(count>=0)
{

init_bact-=(0.0028*init_bact);

count--;

System.out.println("The remaining Bacteria is:"+init_bact);

4)A Software is being developed by the management that displays SGPA of your current
semester. You are given the task to develop a module that calculates the SGPA with respect
to the secured grade points corresponding to given number of credits in each subject. The
credits for the courses are:
Graphics: 2, MVC: 4, COA: 3, Chemistry: 3, English: 2, Technical Skills: 1.5, Data Structures: 4
Complete your Module by displaying the SGPA of current semester.[LO - 3]

Solution :

import java.io.*;

import java.math.*;

import java.text.*;

import java.util.*;

import java.lang.*;

class Main

public static void main(String[] args)

int gph_g=10,mvc_g=9,coa_g=10,chem_g=10,eng_g=10,ts_g=9,ds_g=8;
double gph_c=2,mvc_c=4,coa_c=3,chem_c=3,eng_c=2,ts_c=1.5,ds_c=4;

Double SGPA = ((gph_g*gph_c) +(mvc_g*mvc_c)+ (coa_g*coa_c)+(chem_g*chem_c) +

(eng_g*eng_c) +(ts_g*ts_c)+(ds_g*ds_c))/19.5;

System.out.printf("your SGPA for the semester is %.2f:",SGPA);

5) You are appointed as a programmer of a newly taken up project for Bank-Customer


transactions of a National Bank. The management of the bank requires the customer to give
out their name, account number, and the initial amount present in their account. The
customer will request for the deposit and withdraw of amount from their account. Your
program should be able to check whether the request can be accepted depending on the
account balance in their account and display the appropriate message for their transaction
while also displaying the remaining balance in his/her account. Make sure your program
ensures the access of account number only to the account holder and the bank (Use two
different classes for deposit and withdrawal). [LO - 1,3]

Solution :

class Deposit

public float deposit(float current,float amount)

current +=amount;

System.out.println("Amount deposited Successfully!!!");

return current;

class Withdrawal

public float withdrawal(float current,float amount)

{
if(amount>current)

System.out.println("Insufficient balance");

else

current-=amount;

System.out.println("Amount drawn successfully!!!");

return current;

class Bank

public static void main(String[] args)

float current=20000;

System.out.println("Current Balance is:"+current);

Deposit d=new Deposit();

current=d.deposit(current,20000);

System.out.println("Amount after deposit has done:"+current);

Withdrawal wd=new Withdrawal();

current=wd.withdrawal(current,1000);

System.out.println("Amount after withdrawal has done:"+current);

6) An IT Industry recruited a few employees and wants to maintain a record of their details
containing their name,age and salary. You have been given the task to write a program to
display the details, mentioning the salary to be hidden to others except that particular
employee and the management. [LO - 5]

Solution :
class Employee

private int salary=5000;// It is visible in Employee class only

public int age=32;

public void displayDetail()

System.out.println("Employee salary :" + salary);

public class Main

public static void main(String args[])

String empName="rahul";

System.out.println("Employee name: "+empName);

Employee empObj = new Employee();

empObj.displayDetail();

System.out.println("Employee age: " + empObj.age);

OOPS LAB-2

1) Ramesh’s house is located at a junction from which the places of his four friends are
located at two coordinate points each. He must be at either one of their houses at
the same time. Help him choose which house to go to by finding out the one with
the nearest distance from his place. The coordinates of their houses are as follows:
[LO:1,3]

Name Coordinates
Ramesh (3,2)
Friend A (2,3)
Friend B (0,0)
Friend C (5,8)
Friend D (1,4)

Solution:
import java.lang.*;

import java.lang.Math;

class Nexthouse

public static void main(String args[])

int rx=3,ry=2;

int x[]=new int[]{2,0,5,1};

int y[]=new int[]{3,0,8,4};

int ind=0;

double s,max=100;

for(int i=0;i<4;i++)

s=Math.sqrt(Math.pow((rx-x[i]),2)+Math.pow((ry-y[i]),2));

System.out.println("Distance to Friend"+(i+1)+" house is "+s);

if(s<max)

max=s;

ind=i;

System.out.println("Go to Friend"+(ind+1)+" House");

2) Pavan and Praveen are playing rock - paper - scissor. Here rock = 0, paper = 1, scissor
= 2. Their throws are as follows:
[LO:1,3]

Rounds Round Round Round Round Round Round Round Round Round Round
1 2 3 4 5 6 7 8 9 10
Pavan 0 1 1 2 0 0 1 2 1 0
Praveen 1 2 0 1 0 2 0 1 1 2
Compare and print the score of each of the player at the end of ten rounds and
declare the winner.
Solution:
class Game

public static void main(String args[])

int a[]=new int[]{0,1,1,2,0,0,1,2,1,0};

int b[]=new int[]{1,2,0,1,0,2,0,1,1,2};

winner(a,b);

static void winner(int a[],int b[])

int pavan=0,praveen=0;

for(int i=0;i<10;i++)

if(a[i]==1 && b[i]==0)

pavan++;

else if(a[i]==0 && b[i]==2)

pavan++;

else if(a[i]==1 && b[i]==2)

pavan++;

else if(b[i]==1 && a[i]==0)

praveen++;

else if(b[i]==0 && a[i]==2)

praveen++;

else if(b[i]==1 && a[i]==2)

praveen++;

else if(a[i]==b[i])

continue;

}
if(pavan>praveen)

System.out.println("Pavan is the winner\n");

else if(praveen>pavan)

System.out.println("Praveen is the winner\n");

else(praveen==pavan)

System.out.println("There is a tie between Pavan and Praveen\n");

3) The Government adopts the orphans of various age groups and sends them to an
orphanage. Since the warden doesn’t know the exact count of the orphans help him
by writing a program to count the total number of orphans and find the frequency of
similar age groups. (Use command line arguments as user input). [LO:1,2]

Solution:
import java.util.*;
class Orphanage
{
public static void main(String[] args)
{

int cnt,val,ocnt=0;
int[] fre=new int[args.length];
for(int i=0;i<args.length;i++)
{
fre[i]=-1;
ocnt++;
}
System.out.println("The total no of orphans into the orphanage are: "+ocnt);
for(int i=0;i<args.length;i++)
{
cnt=1;
for(int j=i+1;j<args.length;j++)
{
if(args[i].equals(args[j]))
{
cnt++;
fre[j]=0;
}
}
if(fre[i]!=0)
{
fre[i]=cnt;
}
}
for(int i=0;i<args.length;i++)
{
if(fre[i]!=0)
{
System.out.println("The orphans with age "+args[i]+" are :
"+fre[i]);
}
}
}
}

4) Captain Jack Sparrow went for a treasure hunt with his crew. He came to an Island
and found five caves in a series numbered as (2, 5, 7, 4, 9). Help Captain Sparrow to
(1) Find the caves with treasure?
Hint: -G = (cave number+3) ^2 %10
If (G < 5) -> Cave has treasure.
(2) Find the caves with a new Treasure Map?
Hint: -M = |10 - cave number|%3
If (M==0) ->Cave has treasure map. [LO:1,3]

Solution:

import java.lang.*;
import java.lang.Math;
class Cave
{
public static void main(String args[])
{
int caves[]=new int[]{2,5,7,4,9};
treasure(caves,5);
treasuremap(caves,5);
}
public static void treasure(int caves[],int n)
{
int i,g;
for(i=0;i<n;i++)
{
g=(int)Math.pow((caves[i]+3),2)%10;
if(g<5)
System.out.println("Cave "+(i+1)+" has treasure");
}
}
public static void treasuremap(int caves[],int n)
{
int i,g;
for(i=0;i<n;i++)
{
g=Math.abs(10-caves[i])%10;
if(g<5)
System.out.println("Cave "+(i+1)+" has new treasure map");
}
}
}

5) Tom and Jerry found two bags of apples. The bag that Jerry chose contains 5 apples and
the bag chosen by Tom has 3 apples. Tom wants to have more apples, so he swaps the bags.
Write a program to display the apples in the two bags before and after swapping.
[LO:4]
Hint:-(Try using call by value and call by reference; Write which can be used to swap)
Solution:
public class callbyref

int x;

int y;

public static void main(String[] args)

callbyref obj =new callbyref();

obj.x=10;

obj.y=20;

System.out.println("Before swapping");

System.out.println("The val of x : "+obj.x);

System.out.println("The val of y : "+obj.y);

obj.swap(obj);

System.out.println("After swapping");

System.out.println("The val of x : "+obj.x);

System.out.println("The val of y : "+obj.y);

public void swap(callbyref t) //t=OBJ

int temp=t.x;
t.x=t.y;

t.y=temp;

6) A Person had gone on a holiday. He decided to use his savings amount of 500$. He
allotted certain amount of money as his budget. During the holiday, he first goes on a safari
ride which costs him about $30. Then he goes out for lunch which costs him about $40.
Later, he finishes the day off by going for a movie which costs him $15. Help him find out
the amount left by the end of the holiday.
[LO:3,4]
(Every activity is a method in the class. Only initializing amount is called by value)
Solution:
import java.lang.*;

class Amountleft

int total;

public static void main(String args[])

Amountleft a=new Amountleft();

a.total=500;

safari(a);

lunch(a);

movie(a);

System.out.println("Remaining amount is "+a.total);

static void safari(Amountleft a)

a.total=a.total-30;

static void lunch(Amountleft a)

a.total=a.total-40;
}

static void movie(Amountleft a)

a.total=a.total-15;

7) Write a program to help Alex find out the date and time. [LO:4]
Solution:
import java.util.Date;

public class Current

public static void main(String args[])

Date date = new Date();

System.out.println(date.toString());

}
OOPS LAB-3

1) Rakesh is participating in a Hackathon and it requires him to make a Login page. Help
him out by writing a program to create the page. It should look as follows: [L.O 4]

Solution:
import javax.swing.*;
class Login
{
public static void main(String args[])
{
JFrame frame= new JFrame("Login page");
JButton button = new JButton("Submit");
JTextField usernametextfield;
JPasswordField passwordtextfield = new JPasswordField();
JLabel passwordlabel = new JLabel("Password:");
JLabel usernamelabel = new JLabel("Username:");
usernametextfield=new JTextField();
usernamelabel.setBounds(20,100,80,30);
usernametextfield.setBounds(100,100, 200,30);
passwordlabel.setBounds(20,150,80,30);
passwordtextfield.setBounds(100,150, 200,30);
button.setBounds(150,200, 75,30);
frame.add(usernametextfield);
frame.add(passwordtextfield);
frame.add(usernamelabel);
frame.add(passwordlabel);
frame.add(button);
frame.setSize(400,400);
frame.setLayout(null);
frame.setVisible(true);
}
}
2) A Mathematics faculty in class started asking questions about finding out the square
root of a given number. He now put up a challenge to Satya to tell all the numbers
starting from 1 to the given number (say n). Write a program to help him find out the
square root of all those numbers: [ L.O 1]
Solution:
import java.util.*;
class SquareRootDemo
{
public static void main(String[] args)
{
double n;
int i;
Scanner sc = new Scanner(System.in);
n = sc.nextDouble();
for(i=1;i<=n;i++)
{
double squareRoot = Math.sqrt(i);
System.out.println("number : "+i+":Square root:"+squareRoot);
}
}
}

3) You have a file which contains confidential data in it. You want to send that data to
one of your executives, but you need to send a duplicate copy. Copy the data from
original file to duplicate file and send it: [ L.O 4]

Solution:
import java.io.*;
public class CopyFile
{
public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try
{
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
}
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}

4) While on his duty, a traffic police had the task of checking the speed of vehicles. It is
given that if the speed is above 90kmph, there should be a fine of 1000/- imposed on
the vehicle. Help him out by creating a program to for imposing of the fine. (Create
two classes for police and speed check. All methods must be static): [ L.O 2,3]
Solution:
import java.io.*;
import java.util.*;
class Police
{
public static void Police1(String id,int r)
{
System.out.println("vechical id number :"+id);
if(r==1)
System.out.println("fine imposed Rs 1000/-");
else
System.out.println("No fine imposed");

}
}
class Fine
{
public static int Fine1(int speed)
{
if(speed>90)
return 1;
else

return 0;

}
}
public class Lab
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter car id : ");
String id=sc.next();
System.out.println("Enter speed of vehicle :");
int speed=sc.nextInt();
int r=Fine.Fine1(speed);
Police.Police1(id,r);
}
}

5) Full moon occurs for every 29.52 days. The last full moon occurred on August
14th,2019. Calculate next two full moon days without creating object of the class and
calculate two previous full moon days by creating object of the class: [ L.O 3]
Solution:
import java.util.*;
class NextFullMoons
{
static void nextFullMoons(String mon,int date)
{
date+=29.52-30;
System.out.println("The First Next full moon after August 14th 2019 will be on:
"+"September"+date+"th,2019");
date+=29.52-31;
System.out.println("The Second Next full moon after August 14th 2019 will be on:
"+"October"+date+"th,2019");
}
}
class PreviousFullMoons
{
void previousFullMoons(String mon,int date)
{
date-=29.52-31;
System.out.println("The First Previous full moon before August 14th 2019 will be
on: "+"July"+date+"th,2019");
date-=29.52-30;
System.out.println("The Second Previous full moon before August 14th 2019 will be
on: "+"June"+date+"th,2019");
}
}
public class Fullmoon
{
public static void main(String[] args)
{
PreviousFullMoons pfm=new PreviousFullMoons();
pfm.previousFullMoons("August",14);
NextFullMoons.nextFullMoons("August",14);
}
}

6) Alex was asked to predict number of words and lines in a file. He was just given the
file name. Help Alex to predict, Use Jframes to solve it: [ L.O 4]
(Hint: Take Filename as input in the text field and print the Output in the separate
text fields.)
Sample Output:

Solution:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
class NumberOfWords
{
public static String check(String s,char ch)
{
int count=0;
try
{
FileInputStream fis=new FileInputStream(s);
int d;
while((d=fis.read())!=-1)
{
if((char)d==ch)
count+=1;
}
}
catch(Exception e)
{
return("File Not Found");
}
String t=Integer.toString(count+1);
return t;
}
public static void main(String args[])
{
JFrame f=new JFrame("Creativity");
f.setVisible(true);
f.setSize(400,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p=new JPanel();
TextField tf=new TextField(20);
TextField tf1=new TextField(20);
TextField tf2=new TextField(20);
JLabel l1=new JLabel("Number of words ");
JLabel l2=new JLabel("Number of lines ");
JButton b1=new JButton("Submit");
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String g=check(tf.getText(),' ');
tf1.setText(g);
g=check(tf.getText(),'\n');
tf2.setText(g);
}
});
p.add(tf);
p.add(b1);
p.add(l1);
p.add(tf1);
p.add(l2);
p.add(tf2);
f.add(p);
}
}

7) You are working in DELL company. You’ve been asked to develop a program for
the
service center website of the company. It should contain Purchasing and Servicing
options (Consider them as classes). Purchase class contains purchaseInspiron and
purchaseAlienware methods, Service class contains serviceOfLaptop and serviceOfPc
methods. Both service and purchase classes are in class Dell. (Use Inner Classes) [L.O
5]

Solution:
import java.util.*;
class Dell{
class Purchase{
void vostra(){
System.out.println("Cost of the Vostra Product is $ 200");
}
void alienware(){
System.out.println("Cost of the Alienware Product is $ 450");
}
}
class Service{
void pc(){
System.out.println("Your PC will be serviced soon");
System.out.println("Thank You for using our service");
}
void laptop(){
System.out.println("Your LapTop will be serviced soon");
System.out.println("Thank You for using our service");
}
}
}
class Coustmer extends Dell{
public static void main(String args[]){
Scanner l = new Scanner(System.in);
System.out.println("Welcome to Dell Help Center");
System.out.println("1.Prchase\n2.Service");
System.out.println("Select the help you require");
int choice = l.nextInt();
switch(choice){
case 1: Coustmer.Purchase p = new Coustmer().new Purchase();
System.out.println("1.Vostra\n2.Alienware");
int select = l.nextInt();
System.out.println("Select the Product");
switch(select){
case 1: p.vostra();
System.out.println("Thank you for prchasing");
break;
case 2: p.alienware();
System.out.println("Thank you for prchasing");
break;
}
break;
case 2: Coustmer.Service q = new Coustmer().new Service();
System.out.println("1.PC\n2.LapTop");
int see = l.nextInt();
System.out.println("Select the Service");
switch(see){
case 1: q.pc();
break;
case 2: q.laptop();
break;
}
break;
}
}
}
OOPS LAB - 4

1. A lottery shop owner is running two deals for his customers. In the first deal, he gives out
one token at a cost of 5/- and in the second deal he gives out two tokens at a cost of 10/-.
Each token value ranges from 0 to 5. Each customer gets one chance of playing the game of
BIG SIX WHEEL. If he gets a value which is less than or equal to the token value, he wins a
prize. Help him out by writing a program for this. (Use constructor overloading) [ L.O 1]

Solution:

import java.util.*;

class Lottery

int token_value1,token_value2;

Lottery()

System.out.println("Zero Parameterised Constructor");

Lottery(int tv)

token_value1=tv;

System.out.println("Token_value is: "+token_value1);

token_value2=0;

Lottery(int tv1, int tv2)

token_value1=tv1;

token_value2=tv2;

int check()
{

Random rand=new Random();

int flag=0;

int check=rand.nextInt(6);

System.out.println("Token_value 1 is: "+token_value1);

System.out.println("Token_value 2 is: "+token_value2);

System.out.println("The Big Six Wheel Score is: "+check);

if(token_value1 >= check || token_value2 >= check)

flag=1;

Else

flag=0;

if(flag==1)

return 1;

Else

return 0;

public static void main(String[] args)

Scanner sc=new Scanner(System.in);

System.out.println("Lottery House Offfers you 2 deals ");

System.out.println("1. One token for 5 Rupees/-");

System.out.println("2. Two token for 10 Rupees/-");

int choice=sc.nextInt();
Lottery b;

Lottery c;

int result=-1;

Random r=new Random();

switch(choice)

case 1:

b=new Lottery(r.nextInt(6));

result=b.check();

break;

case 2:

c=new Lottery(r.nextInt(6),r.nextInt(6));

result=c.check();

break;

default:

System.out.println("No offers available other than 5 and 10 Rupees");

/*Lottery b=new Lottery(2);

int result=b.check();*/

if(result == 1)

System.out.println("Kid, you've won the Lottery trial");

else

System.out.println("Kid you lost the Lottery trial, BETTER LUCK NEXTIME");

2. A customer of a bank wants to withdraw/deposit money from his account. There are 3
ATMs in his town. Help him out by writing a program such that his balance will be updated
after a transaction in any of the ATMs. (Use ‘Account’ as Singleton Class and it should be Early
Instantiated) [L.O 2]
Solution:

class Atm

private static Atm acc=null;

public double Balance=123516;

public static Atm amount()

if(acc==null)

acc=new Atm();

return acc;

public void getAmount(int m)

if(Balance==0)

System.out.println("Insufficient Balance");

else if(Balance-m<0)

System.out.println("Insufficient Balance");

else

Balance=Balance-m;

public class HelloWorld

public static void main(String args[])

Atm x=Atm.amount();

x.getAmount(10);

System.out.println(x.Balance);

Atm y = Atm.amount();
y.getAmount(1000);

System.out.println(y.Balance);

3. A Net Cafe has one printer and four systems which has a total of 100 papers. Write a
program such that after every print command the number of papers left should be displayed
on every system. Use GUI, consider each frame as a system. (Use Singleton class) [L.O 2]

Solution:

import java.util.*;

class Singleton

private int counter=100;

private static Singleton obj=null;

private Singleton()

System.out.println("\t object is created");

public static Singleton getInstance()

if(obj==null)

obj=new Singleton();

return obj;

public void used()

System.out.println("A paper is used");

this.counter-=1;
obj.remaining();

private void remaining()

System.out.println("No.of papers remaining in the Printer: "+counter);

class Main

public static void main(String[] args)

Singleton obj1=Singleton.getInstance();

obj1.used();

Singleton obj2=Singleton.getInstance();

obj2.used();

4. You’re an agent of the R.A.W agency who needs to take in the details of the agents and
store them in the database. All the instance variables must be private. Write a program to
access and update the details whenever necessary and display them in the following format:
Name: Bond
Age: 42
ID: 007
Location allocated: Britain (Use mutators and accessors) [L.O 3]

Solution:
import java.util.*;

import java.io.*;

class Main

private String name,location;

private int age,id;

public void setName(String name)

this.name=name;

public String getName()

return name;

public void setAge(int age)

this.age=age;

public int getAge()

return age;

public void setLocation(String location)

this.location=location;

public String getLocation()

return location;

public void setId(int id)

this.id=id;
}

public int getId()

return id;

class Type

public static void main(String args[])

Main M=new Main();

M.setName("Bond");

M.setAge(42);

M.setId(007);

M.setLocation("Britain");

System.out.println("Name:" +M.getName());

System.out.println("Age:" +M.getAge());

System.out.println("Id:"+ M.getId());

System.out.println("Location:"+ M.getLocation());

5. MATCH THE FOLLOWING


(Assume ‘A’ is the class name)
1. public [ ] a) Parameterized Constructor
2. private [ ] b) No-argument constructor
3. A(4,5){ } [ ] c) have only one object
4. Singleton class [ ] d) accessible anywhere
5. A(){ } [ ] e) accessible within the class only
6. Accessors [ ] f) only accessible in class and its subclass
7. Mutators [ ] g) Methods to access instance variables
h) Methods to initiate instance variables

Solution:

1-d

2-e

3-a

4-c

5-b

6-g

7-h

6) A Restaurant serves dishes of three types: Veg, Non-Veg and Egg represented by green, red
and brown color codes respectively. Help them out by writing a menu driven program to
display the various dishes depending on the type of food the customer opts for. [L.O 4]

Solution:

import java.util.*;
class Menu
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
boolean flag = true;
while(flag)
{
System.out.println(" 1.veg\n 2.nonveg\n 3.egg\n 4.exit");
System.out.print(" Enter your Preference: ");
int st=sc.nextInt();
switch(st)
{
case 1:
System.out.println(" veg-biriyani\n veg fried rice\n butter naan");
Break;
case 2:
System.out.println(" chicken-biriyani\n chicken fried rice\n chilli chicken" );
Break;
case 3:
System.out.println("omlett\n egg fried rice\n egg fry");
Break;
case 4:
System.out.println("THANK YOU \n");
Break;
Default:
System.out.println(" category not available ");
Break;
}
System.out.println("Sir! Enter 1 to Order again");
int sele=sc.nextInt();
if(sele == 1 && st!=4)
flag=true;
else
{
System.out.println(" VISIT AGAIN\n");
flag=false;
Break;
}
}
}
}

7) A company wants to digitize their manual records of the employee details (Employee ID,
Employee name, Employee Department). If all the three fields are given, use the given details.
If not, use the default values.
(Use Constructor Overloading) [L.O 1]
Default values are:
ID: 0
Name: #
Department: #
Solution:

import java.util.*;

class Employee

private static int empId;

private static String empName;

private static String empDept;

Employee()

empId=0;

empName="#";

empDept="#";

Employee(int empId,String empName,String empDept)

this.empId=empId;

this.empName=empName;

this.empDept=empDept;

public static void main(String args[])

Employee e;

Scanner s=new Scanner(System.in);

int n,id;

String name,dept;

System.out.println("Enter number of entries ");

n=s.nextInt();

System.out.println("Enter Employee Id ");

id=s.nextInt();

System.out.println("Enter Employee Name ");

name=s.next()+s.nextLine();
System.out.println("Enter Employee Dept ");

dept=s.nextLine();

if(n<3)

e=new Employee();

else

e=new Employee(id,name,dept);

System.out.println("Employee Id is "+e.empId);

System.out.println("Employee Name is "+e.empName);

System.out.println("Employee Dept is "+e.empDept);

8) You need to write a program for a government website which maintains the census details
of the nation. You need to consider Total, male and female population as the attributes. It
should be updated after every census. All the attributes should be private. (Use accessors and
mutators to update and retrieve data.) [L.O 3]

Solution:

import java.util.*;

class Census

private static int total;

private static int male;

private static int female;

public void setTotal(int total)

this.total=total;

public void setMale(int male)

this.male=male;
}

public void setFemale(int female)

this.female=female;

public int getTotal()

return total;

public int getMale()

return male;

public int getFemale()

return female;

public static void main(String args[])

Census c=new Census();

int t,m,f;

Scanner s=new Scanner(System.in);

System.out.println("Enter total population ");

t=s.nextInt();

c.setTotal(t);

System.out.println("Enter number of male ");

m=s.nextInt();

c.setMale(m);

System.out.println("Enter number of female ");

f=s.nextInt();

c.setFemale(f);

System.out.println("Total population is "+c.getTotal());

System.out.println("Employee Name is "+c.getMale());


System.out.println("Employee Dept is "+c.getFemale());

9) You are working as a Data entry operator in a Sports academy which teaches cricket and
football to young kids. As the new calendar year starts a new batch of kids join the academy
and you need to store their details. All of them have instance variables as their name, their
age and their country in the class player. Depending on the sport the other variables vary, like
the class cricketer has matches, runs, wickets, class footballer contains matches and goals.
Using these criteria print the data of a cricketer and a footballer using aggregation and
composition. [L.O.5]

Solution:

class player

String Name;

int age;

String Country;

player(String Name,int age,String Country)

this.Name=Name;

this.age=age;

this.Country=Country;

class Cricketer

player PlayerDetails;

int Runs;

int Wickets;
int Matches;

Cricketer(player PlayerDetails,int Runs,int Wickets,int Matches)

this.PlayerDetails=PlayerDetails;

this.Runs=Runs;

this.Wickets=Wickets;

this.Matches=Matches;

void display()

System.out.println("............Displaying a Cricket Player Details.............");

System.out.println("Name : "+PlayerDetails.Name);

System.out.println("Age : "+PlayerDetails.age);

System.out.println("Country : "+PlayerDetails.Country);

System.out.println("No of Matches :"+Matches);

System.out.println("No of Runs : "+Runs);

System.out.println("No of Wickets : "+Wickets);

class FootballPlayer

player PlayerDetails;

int Goals;

int Matches;

FootballPlayer(player PlayerDetails,int Matches,int Goals)

this.Goals=Goals;

this.Matches=Matches;

this.PlayerDetails=PlayerDetails;

void display()

System.out.println("............Displaying a Football Player Details.............");


System.out.println("Name : "+PlayerDetails.Name);

System.out.println("Age : "+PlayerDetails.age);

System.out.println("No of Matches :"+Matches);

System.out.println("Country : "+PlayerDetails.Country);

System.out.println("No of Goals : "+Goals);

class Display

public static void main(String args[])

player A=new player("Sachin",46,"INDIA");

player B=new player("Messi",31,"Argentine");

Cricketer C=new Cricketer(A,5000,99,200);

FootballPlayer D=new FootballPlayer(B,699,837);

C.display();

D.display();

OOPS Lab – 5

1) Patrick found out that his distant relative had passed away recently and that he had
inherited one of his property papers which contains text. He has an interest in
sentences being PANGRAMS and this text wasn’t in that format. He found that he
had a choice of buying the missing letters from the local store to complete it as
PANGRAM. Each letter has its own price and you need to write a program to help
him find out the cheapest way to make it into a PANGRAM. (Use Inheritance) [L.O.1]
Solution:
import java.util.*;
class Papyrus
{
String getString()
{
//returns a string when called
//return "THISISasentencewithnospaces";
return "abcdefghijklmnopqrstuvw";
}
}
class Mathios extends Papyrus
{
Papyrus ps;
String pangram;
int i;
int[] cost=new int[26];
int price=0;
int panagramChecker(Papyrus ps, int cost[])
{
this.ps=ps;
pangram=ps.getString();
StringBuilder sb=new StringBuilder(pangram.toLowerCase());
System.out.println("Sb is: "+sb);
int length=sb.length();
int[] alphabets=new int[26];
for(i=0;i<length;i++)
{
alphabets[sb.charAt(i)-97]++;
}
for(i=0;i<26;i++)
{
if(alphabets[i]==0)
{
sb.insert(length,(char) (i+97));
length++;
price=price+cost[i];
}
}
return price;
}
}
class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
Mathios m=new Mathios();
int[] cost=new int[26];
for(int i=0;i<26;i++)
{
//cost[i]=sc.nextInt();
cost[i]=i;
}
int price=m.panagramChecker(m,cost);
if(price!=0)
{
System.out.println("Inherited Papyrus is not panagram and the price
to make it panagram is: "+price);
}
else
{
System.out.println("Ineherited String is a panagram");
}
}
}

2) A customer walks into a KFC outlet and sees that he has two options: veg and non-
veg. He observes that plain veg burger costs 80/- and plain non-veg burger costs
120/- each. But he wishes to have extra mayonnaise and either of extra
veggies/chicken on each of his burgers. Help the outlet by writing a program which’ll
help them calculate the cost of the basic burger and also include the cost of the
condiments if he chooses to add any. (Use Inheritance and Null Object Design
Pattern) [L.O.6,7]

Item Cost
Mayonnaise 30/-
Veggies 45/-
Chicken 60/-

Solution:
abstract class Burger
{
String description = "Unknown Burger";
public String getDescription()
{
return description;
}
public abstract double cost();
}
abstract class Extras extends Burger
{
public abstract String getDescription();
}
class ChickenBurger extends Burger
{
public ChickenBurger()
{
description = "ChickenBurger";
}
public double cost()
{
return 100;
}
}
class VegBurger extends Burger
{
public VegBurger()
{
description = "VegBurger";
}
public double cost()
{
return 70;
}
}
class cheese extends Burger
{
Burger burger;
public cheese(Burger burger)
{
this.burger = burger;
}
public String getDescription()
{
return burger.getDescription() + ", Chesses";
}
public double cost()
{
return 30 + burger.cost();
}
}
public class abhinav
{
public static void main(String args[])
{
Burger burger = new ChickenBurger();
burger = new cheese(burger);
System.out.println(burger.getDescription() + " RS" + burger.cost());
Burger burger2 = new VegBurger();
burger = new cheese(burger);
System.out.println(burger2.getDescription () + " RS" + burger2.cost());
}
}

3) Your local library needs your help related to library management and wants you to
develop a program that will help them to calculate the fine .Remember that the
name and the number of days the borrower had the book with them should be
protected and display the information using inheritance concept .After 15 days fine
will be charged as 2 rupees per day until the day of submission, if there is no charge
simply print “NO FINE” else print the fine.[L.O.4]
Solution:
import java.util.Scanner;
class Borrower
{
protected void
borrowerinfo()
{
Scanner sc=new
Scanner(System.in);
System.out.println("Enter the name and the number of days book was
with the borrower");
String name=sc.nextLine();
int n=sc.nextInt();
System.out.println("The name of the borrower :"+name);
System.out.println("The number od books borrower had :"+n);
if(n>1 5)
{
int t=n-15;
int fine= t*2;
System.out.println("FINE:"+f ine);
}
else
{
System.out.println("No fine");
}
}
}

class Library extends Borrower


{
public static void main(String args[])
{
Library lib = new Library();
lib. borrowerinfo();
}
}

4) Abhinav has given his credit card to his three sons for their monthly expenses. After
the turn of the month, he gets a bill of 1,00,000/- Rohit tells him that he had used
15,000/- in that month. Srikanth and Kalyan tell him that they’ve used 35,000/- and
50,000/- respectively. Help Abhinav to find out percentage of amount each of his
sons used in that month. Consider creditBill as abstract class containing a return
method and an abstract method. Use Dynamic Polymorphism. [L.O.2,5]
Solution:
abstract class creditBill{

double totalBill()

//returns total bill when called return 100000.0; }

abstract double bill(creditBill credit_Bill, double individualBill);

class Rohit extends creditBill

creditBill credit_Bill;

double individualBill;

double bill(creditBill credit_Bill, double individualBill){

this.credit_Bill=credit_Bill;

this.individualBill=individua lBill;

return (individualBill/ credit_Bill.totalBill())*100;

class Srikanth extends creditBill

creditBill credit_Bill;

double individualBill;

double bill(creditBill credit_Bill, double individualBill){

this.credit_Bill=credit_Bill; this.individualBill=individua lBill;

return (individualBill/

credit_Bill.totalBill())*100;

class Kalyan extends creditBill{

creditBill credit_Bill; double individualBill; double bill(creditBill credit_Bill, double


individualBill){

this.credit_Bill=credit_Bill; this.individualBill=individua lBill;

return (individualBill/
credit_Bill.totalBill())*100;

public class abhinav

public static void main(String args[]){

creditBill credit_Bill;

Rohit r=new Rohit();

credit_Bill=r;

System.out.println("Rohit spent "+credit_Bill.bill(r,15000.0)+"% of the Totalbill");

Srikanth s=new Srikanth();

credit_Bill=s; System.out.println("Srikanth

spent "+credit_Bill.bill(r,33000.0)+"% of the Total bill");

Kalyan k=new

Kalyan();

credit_Bill=k;

System.out.println("Kalyan spent "+credit_Bill.bill(r,57000.0)+"% of the Total bill");

5) Kartish is the head of the village panchayat and decides to collect the data related to
the population, total income and the average income of the village and stores it in a
class which is in a package village. Help him out to create another package and
access the village information. (Use Protected access specifier) [L.O.4]

Solution:
package in;

import out.*;

class B1 extends Village {


public static void main(String[] args) {

System.out.println(Village.food());

System.out.println(Village.avgincome());

System.out.println(Village.water());

package out;

public class Village {

private static int income=1000;

private static int population=40;

private static int tonsoffood=500;

private static int litresofwater=1000;

protected static int avgincome() {

return income/population;

protected static int food() {

return tonsoffood/population;

protected static int water() {

return litresofwater/population;

6) Ramesh owns a company and ran it for a period of 7 years with a profit of 80cr per
annum. He falls sick and his son Suresh inherits the ownership of the company and
runs it for a period of 6 years with a profit margin of 120cr per annum. Complete the
given code. (Use the keyword ‘Super’) [L.O.3]
class Ramesh
{
Ramesh (int yearsWorked, int profitPerAnnum)
{
//Fill the code
}
}

class Suresh extends Ramesh


{
Suresh (int yearsWorked, int profitPerAnnum)
{
//Fill the code

}
}

class Company
{
public static void main (String[] args)
{
//Fill the line

}
}
OUTPUT FORMAT:
Ramesh worked for 7 years and earned profit 80 crores
Total Profit earned by Ramesh is: 560
After Ramesh's ill health his son Suresh, took over to develop his father’s company
Suresh worked for 6 years and earned profit 120 crores
Total Profit earned by Suresh is: 720

Solution:
class Father{

Father(int yearsWorked, int profitPerAnnum)

System.out.println("Father worked for "+yearsWorked+"years and earned


profit"+profitPerAnnum+" crores");

System.out.println("Total Profit earned by father is: "+(yearsWorked*profitPerAnnum));

class Son extends Father{

Son(int yearsWorked, int profitPerAnnum){

super(7,8 0);

System.out.println("After Father's ill condition his son took his place to develop his fathers
company");

System.out.println("Son worked for "+yearsWorked+"years and earned profit"+profitPerAnnum+"


crores");

System.out.println("Total Profit earned by son is: "+(yearsWorked*profitPerAnnum));

class Company{

public static void main(String[] args){

Son object=new Son(6,120);

7) A student was asked by his teacher to solve a problem which states that he should
be finding out the area of a rectangle by writing a program for it. After writing the
code, he was then asked to find out the area of any given polygon without modifying
the already written code only by extending it. Help him out by writing a program for
it. [L.O.5]

Solution:
class rectangle{
public int length;
public int breadth;
public int area(int l,int b){
this.length=l;
this.breadth=b ;
return 2*(l+b);
}
}
class circle extends rectangle {
public double radius;
public double area(double r){
this.radius=r;
return (3.14)*r*r;
}
}
public class area{
public static void main(String args[]){
rectangle r = new rectangle();
circle c = new circle();
System.out.println(r.area(2,3));
System.out.println(c.area(5)) ;
}
}

8) Mobile phone evolution initially happened in 4 phases. It started with phones having
only call feature, then it extended to phones to having messaging also. In the next
generation phones also had camera and in the final generation of that revolution
they started having internet also. Write a program to print all the features present in
a 4th generation phone. (Use inheritance) [L.O.1]
Solution:
public class Inheritance

public static void main(String[] args)

gen4 obj =new gen4();

class gen1 {

gen1( )

System.out.println("ca ll");

}
}

class gen2 extends gen1

gen2( )

System.out.println("messa ge");

class gen3 extends gen2

gen3( )

System.out.println("camer a");

class gen4 extends gen3

gen4( )

System.out.println("interne t");

9) You are the manager of a textile showroom. According to seasons and festivals you
have to apply coupons so to attract the customers. You have two coupons available
with you i.e. “RAMZAN” and “CHRISTMAS” which gives different discounts for
different coupons. You have to add one more coupon “DIWALI” to your program
without modifying the code by just extending it. [L.O.5]

Solution:
import java.util.Scanner;

class Market

void offer() { }

}
class RAMZAN extends Market

void offer(double bill)

double billafteroffer;

System.out.println("Summer Discount 30%");

billafteroffer = bill-(0.3*bill);

System.out.println("The bill is "+billafteroffer);

class CHRISTMAS extends Market

void offer(double bill)

double billafteroffer;

System.out.println("winter Discount 25%"); billafteroffer = bill-(0.25*bill);

System.out.println("The bill is "+billafteroffer);

class DIWALI extends Market

void offer(double bill)

double billafteroffer;

System.out.print("Festive Season Discount 20%\n");

billafteroffer = bill-(0.20*bill);

System.out.println("The bill is " + billafteroffer);

class Personbill

public static void main(String args[]){

System.out.println("Coupons available are 'RAMZAN' ,'CHRISTMAS'");

System.out.println("Apply coupon");
Scanner sc = new Scanner(System.in);

String coupon = sc.next() + sc.nextLine();

System.out.println("Enter your Bill ");

double Bill = sc.nextDouble();

if(coupon.equals("RAMZA N"))

RAMZAN totalbill = new RAMZAN();

totalbill.offer(Bill);

if(coupon.equals("CHRISTMAS"))

CHRISTMAS totalbill = new

CHRISTMAS();

totalbill.offer(Bill);

if(coupon.equals("DIWALI"))

DIWALI totalbill = new DIWALI();

totalbill.offer(Bill);

10) Admissions for your college have begun and you are required to develop a program
which checks the eligibility criteria for the freshers. If a male student gets less than
2000 rank in EAMCET, he is eligible for admission and has a fee of 100000/- and if a
female student gets less than 1600 rank in EAMCET, she is eligible for admission and
has a fee of 90000/-. Any student wanting to avail the hostel facility has to pay an
additional fee of 100000/- (Use Template Design Pattern) [L.O.7]

Solution:
import java.util.*;

import java.io.*;

abstract class AdmissionTemplate

public abstract void rankRequired();


public abstract void fee();

public final void Hostal()

System.out.println("hostal fee : 100000 per annum");

public void CheckDetails(boolean hostal)

rankRequired ();

fee();

if(hostal)

Hostal();

class Male extends AdmissionTemplate

@Override

public void rankRequired()

System.out.println("The minimum rank required to get Admission is 20000");

@Override

public void fee()

System.out.println("fee for sem is 100000");

class Female extends AdmissionTemplate

@Override

public void rankRequired()

System.out.println("The minimum rank required to get Admission is 16000");


}

@Override

public void fee()

System.out.println("fee for sem is 90000");

public class Main

public static void main (String[] args)

Scanner sc=new Scanner(System.in);

Male m=new Male();

Female f=new Female();

System.out.println("1.Male\n2.Female");

int x=sc.nextInt();

System.out.println("Enter true is hostal required else False");

boolean h=sc.nextBoolean();

if(x== 1)

m.CheckDetails( h);

else

f.CheckDetails( h);

}
OOPS LAB – 6

1. Rohit gives a task to his younger brother where he will be given three variables which may hold any
type of data. The task here is to print the given inputs in the same format. [HINT: Use the concept of
generic methods.] [L.O 1]
18 10861 Virat
Sachin 10 18426
7 Dhoni 10534
10201 333 Gayle
ABD 9577 17

Solution:
import java.util.*;

class GenericMethod{
<a> void method(a x,a y,a z){
System.out.println(x+" "+y+" "+z);
}
}

class Main{
public static void main(String[] args){
GenericMethod g=new GenericMethod();
Scanner sc=new Scanner(System.in);
g.method(1,3,7);
}
}

2. An old man wants to distribute sweets to children near his home. He was confused of how many
sweets he must give to each child. Help the old man by writing a program where the number of
sweets and number of children are initialized using parameterized constructor. Observe what
happens when there are zero number of children and handle the exception if any. [ L.O 2]

Solution:

import java.util.Scanner;
class A
{
int noOfSweets;
int noOfChildren;
A(int noOfChildren ,int noOfSweets)
{
this.noOfChildren=noOfChildren;
this.noOfSweets=noOfSweets;
}
int per(int x,int y)
{//int noofswee;
try
{
int noofswee=x/y;
return noofswee;
}
catch(Exception e)
{
System.out.println(e);
}
return 0;
}
}
class B
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int x=scan.nextInt();
int y=scan.nextInt();
A obj=new A(y,x);
int pereach=obj.per(x,y);
System.out.println(pereach);
}
}

3. Profit or Loss in Stock market is decided by the following formula:


(x^3+x^2+x) / ((f^3+g^3+h^3) - x)
where x is the value of a single share and
f = x% 10, g = (x/100), h = (x%100)/10

The values of x for various companies are as follows

153 505 370 307 480 407 600 371 999


Using the steps of exception handling (try, catch) find whether the companies are getting a profit or
loss and print the exception if there is any. Think and draw conclusion a on why there arises an
exception for certain inputs. [ L.O 2]

Solution:

import java.util.Scanner;

public class Main

{
public static void main(String[] args)

int i;

Scanner scanner =new Scanner(System.in);

for(i=0;i<2;i++)

System.out.println("enter the stock value");

int yes ;

int x = scanner.nextInt();

try

int f = (x%10);

int g = ((x%100)/10);

int d = (x/100);

System.out.println(x+x/(x-(f*f*f + g*g*g +d*d*d )));

System.out.println("company got profit");

catch(Exception e)

System.out.println(e);

System.out.println("company got lose");

} scanner.close();

4. Analyse and guess the output of the following code. [L.O 2]


class Exc
{
public static String lem()
{
System.out.println("lem");
return "return from lem";
}
public static String foo()
{
int x = 0;
int y = 5;
try
{
System.out.println("start try");
int b = y / x;
System. out. println("end try");
}
catch (Exception ex)
{
System. out. println ("catch");
lem();
}
return "oo";
}

public static void bar()


{
System. out. println("start bar");
String v = foo();
System.out.println(v);
System.out.println("end bar");
}
public static void main(String[] args)
{
bar();
System.out.println("End\n");
}
}
Answer:
Output:

start bar

start try

catch

lem

oo

end bar

End

5) Election committee wants to check whether the voter is eligible to vote or not. The person can vote if his
age is greater than 18. Help the Election committee by developing a code which arises exception if the voter
age is less than 18 then print the exception and “VOTER IS NOT ELIGIBLE TO VOTE”, otherwise print “VOTER IS
ELIGIBLE TO VOTE”. [L.O 2]

Solution:

public class Example1 {

public static void main(String args[]) {

int age=2;

try {

if(age<18){
int b=1/0;

System.out.println("Eligible for vote");

catch (ArithmeticException e) {

System.out.println("Not eligible for vote");

System.out.println(e);

6) A student was asked by his faculty to print the name of Sachin Tendulkar, his total number of runs scored
in ODI’s and his average in one line and to print them in reverse order in the next line. Create an object and
pass the data to the constructor Statistics. Help him out by writing out a code. [L.O 1]

Solution:

import java.util.*;

import java.io.*;

class Statistics<T1,T2,T3>

T1 obj;

T2 obj1;

T3 obj2;

Statistics(T1 obj,T2 obj1,T3 obj2)

this.obj = obj;

this.obj1 = obj1;

this.obj2=obj2;

System.out.println("player name "+obj+", total runs scored in odi "+obj1+ ", average runs
scored "+obj2);

System.out.println("average runs scored "+obj2+" , total runs scored in odi "+obj1+" , player
name "+obj);

class Main

public static void main (String[] args)


{

Scanner sc=new Scanner(System.in);

System.out.println("Enter name of player");

String name=sc.next();

System.out.println("Enter runs scored by player ");

int runs=sc.nextInt();

System.out.println("Enter average runs scored by player");

float avg=sc.nextFloat();

Statistics <String,Integer,Float> Obj = new Statistics<String,Integer,Float>(name,runs,avg);

7) There’s a Christmas eve and so every shopping mall in the city conducted many spot events and games. In a
lucky draw, they decided to gift every customer who had their ‘names’ special. “Special”, they meant: The
String ‘name’ with length ‘N’, should have 2

or more than 2 special sets. “Special sets” differ from 1 mall to the other.

• Special set for mall 1 meant: the index ‘i’ (1≤i≤N) such that i th character of the name is vowel and the
(i+1) th letter is a consonant.
• Special set for mall 2 meant: the index ‘i’ (1≤i≤N) such that i th character of the name is vowel and the
(i+2) th letter is a consonant.
Considering “name” and “shopping mall” as inputs, check whether you could win the lucky
draw or not, while also display the required message. Hint: Take ‘Mall’ as an abstract class and
‘special set’ as an abstract method in it. Override the method to the subclasses mall 1, mall 2. [L.O 3]

Solution:

abstract class Mall

abstract void specialSet(String Name);

class MallOne extends Mall

String Name;

int nameLength;

int specialSetCount=0,i;

StringBuilder sb;

void specialSet(String Name)

this.Name=Name;
Name=Name.toLowerCase();

StringBuilder sb=new StringBuilder(Name);

nameLength=sb.length();

for(i=0;i<nameLength-1;i++)

if(sb.charAt(i) == 'a' || sb.charAt(i) == 'e' || sb.charAt(i) == 'i' || sb.charAt(i) == 'o' ||


sb.charAt(i) == 'u')

if(sb.charAt(i+1) != 'a' || sb.charAt(i+1) != 'e' || sb.charAt(i+1) != 'i' ||


sb.charAt(i+1) != 'o' || sb.charAt(i+1) != 'u')

specialSetCount++;

//System.out.println(sb.charAt(i)+","+sb.charAt(i+1));

if(specialSetCount >= 2)

System.out.println("Congragulations Punk");

else

System.out.println("the Special Set is too less to know your name's beauty");

class MallTwo extends Mall

String Name;

int nameLength;

int specialSetCount=0,i;

StringBuilder sb;

void specialSet(String Name)

this.Name=Name;

Name=Name.toLowerCase();

StringBuilder sb=new StringBuilder(Name);


nameLength=sb.length();

for(i=0;i<nameLength-1;i++)

if(sb.charAt(i) == 'a' || sb.charAt(i) == 'e' || sb.charAt(i) == 'i' || sb.charAt(i) == 'o' ||


sb.charAt(i) == 'u')

if(sb.charAt(i+1) != 'a' || sb.charAt(i+1) != 'e' || sb.charAt(i+1) != 'i' ||


sb.charAt(i+1) != 'o' || sb.charAt(i+1) != 'u')

specialSetCount++;

if(specialSetCount >= 2)

System.out.println("Congragulations Punk");

else

System.out.println("the Special Set is too less to know your name's beauty");

class Main

public static void main(String[] args)

MallOne mallOne=new MallOne();

mallOne.specialSet("pavan");

MallTwo malltwo=new MallTwo();

malltwo.specialSet("Pejhvbvdlkdv");

8) One of your friends John has come over from the States and is curious to know about IPL. Explain him about
the working of the league by printing the points table of IPL 2018. Points table is as follows:

Team Matches Won Lost No Result Total Points NRR


played
KXIP 14
SRH 14
CSK 14
MI 14
KKR 14
RCB 14
DC 14
RR 14
Use the concept of generic method and complete the table. [L.O 1]

Solution:

import java.util.*;

class Exp8

public static <T> void display(T team,T match,T won,T lost,T nor,T points,T nrr)

System.out.println("Team : "+team);

System.out.println("Number of matches played : "+match);

System.out.println("Number of matches won : "+won);

System.out.println("Number of matches lost : "+lost);

System.out.println("Number of matches with no result : "+nor);

System.out.println("Points secured : "+points);

System.out.println("Net run rate : "+nrr);

public static void main(String args[])

Scanner sc=new Scanner(System.in);

String team;

int match,won,lost,nor,points;

float nrr;

System.out.println("Enter team details");

for(int i=0;i<1;i++)

team=sc.nextLine();

match=sc.nextInt();

won=sc.nextInt();

lost=sc.nextInt();

nor=sc.nextInt();
points=sc.nextInt();

nrr=sc.nextFloat();

display(team,match,won,lost,nor,points,nrr);

9) There’s an online pizza order store which accepts orders for Veg-Pizza and Non-veg Pizza each in different
sizes and types. Size of Pizza are: (6,9,12 inches); Types of Pizza are: (PLAIN, DELUXE, SUPREME).

The cost of Pizza are as follows:

• For Veg-Pizza the base price is Rs.50 multiplied by the size of pizza for PLAIN type and extra charges
are added for premium types. (DELUXE Rs.100 extra charge and SUPREME Rs.150 extra charge)
• For NonVeg-Pizza the base price is Rs.100 multiplied by the size of pizza for PLAIN type and extra
charges are added for premium types. (DELUXE Rs.150 extra charge and SUPREME Rs.200 extra
charge)

They also wanted to calculate total sales made. There are a total of 5 classes; one abstract class Pizza,
Classes VegPizza and NonVegPizza, user defined exception class – InvalidPizzaException and Main class
PizzaOnline.

The classes have following properties:

Pizza

It is an abstract class and has following methods:

• abstract float calculatePrice()


• Public Boolean validate(int size, String type) – This method returns true if the valid size and type are
given else returns false.

VegPizza

This extends Pizza, and has private members size and type.(variables)

• pizzaType(int size, String type) – this method validates the size and type of pizza by using validate
method from Pizza, if the result is false it then throws InvalidPizzaException.
Else assigns the values to instance variables size and type.
• Float calculatePrice() – Calculates the price of Pizza for the given size and type using the above prices.

NonVegPizza

This extends Pizza, and has private members size and type.(variables)

• pizzaType(int size, String type) – this method validates the size and type of pizza by using validate
method from Pizza, if the result is false it then throws InvalidPizzaException.
Else assigns the values to instance variables size and type.
• float calculatePrice() – Calculates the price of Pizza for the given size and type using the above prices.

PizzaOnline

This is the class which contains main method, contains a private float variable totalSales.

Contains the following methods:

• float order(Pizza pizza) – calculates price of pizza

Finally, print the cost of the meal.

[L.O.3]

Solution:

import java.util.*;

class InvalidPizzaException extends Exception

public InvalidPizzaException(String s)

super(s);

abstract class Pizza

abstract float calculatePrice();

abstract void pizzaType(int size,String type);

public Boolean validate(int size,String type)

if((size==6 || size==9 || size==12)&&(type.equals("PLAIN") ||


type.equals("DELUXE")||type.equals("SUPREME")))

return true;

else

return false;

}
class VegPizza extends Pizza

private int size=0;

private String type;

public void pizzaType(int size,String type)

Boolean test=super.validate(size,type);

try{

if(test==false)

throw new InvalidPizzaException("Details are invalid");

this.size=size;

this.type=type;

}catch(InvalidPizzaException e)

System.out.println("Exception caught");

public float calculatePrice()

float x=50*size;

if(type.equals("DELUXE"))

x+=100;

else if(type.equals("SUPREME"))

x+=150;

return x;

class NonVegPizza extends Pizza

private int size=0;

private String type;


public void pizzaType(int size,String type)

Boolean test=super.validate(size,type);

try{

if(test==false)

throw new InvalidPizzaException("Details are invalid");

this.size=size;

this.type=type;

}catch(InvalidPizzaException e)

System.out.println("Exception caught");

public float calculatePrice()

float x=100*size;

if(type.equals("DELUXE"))

x+=150;

else if(type.equals("SUPREME"))

x+=200;

return x;

public class PizzaOnline

private static float totalSale=0;

static float order(Pizza p)

Scanner sc=new Scanner(System.in);

int size;

String type;
System.out.println("Enter type and size of pizza");

type=sc.nextLine();

size=sc.nextInt();

p.pizzaType(size,type);

float f=p.calculatePrice();

return f;

/*static float getTotalSales()

return totalSale;

}*/

public static void main(String args[])

Scanner s=new Scanner(System.in);

System.out.println("Enter type of pizza (veg/nonveg)");

String t=s.nextLine();

Pizza p;

if(t.equals("veg"))

p=new VegPizza();

else

p=new NonVegPizza();

float g=PizzaOnline.order(p);

totalSale+=g;

System.out.println("Total cost is "+totalSale);

10) You are working in a bank in the foreign currency department and are asked by your superiors to develop a
program which takes in the value of rupee as dynamic input and converts it into dollars and euros. It is known
that 1 dollar = 69.79 rupees and 1 euro = 78.40 rupees (Use Observer Design Pattern) [L.O.4]

Solution:

import java.io.*;
import java.util.*;
class CurrencyConverter
{

float rupee;
Euro euro;
Dollar dollar;
Scanner sc=new Scanner(System.in);
public CurrencyConverter(Euro euro,Dollar dollar)
{
this.euro=euro;
this.dollar=dollar;
}

public float getRupeeValue()


{
System.out.println("Enter value in rupee:");
return sc.nextFloat();
}

public void ChangeCurrency()


{
rupee=getRupeeValue();
euro.update(rupee);
dollar.update(rupee);
}
}
class Euro
{
float euros;
public void update(float rupee)
{
euros=rupee/(float) 78.40;
display();
}
public void display()
{
System.out.println("Euro ="+euros);
}
}
class Dollar
{
float dollars;
public void update(float rupee)
{
dollars=rupee/(float) 69.79;
display();
}
public void display()
{
System.out.println("Dollar ="+dollars);
}
}
public class Main
{
public static void main (String[] args) {
Euro euro=new Euro();
Dollar dollar=new Dollar();
Scanner sc=new Scanner(System.in);
CurrencyConverter con=new CurrencyConverter(euro,dollar);
con.ChangeCurrency();
while(true)
{
System.out.println("1.continue\n2.exit");
int x=sc.nextInt();
if(x==1)
{
con.ChangeCurrency();
}
else
{
break;
}
}
}
}

OOPS LAB-7

1) You are a journalist and are required to submit a report on the number of accidents
that had occurred in your area. Collect the information of accidents caused by car,
bus and bike from your local NGO’s and write a program that will print the number
of accidents of each type that had occurred. (Use Interface and it contains a method
number Of Accidents.) [L.O.1]
Solution:

import java.util.*;
interface Accidents {
void numberofaccidents(int a);
}
class Car implements Accidents {
public void numberofaccidents(int b) {
System.out.println("Total Accidents by Car " + b);
}
}
class Bus implements Accidents {
public void numberofaccidents(int c) {
System.out.println("Total Accidents by Bus " + c);
}
}
class Bike implements Accidents {
public void numberofaccidents(int d) {
System.out.println("Total Accidents by Bike " + d);
}
}
class M {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the car accidents");
Car z = new Car();
int i = sc.nextInt();
z.numberofaccidents(i);
System.out.println("Enter the bus
accidents ");
int x = sc.nextInt(); Bus e = new Bus(); e.numberofaccidents(x);
}
}

2) Mark owns a Xerox shop. He uses a Smart Printer which can Print, Fax and Scan to
render his services to the customers. As the business is booming, he bought and
installed an Economic Printer which can only print. Implement interfaces for both
printers using Interface Segregation Principle. [L.O.5]
Solution:

import java.io.*;

import java.util.*;

interface IPrinter {

void Print();

interface IFax {

void Fax();

interface IScanner {

void Scan();

class EconomicPrinter implements IPrinter {

public void Print()

{
System.out.println("Printers are ready to print the data");

class AllInOnePrinter implements IPrinter, IFax, IScanner {

public void Print()

System.out.println("printers is ready to give print");

public void Fax()

System.out.println("Fax Machine two received a fax message");

public void Scan()

System.out.println("Scanner is ready to scan");

public class Main1demo {

public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.println("Press 1 for print service \n press 2 for print,fax,scan services \n");

System.out.println(" ");
System.out.println("Please enter your service from us");

int choice = in .nextInt();

switch (choice) {

case 1:

System.out.println("welcome to printer services");

EconomicPrinter e = new EconomicPrinter();

e.Print();

break;

case 2:

System.out.println("Welcome to remaining services provided by us");

AllInOnePrinter a = new AllInOnePrinter();

a.Print();

a.Scan();

a.Fax();

break;

default:

break;

3) Dominos wanted to add a pizza customization feature in their app so that the
customer can have the liberty to choose the base and customize the toppings.
Implement the program using decorator design pattern and print the price of the
pizza based on the customized toppings. [L.O.3]
Solution:

package pizzatester;

public class Base implements Pizza {


@Override
public String getDescription() {
return &quot;
Ambigous Pizza Crust & quot;;
}
@Override
public double getCost() {
return 0.00;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package pizzatester;

public class Cheese extends Topping {


public Cheese(Pizza newPizza) {
super(newPizza);
System.out.println( & quot; Adding cheese to pizza & quot;);
}
@Override
public String getDescription() {
return tempPizza.getDescription() + & quot;, Cheese & quot;;
}
@Override
public double getCost() {
return tempPizza.getCost() + 1.00;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package pizzatester;

public class Mushrooms extends Topping {


public Mushrooms(Pizza newPizza) {
super(newPizza);
System.out.println( & quot; Adding mushrooms to pizza & quot;);
}
@Override
public String getDescription() {
return tempPizza.getDescription() + & quot;, Mushrooms & quot;;
}
@Override
public double getCost() {
return tempPizza.getCost() + 1.00;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package pizzatester;

public class Olives extends Topping {


public Olives(Pizza newPizza) {
super(newPizza);
System.out.println( & quot; Adding olives to pizza & quot;);
}
@Override
public String getDescription() {
return tempPizza.getDescription() + & quot;, Olives & quot;;
}
@Override
public double getCost() {
return tempPizza.getCost() + .75;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package pizzatester;

public class Onions extends Topping {


public Onions(Pizza newPizza) {
super(newPizza);
System.out.println( & quot; Adding onions to pizza & quot;);
}
@Override
public String getDescription() {
return tempPizza.getDescription() + & quot;, Onions & quot;;
}
@Override
public double getCost() {
return tempPizza.getCost() + .50;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package pizzatester;

public class Pepperoni extends Topping {


public Pepperoni(Pizza newPizza) {
super(newPizza);
System.out.println( & quot; Adding pepperoni to pizza & quot;);
}
@Override
public String getDescription() {

return tempPizza.getDescription() + & quot;, Pepperoni & quot;;


}
@Override
public double getCost() {
return tempPizza.getCost() + .50;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package pizzatester;

public interface Pizza {


public String getDescription();
public double getCost();
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package pizzatester;

public class PizzaTester {


public static void main(String[] args) {
Pizza pizza1 = new Mushrooms(new Cheese(new Thick()));
System.out.println();
Pizza pizza2 = new Olives(new Onions(new Pepperoni(new Thin())));
System.out.println();
System.out.println( & quot; Description: & quot; + pizza1.getDescription());
System.out.printf( & quot; The price of your pizza is $ % .2 f\ n & quot;, pizza1.getCost());
System.out.println();
System.out.println( & quot; Description: & quot; + pizza2.getDescription());
System.out.printf( & quot; The price of your pizza is $ % .2 f\ n & quot;, pizza2.getCost());
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package pizzatester;

public class Thick extends Base {


@Override
public String getDescription() {
return &quot;
Thick crust w / Spicy Sauce & quot;;
}
@Override
public double getCost() {
return 3.00;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package pizzatester;

public class Thin extends Base {


@Override
public String getDescription() {
return &quot;
Thin crust w / Sweet Sauce & quot;;
}
@Override
public double getCost() {
return 2.50;
}
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
package pizzatester;

public abstract class Topping implements Pizza {


protected Pizza tempPizza;
public Topping(Pizza newPizza) {
this.tempPizza = newPizza;
}
@Override
public String getDescription() {
return tempPizza.getDescription();
}
@Override
public double getCost() {
return tempPizza.getCost();
}
}

4) A bank manager wants to improve the rate of customers using the bank. He
arranged a meeting with a software company to discuss the ways to improve the
customers. You pointed out that the bank interface needs to be more user-friendly
to attract more customers. Use the facade design pattern to implement a program
which contains all the daily transactions like withdraw, deposit and transfer amount.
[L.O.4]
Solution:
import java.io.*;
import java.util.*;
class Bank {
public void Debitamount(String ac, double amount) {
System.out.println(amount + " rs debited from " + ac);
}
public void Creditamount(String ac, double amount) {
System.out.println(amount + " rs credited into " + ac);
}
}
class Customer {
public void transferamount(String ac1, String ac2, double amount) {
Bank Customer1 = new Bank();
Customer1.Debitamount(ac1, amount);
Customer1.Creditamount(ac2, amount);
}
public void Deposit(String ac, double amount) {
Bank Customer2 = new Bank();
Customer2.Creditamount(ac, amount);
}
public void Withdraw(String ac, double amount) {
Bank Customer3 = new Bank();
Customer3.Debitamount(ac, amount);
}
}
class Facadepattern {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("1.Transferamount\n2.Deposit\n3.Withdraw\n");
String s1, s2;
double n;
int a = sc.nextInt();
Customer Cus = new Customer();
switch (a) {
case 1:
System.out.println("Enter ac number from which you need transfer money");
s1 = sc.next();
System.out.println("Enter ac number to which you need transfer money");
s2 = sc.next();
System.out.println("Enter amount that to be transfered");
n = sc.nextDouble();
Cus.transferamount(s1, s2, n);
System.out.println("Amount transfer succesful.....");
break;
case 2:
System.out.println("Enter your ac number");
s1 = sc.next();
System.out.println("Enter amount to Deposit ");
n = sc.nextDouble();
Cus.Deposit(s1, n);
break;
case 3:
System.out.println("Enter your ac number");
s1 = sc.next();
System.out.println("Enter amount to Withdraw ");
n = sc.nextDouble();
Cus.Withdraw(s1, n);
break;
}
}
}

5) The vice-chancellor of KL University came to know that there was a problem for
visitors on identifying the location of the department blocks and their timings. In
order to resolve this issue, you are assigned to design a software that displays the
name of the block for the respective department, timings as well as the HOD of the
department. Implement factory method design pattern to resolve this issue. [L.O.3]
Solution:
import java.io.*;
import java.util.*;
interface University {
void block();
void hod();
void time();
}
class Cse implements University {
@Override
public void block() {
System.out.println("block F1 is alloted to Cse department ");
}
@Override
public void hod() {
System.out.println("The hod of cse department is Dr.Hari kiran vege");
}
@Override
public void time() {
System.out.println("the timings for cse department is monday to saturday 9:00 AM to 5:00 Pm
except Friday");
}
}

class Ece implements University {


@Override
public void block() {
System.out.println("block F2 is alloted to Ece department ");
}
@Override
public void hod() {
System.out.println("The hod of Ece department is Dr.K.CH.SRI KAVYA");
}
@Override
public void time() {
System.out.println("the timings for Ece department is monday to saturday 9:00 AM to 5:00 Pm
except thuresday");
}
}
class Eee implements University {
@Override
public void block() {
System.out.println("block F3 is alloted to Eee department ");
}
@Override
public void hod() {
System.out.println("The hod of Eee department is Dr.K.SUBBA RAO");
}
@Override
public void time() {
System.out.println("the timings for Eee department is monday to saturday 9:00 AM to 5:00 Pm
except tuesday");
}
}

class Depttype {
public University getDepartment(String Dept) {
if (Dept == null) {
return null;
} else if (Dept.equalsIgnoreCase("CSE")) {
return new Cse();
} else if (Dept.equalsIgnoreCase("Ece")) {
return new Ece();
} else if (Dept.equalsIgnoreCase("Eee")) {
return new Eee();
}
return null;
}
}
public class Factorydemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("please Enter department name");
Depttype dept = new Depttype();
String S = sc.next();
University uvi = dept.getDepartment(S);
uvi.block();
uvi.hod();
uvi.time();
}
}

6) A travel agency has many buses which travel long distances. They need their buses
to have a full tank before every journey starts. You are required to develop a
program which will calculate the amount of fuel required to reach the destination
and the average speed that the driver should maintain to reach the destination on
time(Hint: interface one should contain abstract method avg speed and distance that
driver should travel, interface 2 contains time and abstract method fuel, take static
inputs) [L.O.2]
Solution:
interface I1 {
double distance = 100.0; //distance in km
public void averageSpeed();
}
interface I2 {
double time = 6.5; //time in hours
public void Fuelrequired();

}
public class Main implements I1, I2 {
public void averageSpeed() {
double speed = distance / time;
System.out.println("To reach the destination the vehicle should travel with averageSpeed of " +
speed + " km/hr");
}
public void Fuelrequired() {
double Fuel = distance / 12.0;
System.out.println("Fuel required to reach destination is " + Fuel + " liters");
}
public static void main(String[] args) {
Main obj = new Main();
obj.averageSpeed();
obj.Fuelrequired();
}
}

7) Samsung had taken a patent for certain attributes (shape, thickness, weight) and you
are part of Apple and are required to know about the details that they’ve patented.
So, write a java program to retrieve the data. Your program must consist of two
classes in which Samsung class is “final”. The “final” class contains the attributes of
mobile. By using composition in Apple class, retrieve the data from “final” class and
display it to your stakeholders. [L.O.7]
Solution:
final class Mobile {
public void getShape() {
System.out.println("It is rectangular in shape ");
}
public void getThickness() {
System.out.println("It is 7.3mm in thickness ");
}
public void getWeight() {
System.out.println("It weighs 150g ");
}
}
public class Samsung {
public static void main(String args[]) {
Mobile m = new Mobile();
System.out.println("Name of mobile is Samsung ");
m.getShape();
m.getThickness();
m.getWeight();
}
}

8) A car manufacturer wants to manufacture cars as per the customer’s choice of color
and the other materials were predefined by the company. You are the engineer
hired by the car manufacturer to help them out in manufacturing cars in accordance
with customer’s choice of colors. (Use Interface) [L.O.1]
Solution:
import java.util.*;
import java.io.*;
interface Car {
String body_material = "carbon steel";
String wheels = "alloy";
void colour(String c);
void getcar();
}
class Manufacturing implements Car {
String colour = "black";
public void colour(String colour) {
this.colour = colour;
}
public void getcar() {
System.out.println("A car of " + colour + " colour , with " + body_material + "body and " + wheels
+ " wheels is manufactured.");
}
}
class customer {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter your car colour");
String cl = s.nextLine();
Manufacturing newcar = new Manufacturing();
newcar.colour(cl);
newcar.getcar();
}
}

9) Your friend wanted to know about the Christopher Nolan’s Batman Trilogy, and he
has asked you to give brief details about it. You decide to make an event driven
program consisting of classes batmanBegins, theDarkKnight and theDarkKnightRises.
Each class consists of information about the cast, release date and budget.
Implement those classes by using the interface movieInfo. Create one button for
each class such that the information is displayed when it is selected. [L.O.6]
Solution:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class nolan {

public static void main(String args[]) {

JFrame f = new JFrame("Welcome");


JButton b1 = new JButton("Batman Begins");
JButton b2 = new JButton("The dark knight");
JButton b3 = new JButton("The dark knight rises");
JLabel l = new JLabel("The batman Trilogy ");
JFrame f1 = new JFrame("Batman Begins");
JFrame f2 = new JFrame("The dark knight");
JFrame f3 = new JFrame("The dark knight rises");
JButton b = new JButton("<--Back");
JButton ex = new JButton("Exit");

f.add(b1);
f.add(b2);
f.add(b3);
f.add(l);
f.add(ex);

b1.setBounds(100, 150, 200, 50);


b2.setBounds(100, 210, 200, 50);
b3.setBounds(100, 270, 200, 50);
l.setBounds(100, 50, 200, 50);
ex.setBounds(120, 330, 100, 30);

f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);

ex.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();

}
});

b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();

JLabel a1 = new JLabel("batman begins");


JLabel a2 = new JLabel("CAST :Christian bale,katie holmes");
JLabel a3 = new JLabel("RELEASE :17 june 2005");

f1.setSize(400, 400);
f1.setLayout(null);
a1.setBounds(100, 50, 250, 50);
a2.setBounds(100, 100, 250, 50);
a3.setBounds(100, 150, 250, 50);
b.setBounds(120, 200, 100, 50);
f1.add(a1);
f1.add(a3);
f1.add(a2);
f1.add(b);
f1.setVisible(true);

}
});

b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
JLabel c1 = new JLabel("batman begins");
JLabel c2 = new JLabel("CAST :Christian bale,heath ledger ");
JLabel c3 = new JLabel("RELEASE :18 july 2008");

f2.setSize(400, 400);
f2.setLayout(null);
f2.setVisible(true);

c1.setBounds(100, 50, 250, 50);


c2.setBounds(100, 100, 250, 50);
c3.setBounds(100, 150, 250, 50);
f2.add(c1);
f2.add(c2);
f2.add(c3);
f2.add(b);

}
});
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f.dispose();
JLabel d1 = new JLabel("batman begins");
JLabel d2 = new JLabel("CAST :Christian bale,Tom Hardy");
JLabel d3 = new JLabel("RELEASE :20 july 2012");
d1.setBounds(100, 50, 250, 50);
d2.setBounds(100, 100, 250, 50);
d3.setBounds(100, 150, 250, 50);
f3.add(d1);
f3.add(d2);
f3.add(d3);
f3.add(b);

f3.setSize(400, 400);
f3.setLayout(null);
f3.setVisible(true);

}
});
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
f1.dispose();
f2.dispose();
f3.dispose();
f.setVisible(true);

}
});

}
}

10) A student was asked by his faculty to take in two operands and one operator as
inputs and perform the necessary operation using Chain of Responsibility design
pattern. (Do not use switch case or if-else statements) [L.O.3]
Solution:
interface Chain {
public void setNextChain(Chain nextChain);
public void calculate(Numbers request);
}
public class TestCalcChain {
public static void main(String[] args) {
Chain chainCalc1 = new AddNumbers();
Chain chainCalc2 = new SubtractNumbers();
Chain chainCalc3 = new MultNumbers();
Chain chainCalc4 = new DivideNumbers();
chainCalc1.setNextChain(chainCalc2);
chainCalc2.setNextChain(chainCalc3);
chainCalc3.setNextChain(chainCalc4);
Numbers request = new Numbers(10, 2, "/");
chainCalc1.calculate(request);
}
}
class Numbers {
private int number1;
private int number2;
private String calculationWanted;
public Numbers(int newNumber1, int newNumber2, String calcWanted) {
number1 = newNumber1;
number2 = newNumber2;
calculationWanted = calcWanted;
}
public int getNumber1() {
return number1;
}
public int getNumber2() {
return number2;
}
public String getCalcWanted() {
return calculationWanted;
}
}
class DivideNumbers implements Chain {
private Chain nextInChain;
public void setNextChain(Chain nextChain) {
nextInChain = nextChain;
}
public void calculate(Numbers request) {

if (request.getCalcWanted() == "/") {
System.out.print(request.getNumber1() + " / " + request.getNumber2() + " = " +
(request.getNumber1() / request.getNumber2()));
} else {
System.out.print("Only works for +, -, *, and /");
}
}
}
class MultNumbers implements Chain {
private Chain nextInChain;
public void setNextChain(Chain nextChain) {
nextInChain = nextChain;
}
public void calculate(Numbers request) {

if (request.getCalcWanted() == "*") {
System.out.print(request.getNumber1() + " * " + request.getNumber2() + " = " +
(request.getNumber1() * request.getNumber2()));
} else {
nextInChain.calculate(request);
}
}
}
class SubtractNumbers implements Chain {
private Chain nextInChain;
public void setNextChain(Chain nextChain) {
nextInChain = nextChain;
}
public void calculate(Numbers request) {
if (request.getCalcWanted() == "-") {
System.out.print(request.getNumber1() + " - " + request.getNumber2() + " = " +
(request.getNumber1() - request.getNumber2()));
} else {
nextInChain.calculate(request);
}

}
}
class AddNumbers implements Chain {

private Chain nextInChain;


public void setNextChain(Chain nextChain) {
nextInChain = nextChain;
}
public void calculate(Numbers request) {
if (request.getCalcWanted() == "+") {
System.out.print(request.getNumber1() + " + " + request.getNumber2() + " = " +
(request.getNumber1() + request.getNumber2()));
} else {
nextInChain.calculate(request);
}
}
}

11) You are required to perform three operations on a file: Open, close and write. On
execution of each operation the system should print that the particular operation
has been successful. Use command design pattern to implement the above problem.
[L.O.3]
Note: Implement it using Interface.
Solution:
Command.java

public interface Command {


public void execute();
}

class File {
public void openFile() {
System.out.println("File is opened");
}
public void closeFile() {
System.out.println("File is closed");
}
public void writeFile() {
System.out.println("Content is written to file");
}
}

class OpenCommand implements Command {


File f;
public OpenCommand(File f) {
this.f = f;
}
public void execute() {
f.openFile();
}
}

class CloseCommand implements Command {


File f;
public CloseCommand(File f) {
this.f = f;
}
public void execute() {
f.closeFile();
}
}

class WriteCommand implements Command {


File f;
public WriteCommand(File f) {
this.f = f;
}
public void execute() {
f.writeFile();
}
}
-------------------------------------------------------
Client . java

public class Client {


public static void main(String args[]) {
Invoker in = new Invoker();
File f = new File(); in .setCommand(new OpenCommand(f)); in .run(); in .setCommand(new
CloseCommand(f)); in .run(); in .setCommand(new WriteCommand(f)); in .run();
}
}
------------------------------------------------------
Invoker.java

public class Invoker {


Command c;
public void setCommand(Command c) {
this.c = c;
}
public void run() {
c.execute();
}
}

OOPS LAB-8

1) You are working in Swiggy and you are required to write a program which takes in
thecustomer’s order and address and then gives the restaurant, your order details. The
deliveryexecutive will be given both the order detailsand address details. Clone and print
the information sent to the delivery executive and the information sent to the
restaurant separately. [L.O.3]
Solution:
import java.util.Scanner;
class details implements Cloneable{
Scanner sc = new Scanner(System.in);
void hai_details(){
System.out.println("enter your name");
String name = sc.nextLine();
System.out.println("enter your number");
int number = sc.nextInt();
System.out.println("Name : " + name);
System.out.println("number : "+ number);
System.out.println("Enter your address");

System.out.print("enter door number :");

String doorno = sc.nextLine();

System.out.print("enter street name :");

String street = sc.nextLine();

System.out.print("enter land mark :");

String landmark = sc.nextLine();

System.out.print("enter city name :");


String city = sc.nextLine();
//Order obj = new Order();
System.out.println("door no" + doorno);
System.out.println("street " + street);
System.out.println("land mark " + landmark);
System.out.println("city " + city);
}

void hai_Order(){

System.out.print("enter your items");


String order = sc.nextLine();
System.out.println(order);
}

public Object clone() throws CloneNotSupportedException {


return (details) super.clone();

}
}
class Test {

public static void main(String[] args) {


try{
details obj1 = new details();
details obj2 = (details)obj1.clone();
obj2.hai_details();
}
catch(CloneNotSupportedException e) {
e.printStackTrace();
}

2) The Vijayawada Traffic Police has asked you to develop a program which takes in the car
number, name and the fine and stores it in a vector. Then compare the fine and sort
them in ascending order and print them. (Use comparable interface) [L.O.2]
Solution:
import java.util.*;
class Owner implements Comparable<Owner>{
int carno;
String name;
int fine;
Owner(int carno,String name,int fine){
this.carno=carno;
this.name=name;
this.fine=fine;
}

public int compareTo(Owner own){


if(fine==own.fine)
return 0;
else if(fine>own.fine)
return 1;
else
return -1;
}
}

public class TestSort1{


public static void main(String args[]){
Vector<Owner> al=new Vector<Owner>();
al.add(new Owner(2811,"Vijay",6785));
al.add(new Owner(1006,"Ajay",4598));
al.add(new Owner(6105,"Jai",2100));

Collections.sort(al);
for(Owner own:al){
System.out.println(own.carno+" "+own.name+" "+own.fine);
}
}
}

3) As an assignment, you were asked by your faculty to develop a program which takes in
the ID number and name as inputs and converts them into a byte stream and store that
into a file. (Use Serializable)[L.O.1]
Solution:
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Student implements Serializable
{
public Student(name , id, sec)
{
System.out.println(name);
System.out.println(id);
System.out.println(sec);
}
}
public class Serializationclass
{
public static void main (String args[])throws Exception
{
Student s1 =new Student("TRINADH","576",5);
FileOutputStream fout=new FileOutputStream("add.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
//out.flush();
}
}

4) The Section IV Students of K L university want to save the details ofstudents present in
their class which include student ID number and student name. Help them by creating a
java program usingvectors.Your program should contain methods to add new
students,display students,find students,remove students.(hint: use 2 vectors v1to save
name,v2 to save ID.no,the S.no of student will be the index ofvector)[L.O.4]
Solution:
import java.util.*;
import java.io.*;
import java.lang.*;
public class Main {

public void addStudent(Vector v,Vector v1)


{
Scanner sc=new Scanner(System.in);
System.out.println("Enter name of student :");
v.add(sc.next());
System.out.println("Enter id number of ");
v1.add(sc.next());
}
public void removeStudent(Vector v,Vector v1)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter sno of student ");
int n=sc.nextInt();
v.remove(n);
v1.remove(n);
}
public void findStudent(Vector v1)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter id number of student ");
boolean b=v1.contains(sc.next());
if(b==true)
{
System.out.println("Student present in class");
}
else{
System.out.println("Student not present in class ");
}
}
public void Display(Vector v,Vector v1)
{
Iterator itr=v.iterator();
Iterator itr1=v1.iterator();
int c=1;
while (itr.hasNext())
{
System.out.println("sno : "+c+" , name : "+itr.next()+" , idno : "+itr1.next());
c++;
}
}
public static void main(String[] arg)
{
Scanner sc=new Scanner(System.in);
Vector v = new Vector();
Vector v1=new Vector();
Main obj=new Main();

while(true)
{
System.out.println("1.addStudent\n2.removeStudent\n3.findStudent\n4.Display\n5.exit");
int x=sc.nextInt();
if(x==1)
obj.addStudent(v,v1);
if(x==2)
obj.removeStudent(v,v1);
if(x==3)
obj.findStudent(v1);
if(x==4)
obj.Display(v,v1);
if(x==5)
System.exit(0);
}

}
}

5) A student was asked by his faculty to take in two lists as inputs and compare and sort
them. As the output he should be printing the common elements in both the lists in the
first line. He should then print the elements that are present in the first list but not in
the second list in a new line and then print the elements present in second list but not in
the first one is another line.[L.O.2,4]
Solution:
public class ArrayListExample
{
public static void main(String[] args)
{
ArrayList<String> listOne = new ArrayList<>(Arrays.asList("a", "b", "c", "d","f"));

ArrayList<String> listTwo = new ArrayList<>(Arrays.asList("a", "b", "c", "d","e"));

Collections.sort(listOne);
Collections.sort(listTwo);

boolean isEqual = listOne.equals(listTwo);


System.out.println(isEqual);
listOne.retainAll(listTwo);
System.out.println(listOne);
listOne.removeAll(listTwo);
System.out.println(listOne);
listTwo.removeAll(listOne);
System.out.println(listTwo);

}
}

6) A worker is assigned with a work by the Management and there are few required
components to get the work done by the worker. He makes the list of the components
required and clone them while also forwarding a copy to the management. The
management would then remove the availablecomponents from the cloned list and
then would forward the unavailable list to the owner for requirement. Help the
management to display the cloned list along with hash codeand the list of the
components that are sent to the owner. [L.O.3,4]
Solution:
import java.io.*;
import java.util.ArrayList;

public class Main {

public static void main(String args[])


{

System.out.println("Enter the required accessories for worker");


ArrayList<String> list
= new ArrayList<String>();

list.add("Wood");
list.add("Art");
list.add("GAllery");
list.add("Nails");

System.out.println("The accessories required: "


+ list);

ArrayList list2 = new ArrayList();

list2 = (ArrayList)list.clone();

System.out.println("After cloning "


+list2);
System.out.println("removing items");
list2.remove(1);
System.out.println("Final list "
+list2);
}
}

7) Your mother works as a teacher for a Secondary School. At the end of the academic
year, she needs to finalize the ranks of the students according to the total marks
obtained by students. Help her in doing this by using comparable Interface. She would
be giving you the LISTwhich consists of details of the student consisting Name, ID, Total
marks of the Student. [L.O.2,4]
Solution:
import java.util.*;
class Student implements Comparable<Student>
{
int Marks;
String name;
int rollno;
Student(int rollno,String name,int Marks )
{
this.rollno=rollno;
this.name=name;
this.Marks=Marks;
}

public int compareTo(Student st)


{
if(Marks==st.Marks)
return 0;
else if(Marks>st.Marks)
return 1;
else
return -1;
}
}
class Test
{
public static void main(String args[]){
ArrayList<Student> s=new ArrayList<Student>();
s.add(new Student(101,"Sai",486));
s.add(new Student(106,"Abhi",273));
s.add(new Student(105,"Vaishnavi",590));
Collections.sort(s);
for(Student st:s)
{
System.out.println(st.rollno+" "+st.name+" "+st.Marks);
}
}
}

8) A student wants to increase his laptop performance by increasing the ram size by adding
an additional 8 Gb RAM.He wants to buy it at an optimal cost ,so he visited different
online stores and collected ram details(price,brand,store,productid) from different
stores. Help him by writing a java program that stores the data in anarraylist and sort in
ascending order of price using java Comparable interface. [L.O.2,4]
Solution:
import java.util.*;

class Ram implements Comparable<Ram>

String Ramid,Rambrand,store;

int price;

Ram(String Ramid,String Rambrand,String store,int price)

this.Rambrand=Rambrand;

this.Ramid=Ramid;

this.store=store;

this.price=price;

public int compareTo(Ram r)

if(price==r.price)

return 0;

else if(price>r.price)

return 1;

else

return -1;

public class Lab8


{
public static void main(String args[])

Scanner sc=new Scanner(System.in);

ArrayList<Ram> al=new ArrayList<Ram>();

System.out.println("Enter no of inputs");

int n=sc.nextInt();

for(int i=0;i<n;i++)

System.out.print("\nEnter Ramid");

String Ramid=sc.next();

System.out.print("\nEnter brand");

String Rambrand=sc.next();

System.out.print("\nEnter store");

String store=sc.next();

System.out.print("\nEnter price");

int price=sc.nextInt();

al.add(new Ram(Ramid,Rambrand,store,price));

Collections.sort(al);

for(Ram r:al)

System.out.println(r.price);

}
}

9) Your friend wants to have a security system for his room which depends on Floor
sensitivity, Temperature sensitivity and Sound sensitivity. These factors should be
activated when he exits the room and the door should remain locked, whereas the door
should unlock,and the factors should be deactivated when he enters the room. Develop
a program to help him out.( All the required methods should be defined in an interface
and implement using State Design Pattern)[L.O.5]
Solution:
interface SecurityState
{
public void setSecurity(SecurityStateUpdate sec);
}
class SecurityStateUpdate
{
private static SecurityState currentstate = new UserAbsence();
public void setState(SecurityState state)
{
currentstate = state;
}
public void setSecurity()
{
currentstate.setSecurity(this);
}
}
class UserAbsence implements SecurityState
{
public void setSecurity(SecurityStateUpdate s)
{
System.out.println("Activated User Absence Security");
System.out.println("Door Locked");
System.out.println("Floor Sensitivity Activated");
System.out.println("Temperature Sensitivity Activated");
System.out.println("Sound Sensitivity Activated");
}
}
class UserPresence implements SecurityState
{
public void setSecurity(SecurityStateUpdate s)
{
System.out.println("Activated User Presence Security");
System.out.println("Door Locked");
System.out.println("Floor Sensitivity Deactivated");
System.out.println("temperature Sensitivity Deactivated");
System.out.println("Sound Sensitivity Deactivated");
}
}
class Security
{
public static void main(String[] args)
{
SecurityStateUpdate security = new SecurityStateUpdate();
security.setSecurity();
security.setState(new UserPresence());
System.out.println();
security.setSecurity();
}
}

OOPS LAB-9

1) You are given a task of printing the first five natural numbers assigned to all three
different threads which should be created by implementing runnable interface. Run
this program for three times and check the printing style each time. [L.O.1]

Solution:
class Thread1 implements Runnable

String name;

Thread t;

Thread1(String threadname)

name = threadname;

t = new Thread(this, name);

System.out.println("thread one: " + t);

t.start();

public void run()

try {

for(int i = 1; i <= 5; i++) {

System.out.println(name + ": " + i);

Thread.sleep(3000);

catch (InterruptedException e) {

System.out.println(name + "Interrupted");

}
System.out.println(name + " exiting.");

class Thread2 implements Runnable {

String name;

Thread t;

Thread2(String threadname) {

name = threadname;

t = new Thread(this, name);

System.out.println("thread two: " + t);

t.start();

public void run() {

try

for(int i = 1; i <= 5; i++) {

System.out.println(name + ": " + i);

Thread.sleep(2000);

catch (InterruptedException e) {

System.out.println(name + "Interrupted");

System.out.println(name + " exiting.");

class Thread3 implements Runnable {

String name;

Thread t;

Thread3(String threadname) {

name = threadname;

t = new Thread(this, name);

System.out.println("thread three: " + t);


t.start();

public void run() {

try {

for(int i = 1; i <= 5; i++) {

System.out.println(name + ": " + i);

Thread.sleep(500);

catch (InterruptedException e) {

System.out.println(name + "Interrupted");

System.out.println(name + " exiting.");

class MultiThreadDemo {

public static void main(String args[]) {

new Thread1("Thread-1");

new Thread2("Thread-2");

new Thread3("Thread-3");

try {

Thread.sleep(2000);

catch (InterruptedException e) {

System.out.println("Main thread Interrupted");

System.out.println("Main thread exiting.");

2) Rohan was asked by his teacher to develop a program which takes in a dynamic user
input and prints all the prime numbers till that number and then prints all the
composite numbers till that number. Help him out by developing the program to do
so. Use one thread each for both prime and composite numbers and apply the
concept of thread synchronization [L.O.3]

Solution:
import java.io.*;

import java.util.*;

class Number{

synchronized void display(int a,int x){

if(x==0)

System.out.println("prime numbers ");

if(x==1)

System.out.println("non prime numbers ");

for(int i=2;i<=a;i++)

int flag=0;

for(int j=2;j<i/2+1;j++)

if(i%j==0)

flag=1;

break;

if(flag==x)

System.out.println(i);

try{

Thread.sleep(500);

catch(Exception e){

System.out.println(e);

}
}

class MyThread_1 extends Thread{

Number n;

MyThread_1(Number n){

this.n=n;

public void run(){

n.display(20,0);

class MyThread_2 extends Thread{

Number n;

MyThread_2(Number n){

this.n=n;

public void run(){

n.display(20,1);

public class Test1{

public static void main(String args[]){

Number obj = new Number();

MyThread_1 t1=new MyThread_1(obj);

MyThread_2 t2=new MyThread_2(obj);

t1.start();

t2.start();

}
3) You are editing your friend’s short film which is made up of 15 frames. You need to
develop a program which makes sure that the audio and video are running parallelly.
Use one thread each for audio and video. Make sure both the threads have equal
sleep time. Use runnable interface to implement the threads. [L.O.1]
Solution:
import java.io.*;
import java.util.*;
class A1 implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Audio");
try {
Thread.sleep(100);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
class B1 implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Vedio");
try {
Thread.sleep(100);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
public class Main {

public static void main(String[] args) throws Exception {


A1 t1=new A1();
B1 t2=new B1();
Thread obj1=new Thread(t1);
Thread obj2=new Thread(t2);
obj1.start();
obj2.start();
}

4) Tony was asked to develop a program which takes in five alphabets as dynamic user
input and stores them in an array. He passes the array to two threads. First one
should traverse the array, and the vowels present in it should be printed and the
second thread should print the consonants present in the array. Help him out by
writing the program. [L.O.1]
Solution:
class Consonant implements Runnable

String name;

Thread t;

char ar[];

Consonant(String threadname,char ar[])

name = threadname;

this.ar=ar;

t = new Thread(this, name);

System.out.println("thread one: " + t);

t.start();

public void run()

try

for(char i : ar) {

char x = i;

if(!(x=='a')&&!(x=='e')&&!(x=='i')&&!(x=='o')&&!(x=='u'))

System.out.println(x+" is a Consonant");

Thread.sleep(3000);
} catch (InterruptedException e) {

System.out.println(name + "Interrupted");

System.out.println(name + " exiting.");

class Vowel implements Runnable {

String name;

Thread t;

char ar[];

Vowel(String threadname,char ar[])

this.ar=ar;

name = threadname;

t = new Thread(this, name);

System.out.println("thread two: " + t);

t.start();

public void run()

try {

for (char i : ar) {

char x = i;

if((x=='a')||(x=='e')||(x=='i')||(x=='o')||(x=='u'))

System.out.println(x+" is a vowel");

Thread.sleep(2000);

catch (InterruptedException e) {

System.out.println(name + "Interrupted");
}

System.out.println(name + " exiting.");

class Multi{

public static void main(String args[]) {

char ar[]={'a','g','c','f','j'};

new Consonant("Thread-1",ar);

new Vowel("Thread-2",ar);

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

System.out.println("Main thread Interrupted");

System.out.println("Main thread exiting.");

5) You are asked to take two integer values as dynamic user inputs. The values are then
passed to two threads where their respective multiplication table’s logic (up to 10)
should be written in a synchronized block and print them. [L.O.3]
Solution:
class Table
{
//synchronized method
synchronized void printTable(int n)
{
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(1000);
}catch(InterruptedException ie){}
}
}
}
class MyThread1 extends Thread
{
//vars
Table t;

//param.constructor
MyThread1(Table t){
this.t = t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread
{
//vars
Table t;

//param.constructor
MyThread2(Table t){
this.t = t;
}
//method
public void run(){
t.printTable(10);
}
}

class MultiTaskDemo2
{
public static void main(String[] args)
{
Table t1 = new Table();

MyThread1 m1 = new MyThread1(t1);


m1.start();

MyThread2 m2 = new MyThread2(t1);


m2.start();
}
}

6) You are asked to take two threads which print the statement “hello world from
thread ______ (thread name)” five times where it should be written in a
synchronized method. Develop a program to do so. [L.O.3]
Solution:
class Check_Count implements Runnable

public void run()

for(int i=0;i<5;i++)

synchronized(this)
{

String name=Thread.currentThread().getName();

System.out.println("Hello from "+name);

class Check

public static void main(String args[])

Check_Count c=new Check_Count();

Thread t1=new Thread(c);

t1.start();

Thread t2=new Thread(c);

t2.start();

7) Ram is working in Indigo Airlines and has been asked by his superiors to develop a
program which helps train the newly recruited air flight attendants by taking in their
name, designation and the flight starting point and destination to which they’re
allotted. It should then print the information in the following format:
Welcome on board to Indigo Airlines
Good morning (Time of the day)!
This is your _____ (Designation), _____ (Name) speaking!
Thank you for choosing Indigo Airlines to travel from ____ (Starting point) to _____
(Destination)
Wish you have a safe and comfortable journey.
(Implement the threads using runnable interface by extending a thread class) [L.O.2]

Solution:
import java.io.*;

import java.util.*;

class Cabincrew{

public static void pilot(String t ,String fromplace , String toplace,String designation , String hname){

System.out.println("Welcome on board to Indigo airlines");

System.out.println("Good"+ t + "everyone!!");

System.out.println("These is your "+ designation+" "+ hname + " here");

System.out.println("Thank you for choosing indigo airline today for travelling from "+
fromplace + " to " + toplace);

try{

Thread.sleep(100);

catch(Exception e){System.out.println(e);}

class Flight extends Cabincrew implements Runnable{

public void run(){

System.out.println("Wish you a enjoyable stay");

public class Flightattendant{

public static void main(String args[]){

Scanner in = new Scanner(System.in);

System.out.println("welcome air hostees ");

Flight f = new Flight();

System.out.println("please enter the details of your flight time ");

String time= in.next();

System.out.println("please enter the your designation");

String position=in.next();

System.out.println("please enter your name ");


String name=in.next();

System.out.println("please enter the destination of your flight ");

String dest=in.next();

System.out.println("please enter the Origin of your flight ");

String org=in.next();

f.pilot(time , org , dest, position , name );

Thread t1 = new Thread(f);

t1.start();

OOPS LAB-10

1. Akash was asked by his faculty to take in ten integer values as dynamic user inputs and
store them in a treeset. He was then asked to print the minimum and maximum value
from the given values and find the sum of the given values (Use iterator). He was also
asked to take another integer as input and check whether it is present in the treeset or
not. Help him out by writing a program for the above statement. [L.O.1]
Solution:
import java.util.*;

class Exp1
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
TreeSet<Integer> ts1 = new TreeSet<Integer>();
int n,i,a,sum=0,r,x;
System.out.println("Number of entries :");
n=sc.nextInt();
for(i=0;i<n;i++)
{
a=sc.nextInt();
ts1.add(a);
}
System.out.println("Minimum value is "+ts1.first());
System.out.println("Maximum value is "+ts1.last());
Iterator it=ts1.iterator();
while(it.hasNext())
{
x=(int)it.next();
sum=sum+x;
}
System.out.println("Sum of entered value is "+sum);
System.out.println("Enter value to be removed ");
r=sc.nextInt();
if(ts1.contains(r))
{
ts1.remove(r);
System.out.println("Number removed");
}
else
System.out.println("Number is not removed");
}
}

2. You are part of an agency which helps the Government in collecting the census data and
are required to write a program which verifies the names of the users from a certain
street. The program should take in the number of names to be entered and the names
of the citizens in that street. It should also enable you to search for a citizen’s name and
print yes if the name is present and no if it is not. Store the names in a Treeset. [L.O.1]
Solution:
import java.util.*;
import java.util.SortedSet;
import java.util.TreeSet;
public class CreateTreeSetExample
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter no of names");
int value = sc.nextInt();
SortedSet <Object> name = new TreeSet <Object> ();
System.out.println("enter names");
for(int i=0;i<value;i++)
{
String n= sc.next();
name.add(n);
}
System.out.println("the created tree set : " + name);
System.out.println("enter the search element");
String s= sc.next();
boolean blnExists = name.contains(s);
System.out.println(blnExists);
}
}
3. Ram is working as a Data entry operator in KLEF and wants you to develop a program
which helps him digitalize the process of entering data into registers. Your
program should be able to add records of students into the register, retrieve the records
whenever needed and remove a student’s record when needed. It should also be able to
clear the entire register when needed. Store them in a Treeset and use Singleton Design
Pattern to do so. [L.O.1]

Solution:
import java.util.*;

class Singleton
{
TreeSet<String> t=new TreeSet<String>();
private Singleton(){}
private static class SingletonHelper
{
private static final Singleton unique=new Singleton();
}
public static Singleton getInstance()
{
return SingletonHelper.unique;
}
public void setData(String s)
{
t.add(s);
}
public void clearData()
{
t.clear();
}
public void removeData(String s)
{
if(t.remove(s))
System.out.println("Item has been deleted");
else
System.out.println("Item cannot be detected");
}
public void getData()
{
System.out.println("Size is "+t.size());
Iterator it=t.iterator();
while(it.hasNext())
System.out.println(it.next());
}
}

public class Test


{
public static void main(String args[])
{
Singleton h=Singleton.getInstance();
Scanner s=new Scanner(System.in);
int n,i;
System.out.println("Number of entries ");
n=s.nextInt();
String st;
for(i=0;i<n;i++)
{
st=s.next()+s.nextLine();
h.setData(st);
}
h.getData();
System.out.println("Enter the item to be deleted ");
st=s.nextLine();
h.removeData(st);
h.getData();
h.clearData();
h.getData();
}
}

4. Rajesh wants to you to suggest him a movie to watch based on a list of 5 movies given
by him. He wants the criteria of suggestions to be rating, name and year of release.
Develop a program which sorts the movies by using all the three attributes individually
and prints them accordingly. (Use comparable interface) [L.O.3]

Solution:
import java.io.*;
import java.util.*;

class Movie implements Comparable<Movie>


{
private double rating;
private String name;
private int year;
public int compareTo(Movie m)
{
return this.year - m.year;
}

public Movie(String nm, double rt, int yr)


{
this.name = nm;
this.rating = rt;
this.year = yr;
}
public double getRating() { return rating; }
public String getName() { return name; }
public int getYear() { return year; }
}

class RatingCompare implements Comparator<Movie>


{
public int compare(Movie m1, Movie m2)
{
if (m1.getRating() < m2.getRating()) return -1;
if (m1.getRating() > m2.getRating()) return 1;
else return 0;
}
}

class NameCompare implements Comparator<Movie>


{
public int compare(Movie m1, Movie m2)
{
return m1.getName().compareTo(m2.getName());
}
}

class Main
{
public static void main(String[] args)
{
ArrayList<Movie> list = new ArrayList<Movie>();
list.add(new Movie("Force Awakens", 8.3, 2015));
list.add(new Movie("Star Wars", 8.7, 1977));
list.add(new Movie("Empire Strikes Back", 8.8, 1980));
list.add(new Movie("Return of the Jedi", 8.4, 1983));

System.out.println("Sorted by rating");
RatingCompare ratingCompare = new RatingCompare();
Collections.sort(list, ratingCompare);
for (Movie movie: list)
System.out.println(movie.getRating() + " " +
movie.getName() + " " +
movie.getYear());

System.out.println("\nSorted by name");
NameCompare nameCompare = new NameCompare();
Collections.sort(list, nameCompare);
for (Movie movie: list)
System.out.println(movie.getName() + " " +
movie.getRating() + " " +
movie.getYear());

System.out.println("\nSorted by year");
Collections.sort(list);
for (Movie movie: list)
System.out.println(movie.getYear() + " " +
movie.getRating() + " " +
movie.getName()+" ");
}
}

5. Riya is a bibliophile and wants you to develop a program which takes in 5 words from a
dictionary as dynamic user input and stores them in a Hashset. It should then print them
in lexicographical order. [L.O.2]
Solution:
import java.util.*;
public class Hs {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter no.of words to take:");
int n=sc.nextInt();
HashSet<String> hs = new HashSet<String>();
for(int i=0;i<n;i++)
{
System.out.println("Enter the word:");
String s=sc.next();
hs.add(s);
}
System.out.println("Original HashSet: "+ hs);
TreeSet<String> ts = new TreeSet<String>(hs);
System.out.println("HashSet elements "+ "in sorted order "+ "using TreeSet: "+ ts);
}
}

6. Stuti was asked to find maximum and minimum from a given set of numbers as her
assignment. Help her out by developing a program which takes in 10 numbers as a
dynamic user input and store them in a Hashset. Then it should sort the numbers and
print the maximum and minimum values from that list of numbers. [L.O.2]
Solution:
import java.util.*;
public class Hs2 {
public static void main(String args[])
{
Object obj1,obj2;
Scanner sc=new Scanner(System.in);
System.out.println("Enter no.of values to take:");
int n=sc.nextInt();
HashSet<Integer> hs = new HashSet<Integer>();
for(int i=0;i<n;i++)
{
System.out.println("Enter the number:");
int s=sc.nextInt();
hs.add(s);
}
System.out.println("Original HashSet: "+ hs);
obj1 = Collections.max(hs);
System.out.println("Max.value in the Hashset is :"+obj1);
obj2 = Collections.min(hs);
System.out.println("Min.value in the Hashset is :"+obj2);
/* TreeSet<Integer> ts = new TreeSet<Integer>(hs);
System.out.println("Lowest value : " + ts.first());
System.out.println("Highest value : " + ts.last());*/
}
}

7. Sara is the CEO of your company and wants to know about the various packages the
company is offering to the employees. You are asked by Sara to develop a program
which takes in the Salaries of 10 employees as Dynamic User Input and store them in a
Hashset. It should then print the various packages offered by the company in a sorted
order. [L.O.3]
Solution:
import java.util.*;
class Employee implements Comparable<Employee>
{
int Salary;
String name;
Employee(int Salary,String name)
{
this.Salary=Salary;
this.name=name;
}

public int compareTo(Employee st)


{
if(Salary==st.Salary)
return 0;
else if(Salary>st.Salary)
{
return 1;
}
else
{
return -1;
}
}
}
class TestSort
{
public static void main(String args[])
{
HashSet<Employee> al=new HashSet<Employee>();
al.add(new Employee(45600,"Rohit"));
al.add(new Employee(59000,"Sam"));
al.add(new Employee(39800,"Sai"));
List<Employee> s = new ArrayList<Employee>(al);//We can't sort by using comparable so we
convert in into list
Collections.sort(s);
//Collections.sort(al); //If we use this then it shows error.
System.out.println("Availabe Salary packages");
for(Employee st:s)
{
System.out.println(st.Salary);
}
}
}

8. Ram has a hobby of collecting coins. He loves collecting coins with different materials
like gold, silver, bronze, aluminum, etc. He visits his grandma’s home and finds a box
containing huge number of ancient coins. He then takes all of them and place them in
his collection. Later, he displays his collection to his family by picking the coins randomly
from his sack containing his collection. You are supposed to show the whole process by
displaying the random coins using Hashset. [L.O.2]

Solution:
import java.util.*;
class You{
public static void main(String args[]){
Scanner l = new Scanner(System.in);
HashSet<String> s = new HashSet<String>();
s.add(l.nextLine());
s.add(l.nextLine());
s.add(l.nextLine());
s.add(l.nextLine());
Iterator<String> i=s.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}

9. The details of enrolled students for JAVA Training session is to be maintained by the
Lecturer. He assigns you the task of creating it, asking you to create a class ‘Student’
taking in the required details of the student consisting Name, Id, Branch. You need to
explicitly convert the details in the class to the Hashset. Finally, the register should have
the details of Students in the ascending order of their ID numbers. Get this done by
using Hashset and comparable interface. [L.O.3]
Solution:
import java.util.*;
class StudentInfo implements Comparable<StudentInfo>
{
int id;
String name;
String branch;
public StudentInfo(int id, String name, String branch){
this.id = id;
this.name = name;
this.branch = branch;
}
public int compareTo(StudentInfo st){
if(id==st.id)
return 0;
else if(id>st.id)
return 1;
else
return -1;
}
}
class Hash {
public static void main(String[] args) {
HashSet<StudentInfo> set=new HashSet<StudentInfo>();
StudentInfo b1=new StudentInfo(180030310,"Kamal","CSE");
StudentInfo b2=new StudentInfo(180030244,"Akhil","ECE");
StudentInfo b3=new StudentInfo(180030148,"Mai","EEE");
set.add(b1);
set.add(b2);
set.add(b3);
ArrayList<StudentInfo> l = new ArrayList<StudentInfo>(set);
Collections.sort(l);
for(StudentInfo b:l){
System.out.println(b.id+" "+b.name+" "+b.branch);
}
}
}
OOPS LAB-11

1) You are the head of your project team and are required to store the mail ID’s and ID
numbers of all your batchmates. Develop a program which takes in the details of the 7
team members as dynamic user input and store them in Hashmap. It should print the
details and it should also be able to help you search for a Mail ID using the ID number.
[L.O.2]

Solution:
import java.util.*;
import java.io.*;
class A{

private A()
{

}
HashMap<String,String> t=new HashMap<String,String>();
private static A obj=null;
public static A getA()
{
if(obj==null)
obj=new A();
return obj;
}
public void display()
{
System.out.println(t);
}

public void add(String id,String mail)


{
t.put(id,mail);
}
public void find(String id)
{
System.out.println(t.get(id));
}
}
public class Main
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
A obj=A.getA();
while(true)
{
System.out.println("1.add new Mail Id\n2.display\n3.Find mail id\n4.exit");
int x=sc.nextInt();
if(x==1)
{
System.out.println("enter student id");
String id=sc.next();
System.out.println("Enter new mail id");
String s=sc.next();
obj.add(id,s);
}
else if(x==2)
{
obj.display();
}
else if(x==3)
{
System.out.println("Enter student id");
String i=sc.next();
obj.find(i);
}
else
{
break;
}
}
}
}

2) Neha is working in the census department and wants to know the population details of
10 districts. Help her out by developing a program which takes in the name and population
of the districts as dynamic user inputs and stores them into a Treemap. It should also be
able to take in the name of a district from that list and print the districts having lesser
population than the given district. It should also be able to take in another district and
print the districts having greater population than given district. Also sort and print the
districts in descending order. [L.O.1]

Solution:
import java.io.*;
import java.util.*;
public class Treemap1{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
// creating tree map

TreeMap<String,Integer> map=new TreeMap<String,Integer>();

// adding details of the program

map.put("Adilabad",2000000);
map.put("hyderabad",3100000);
map.put("Karimnagar",3000000);
map.put("khammam",2210000);
map.put("Mahbunagar",3700000);
map.put("Medak",2260000);
map.put("Nalgonda",2850000);
map.put("Nizamabad",2030000);
map.put("RangaReddy",2551000);
map.put("Warangal",2810000);

// printing the population of each district above the given value


System.out.println("Enter the district name to know population");
String s=in.next();
System.out.println(map.tailMap(s));

// printing the population of each district below the given value


System.out.println("Enter the district name to know population");
String a=in.next();
System.out.println(map.tailMap(a));

// printing the population of each district in telangana in descending order

System.out.println(map.descendingMap());
}
}

3) Khyati is the Vijayawada railway station incharge and wants to digitalize the register for
the loco pilots and has asked you to develop a program which helps in doing so. It should
take in the details of 10 trains for that day (driver name, train number) as dynamic user
input and store them in a Hashmap. It should then be able to add the details of a new loco
pilot and his on-duty train number and also should be able to delete an entry when
needed. The program should also be able to update the details of an entry if a loco pilot
is on leave or if the train assigned to him is changed. [L.O.2]

Solution:
import java.io.*;
import java.util.*;
public class Hashmap{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,String>();

// adding details of loco pliot to the hashset

map.put(12739,"Ravi");
map.put(22203,"Ramu");
map.put(11020,"Gaurav");
map.put(12514,"Rahul");
map.put(12703,"Vijay");
map.put(12705,"Amit");
map.put(12709,"Virendra Singh");
map.put(12713,"Ajay");
map.put(12759,"Gopal");
map.put(12763,"Abdul Ali");
System.out.println("The below list conatins 10 locopilots alloted to trains from BZA
to SCJN");
System.out.println(" ");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+ m.getValue());
}
System.out.println(" ");
System.out.println("Number of trains running in these route as per present entries:
"+map.size());
System.out.println(" ");
System.out.println("using put if absent method");
System.out.println(" ");
map.putIfAbsent(17213,"Md Khan");
map.putIfAbsent(12705,"Venu");
map.putIfAbsent(18111,"Rama Murthy");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+ m.getValue());
}
System.out.println(" ");
System.out.println("Number of trains running in these route as per present entries:
"+map.size());
System.out.println(" ");
System.out.println(" ");
System.out.println("using remove method");
System.out.println(" ");
map.remove(12703);
map.remove(12705);
map.remove(12739);
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+ m.getValue());
}
System.out.println(" ");
System.out.println("Number of trains running in these route as per present entries:
"+map.size());
System.out.println(" ");
System.out.println("using replace method");
System.out.println(" ");
map.replace(11020,"Gaurav","akbar");
map.replace(12763,"Abdul Ali","Shamshuddin khan");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+ m.getValue());
}
System.out.println(" ");
System.out.println("Number of trains running in these route as per present entries:
"+map.size());
}
}

4) Sowmya is the manager of the Indusland Bank and has asked you to develop a program
which takes in the details (account balance, customer name) of 5 customers as dynamic
user input and store them in a Treemap. It should then print the details in alphabetical
order of the accountant’s name. It should also give a feature to the customers where in if
three of them withdraw 1000/- and two of them deposit 1000/- it should then print the
updated balances along with their names. [L.O.1]
Solution:
import java.util.*;
public class TreeMapDemo {

public static void main(String args[]) {


TreeMap tm = new TreeMap();
tm.put("Zara", new Double(3434.34));
tm.put("Mahnaz", new Double(123.22));
tm.put("Ayan", new Double(1378.00));
tm.put("Daisy", new Double(99.22));
tm.put("Qadir", new Double(-19.08));
Set = tm.entrySet();
Iterator i = set.iterator();
while(i.hasNext()) {
double balance ;
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
double balance = ((Double)tm.get("Zara")).doubleValue();
tm.put("Zara", new Double(balance + 1000));
System.out.println("Zara's new balance: " + tm.get("Zara"));
double balance1 = ((Double)tm.get("Mahnaz")).doubleValue();
tm.put("Mahnaz", new Double(balance1 + 1000));
System.out.println("Mahnaz's new balance1: " + tm.get("Mahnaz"));

}
}

5) Nikhil is the class teacher of a section and wants to know the details of the student’s
grades in a subject. Develop a program which will help find out the number of students in
each grade by taking the scores of 15 students in that subject along with their roll number
as dynamic user inputs and store them into a Hashmap. Then it should accordingly sort
the student’s marks based on the grades they received and create a new Hashmap for
each grade. It should then count the number of students in each grade and print their
details individually in accordance to the grades. [L.O.2]

Marks Grade
85-100 O
80-84 A+
65-79 A
50-64 B
<50 F
Solution:
import java.util.*;
public class sort{
public static void main(String args[]){
HashMap<Integer,Integer> m = new HashMap<Integer,Integer>();
HashMap<Integer,Integer> O = new HashMap<Integer,Integer>();
HashMap<Integer,Integer> Ap = new HashMap<Integer,Integer>();
HashMap<Integer,Integer> A=new HashMap<Integer,Integer>();
HashMap<Integer,Integer> F =new HashMap<Integer,Integer>();
for(int i=0;i<4;i++)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int name=sc.nextInt();

m.put(n,name);

}
for (Map.Entry<Integer, Integer> entry : m.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
int i=entry.getValue();
int j=entry.getKey();
if(i>=85)
{
O.put(j,i);
}
else if(i>=80){
Ap.put(j,i);
}
else if(i>=65){
A.put(j,i);
}
else if(i<50){
F.put(j,i);
}

}
int c1,c2,c3,c4;
c1=O.size();
c2=Ap.size();
c3=A.size();
c4=F.size();
System.out.println("O GRADE:"+c1);
System.out.println("A+ GRADE:"+c2);
System.out.println("A GRADE:"+c3);
System.out.println("FAILURES:"+c4);

}
}

6) Andrew is the librarian of your local library and wants to digitalize the process of storing
the details of the books present. Help him out by developing a program which takes in the
names and their ID’s of 10 books as dynamic user inputs and stores them into a Treemap.
It should then allow you to add details of new books and delete previous book’s details if
they’ve been replaced in the library. It should also display the details of all the books
present whenever necessary. Use Singleton Class to develop the program. [L.O.1]
Solution:
import java.util.*;
class Singleton
{
private Singleton()
{

}
TreeMap<Integer,String> t=new TreeMap<Integer,String>();
public static Singleton obj=null;
public static Singleton getInstance()
{
if (obj==null)
obj=new Singleton();
return obj;
}
public void addBook(int id,String name)
{
t.put(id,name);
}
public void display()
{
System.out.println(t);
}
public void Remove(int id)
{
t.remove(id);
}
}
public class Main
{
public static void main(String[] args)
{
Singleton obj=Singleton.getInstance();
Scanner sc=new Scanner(System.in);
System.out.println("Enter no of books");
int n=sc.nextInt();
for(int i=1;i<=n;i++)
{
System.out.println("Enter book id");
int id=sc.nextInt();
System.out.println("Enter book name");
String name=sc.next();
obj.addBook(id,name);
}
while(true)
{
System.out.println("1.Remove book\n2.display\n3.exit");
int x=sc.nextInt();
if(x==1)
{
System.out.println("Enter book id to remove");
int id=sc.nextInt();
obj.Remove(id);
}
else if(x==2)
{
System.out.println("Books present in store");
obj.display();
}
else
{
break;
}
}
}
}

7) Scott is incharge of all the workers in your mansion and wants your help to manage the
everyday tasks of all of them. Develop a program which’ll help him out by taking 6 tasks
along with the time consumed to complete the tasks as dynamic user inputs and store
them in a Treemap. It should then sort them in an ascending order of the time taken for
each task to be completed. [L.O.1]

Solution:
import java.util.*;
class work
{
public static void main(String[] args)
{
Map<Integer,String> map= new TreeMap<Integer,String>();
Scanner sc = new Scanner(System.in);
System.out.println("Enter no of works...");
int n = sc.nextInt();
for (int y=0;y < n;y++)
{
System.out.println("Enter "+(y+1)+"st Work name :");
String b = sc.next();
System.out.println("Enter "+(y+1)+"st Work time :");
int a = sc.nextInt();
map.put(a,b);
}
int c = 1;
for(Map.Entry<Integer, String> entry:map.entrySet())
{
int key=entry.getKey();
String b1=entry.getValue();
System.out.println((c++)+"st Task : ");
System.out.println("Do "+b1+" It takes "+key+" minutes..");
}
}
}

8) You are a software developer and your client require a login page where user gives in
username and password. Create a login page using GUI in java. All the usernames and
passwords must be stored in a HashMap. If the credentials are valid, display the message
“Logged In”. If the credentials are invalid, display “Incorrect Credentials”. [L.O.2]
Solution:
import java.util.*;
class Details{
String username,password;
public Details(String username,String password){
this.username = username;
this.password = password;
}
}
public class Loki{
public static void main(String args[]){
HashMap<Integer,Details> y = new HashMap<Integer,Details>();
Details b1 = new Details("Kamal","LOkk");
Details b2 = new Details("Sdvc","dsfjc");
Details b3 = new Details("Qaom","mdsij");
y.put(1,b1);
y.put(2,b2);
y.put(3,b3);
for(HashMap.Entry<Integer, Details> entry:y.entrySet()){
int key=entry.getKey();
Details b=entry.getValue();
System.out.println(key+" Details:");
System.out.println("Username is = "+b.username+" Password = "+b.password);
}
System.out.println("Enter the User number you want to change");
Scanner l = new Scanner(System.in);
int x;
x = l.nextInt();
String k,j;
System.out.println("Enter the New Username and Password");
j = l.nextLine();
k = l.nextLine();
Details b4 = new Details(j,k);
y.replace(x,b4);
for(HashMap.Entry<Integer, Details> entry:y.entrySet()){
int key=entry.getKey();
Details b=entry.getValue();
System.out.println(key+" Details:");
System.out.println("Username is = "+b.username+" Password = "+b.password);
}
}
}
9) Harika is a clothes merchant and wants to digitalize the process of displaying the various
models to the customers. Develop a menu driven program which takes in the dress name
and the cost of 15 types of clothes present in the shop as dynamic user inputs and stores
them in a Treemap. It should sort the clothes on the basis of their price in ascending order,
descending order, the order in which user gives the input and the reverse order to the
given input. [L.O.1]

Solution:
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner = new Scanner(System.in);
System.out.println("1.ascending order 2, dscending order 3.insertion order 4.reverce to
insertion order");
System.out.println("enter your choice");

int x = scanner.nextInt();
if(x==1)
{
TreeMap<Integer,String> map=new TreeMap<Integer,String>();
map.put(100,"Amit");
map.put(1020,"Ravi");
map.put(1001,"Vijay");
map.put(103,"Rahul");

for(Map.Entry m:map.entrySet())
System.out.println(m.getKey()+" "+m.getValue());
}

else if(x==2)
{
TreeMap<Integer,String> map=new TreeMap<Integer,String>(new
MyComparator4());
map.put(100,"Amit");
map.put(1020,"Ravi");
map.put(1001,"Vijay");
map.put(103,"Rahul");

for(Map.Entry m:map.entrySet())
System.out.println(m.getKey()+" "+m.getValue());
}

else if(x==3)
{
TreeMap<Integer,String> map=new TreeMap<Integer,String>(new
MyComparator1());
map.put(100,"Amit");
map.put(1020,"Ravi");
map.put(1001,"Vijay");
map.put(103,"Rahul");

for(Map.Entry m:map.entrySet())
System.out.println(m.getKey()+" "+m.getValue());
}

else if(x==4)
{
TreeMap<Integer,String> map=new TreeMap<Integer,String>(new
MyComparator2());
map.put(100,"Amit");
map.put(1020,"Ravi");
map.put(1001,"Vijay");
map.put(103,"Rahul");

for(Map.Entry m:map.entrySet())
System.out.println(m.getKey()+" "+m.getValue());
}

else
System.out.println("enter valid choice");
}
}
class MyComparator1 implements Comparator
{
public int compare(Object obj ,Object obj1 )
{
Integer l1 = (Integer) obj;
Integer l2 = (Integer) obj1;
return 1;
}
}

class MyComparator2 implements Comparator


{
public int compare(Object obj ,Object obj1 )
{
Integer l1 = (Integer) obj;
Integer l2 = (Integer) obj1;
return -1;
}
}

class MyComparator3 implements Comparator


{
public int compare(Object obj ,Object obj1 )
{
Integer l1 = (Integer) obj;
Integer l2 = (Integer) obj1;
if(l1<l2)
return +1;
else if(l1>l2)
return -1;
else
return 0;
}
}

class MyComparator4 implements Comparator


{
public int compare(Object obj ,Object obj1 )
{
Integer l1 = (Integer) obj;
Integer l2 = (Integer) obj1;
if(l1<l2)
return -1;
else if(l1>l2)
return +1;
else
return 0;
}
KEY VALUE
Restaurant Rating
KFC 4/5
Domino’s 4.2/5
Starbucks 4.8/5
Creamstone 4.1/5
Subway 4.3/5
Pizza Hut 3.8/5
McDonald’s 4.7/5
Makers of Milkshake 4.4/5
The Thickshake Factory 4.5/5
Dunkin Donuts 4.9/5
}

10) What is the output for the following values when they are inserted into Hashmap and
Treemap? [L.O.1,2]
OOPS LAB-12

1) Shreya was curious to know whether a word is a PALINDROME or not so, she wants you
to develop a program which takes a string as dynamic user input and stores it in a stack.
Then check whether it a palindrome or not. (Use Stacks concept only) [L.O.1]

Solution:

import java.util.*;
public class Lab12_1
{
public static void main(String[] args)
{
Stack <Character> Stack1=new Stack<Character>();
Stack <Character> ref=new Stack<Character>();
Stack <Character> Stack2=new Stack<Character>();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String");
String s=sc.next();
for(int i=0;i<s.length();i++)
{
Stack1.push(s.charAt(i));
ref.push(s.charAt(i));
}
for(int i=0;i<s.length();i++)
{
char a=Stack1.pop();
Stack2.push(a);
}
if( ref.equals(Stack2)==true)
{
System.out.println("Your String is palandrome");
}
else
{
System.out.println("Your String is not a palandrome");
}
}
}

2) You are a teacher in a class and want to print the ranks of 10 students who’ve written an
exam. Develop a program which takes in their name, ID number and marks as dynamic
user inputs. Each student’s details must be stored in a reference of a class and that
reference must be stored in a linked list. Print the ranks of all the students based on their
marks in descending order by only displaying their name and ID number. Use comparable
interface. [L.O.3]

Solution:

import java.io.*;
import java.util.*;
class Linkedlist implements Comparable<Linkedlist>
{
String id,name;
int m1;
Linkedlist(String id,String name,int m1)
{
this.id=id;
this.name=name;
this.m1=m1;
}
public int compareTo(Linkedlist h)
{
if(m1==h.m1)
return 0;
else if(m1>h.m1)
return -1;
else
return 1;
}
}
public class Main
{
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
LinkedList<Linkedlist> h=new LinkedList<Linkedlist>();
while(true)
{
System.out.println("1.add details\n2.display\n3.exit");
int x=sc.nextInt();
if(x==1)
{
System.out.println("Enter student id no");
String id=sc.next();
System.out.println("Enter student name");
String name=sc.next();
System.out.println("Enter student marks");
int m=sc.nextInt();
h.add(new Linkedlist(id,name,m));
}
else if(x==2)
{
Collections.sort(h);
for(Linkedlist st:h)
{
System.out.println(st.id+" "+st.name);
}
}
else
{
break;
}
}
}
}

3) Nina is looking for jobs and asked for your help to apply for a company. Develop a program
which takes in the names of 7 companies and their ratings as dynamic user inputs and
store it in a priority queue. Print the list of companies in descending order in accordance
with the rating. [L.O.2]

Solution:
import java.util.*;
public class Example
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
PriorityQueue<Company> pq = new
PriorityQueue<Company>(10, new CompanyComparator());
Company company1 = new Company("Amazon", 9.4);
pq.add(company1);
Company company2 = new Company("Google", 9.8);
pq.add(company2);
Company company3 = new Company("Microsoft", 9.6);
pq.add(company3);
Company company4 = new Company("Facebook",9.4);
pq.add(company4);
Company company5 = new Company("IBM", 9.1);
pq.add(company5);
Company company6 = new Company("Infosys", 8.2);
pq.add(company6);
Company company7 = new Company("TCS", 8.7);
pq.add(company7);
System.out.println("Companys in sorted form");
while (!pq.isEmpty()) {
System.out.println(pq.poll().getName());
}
}
}
class CompanyComparator implements Comparator<Company>
{
public int compare(Company s1, Company s2)
{
if (s1.rating < s2.rating)
return 1;
else if (s1.rating > s2.rating)
return -1;
return 0;
}
}

class Company {
public String name;
public double rating;
public Company(String name, double rating)
{
this.name = name;
this.rating = rating;
}
public String getName()
{
return name;
}
}
4) You are a game developer and are developing a level for an FPS game. Your gun in the
game has a magazine capacity of 10 bullets whose types you need to take in by dynamic
user input. Display the order in which the bullets will be fired. [L.O.1]

Solution:
import java.util.*;
class Stacktest
{
public static void main(String[] args)
{
Stack<String> stack = new Stack<String>();
Scanner sc = new Scanner(System.in);
System.out.println("Load the ammo for gun.");
for(int i =0 ; i < 10 ; i++)
{
String s = sc.nextLine();
stack.push(s);
}
for(int y =0 ; y < 10 ; y++)
{
System.out.println(stack.peek()+" is loaded.."+"\n\n press enter to fire..");
String f = sc.nextLine();
System.out.println("\t\t-----FIRED-----");
}
}
}

5) You are working on a thesis about the various Operating System’s invented till now and
want to develop a program which takes the name, founder and year of invention as the
dynamic user inputs. Each operating System’s details must be stored in a reference of a
class and that reference must be stored in a queue. Print the list of various Operating
System’s based on their year of founding in descending order by only displaying name and
founder. Use Comparable interface. [L.O.2]

Solution:

import java.io.*;
import java.util.*;
class Operatingsystem implements Comparable<Operatingsystem>
{
String name,founder;
int year;
Operatingsystem(String name,String founder,int year)
{
this.name=name;
this.founder=founder;
this.year=year;
}
public int compareTo(Operatingsystem h)
{
if(year==h.year)
return 0;
else if(year>h.year)
return -1;
else
return 1;
}
}
public class Main
{
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
PriorityQueue<Operatingsystem> queue=new PriorityQueue<Operatingsystem>();
System.out.println("Enter no of operating Systems");
int n=sc.nextInt();

for(int i=0;i<n;i++)
{
System.out.println("Enter Operatingsystem name");
String name=sc.next();
System.out.println("Enter Operatingsystem founder");
String founder=sc.next();
System.out.println("Enter published year of Operatingsystem");
int year=sc.nextInt();
queue.add(new Operatingsystem(name,founder,year));
}
for(Operatingsystem b:queue){
System.out.println(b.name+" "+b.founder+" "+b.year);
}

}
}

6) Your company has developed a game and you are overseeing a contest being conducted
on it. As part of the contest, you need to develop a program which takes in the name
and the score of each gamer as dynamic user inputs and store them in a priority queue.
Print the rankings of the gamers by the end of the tournament in descending order in
accordance with their scores. Also print the winner. [L.O.2]
Solution:

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main
{
Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
PriorityQueue<Game> pq = new
PriorityQueue<Game>(5, new StudentComparator());
Game student1 = new Game("Nandini", 3.2);
pq.add(student1);
Game student2 = new Game("Anmol", 3.6);
pq.add(student2);
Game student3 = new Game("Palak", 4.0);
pq.add(student3);
System.out.println("Students served in their priority order");
System.out.println(pq.peek() + " is the winner");
while (!pq.isEmpty())
{
System.out.println(pq.poll().getName() );
}
}
}
class StudentComparator implements Comparator<Game>
{
public int compare(Game s1, Game s2)
{
if (s1.score < s2.score)
return 1;
else if (s1.score > s2.score)
return -1;
return 0;
}
}
class Game
{
public String name;
public double score;
public Game(String name, double score)
{
this.name = name;
this.score = score;
}
public String getName()
{
return name;
}
}
7) Smitha has gone on a holiday to Kashmir and was going through Jawaharlal Nehru
Tunnel (India’s Longest Tunnel) and gets struck in it due to an accident to a car in the
middle of the tunnel. She has been informed that all the cars must back away and exit
the tunnel without proceeding further. Develop a program to help the authorities find
out the flow with which the cars exit the tunnel. [L.O.1,3]
Solution:

import java.util.*;
class Crowd
{
public static void main(String args[])
{
Stack<String> c = new Stack<String>();
c.push("OLA");
c.push("OL");
c.push("OA");
c.push("LA");
c.push("OLAf");
c.push("OLAxz");
c.push("OLsadA");
System.out.println("Your car is at "+(c.size()-c.search("OLA")+1)+" place");
String x,z;
z="OLA";
x=c.pop();
int i=0;
while(x != z)
{
x = c.pop();
i=i+1;
}
System.out.println("The amount that must be paid is Rs "+(i*10)+"/-");
}
}

OOPS LAB-13

1) You have been given an assignment to take in 10 integers as dynamic user inputs and
count the number of positive and negative integers present. Also, calculate the total
and average of all the given numbers by using all the three loops (For, while, do-
while).
Solution:
import java.util.*;
class Demo

public static void main(String args[])

int n,positive=0,negative=0,total=0;

float avg=0;

Scanner sc=new Scanner(System.in);

System.out.println("Enter no.of Integers to read:");

n=sc.nextInt();

System.out.println("Enter the Integers(positive/negative)");

for(int i=0;i<n;i++) //Using FOR loop

int number;

number=sc.nextInt();

if(number>0)

positive++;

if(number<0)

negative++;

total+=number;

/*

int i=1;

while(i<=n) //Using WHILE loop

int number;

number=sc.nextInt();

if(number>0)

positive++;
}

if(number<0)

negative++;

total+=number;

int i=1;

do //Using DO-WHILE loop

int number;

number=sc.nextInt();

if(number>0)

positive++;

if(number<0)

negative++;

total+=number;

while(i<=n);

*/

avg=total/n;

System.out.println("Average of given numbers is: "+avg);

2) Ashley was given a task in class to take in 5 numbers as dynamic user inputs and
check which of the numbers are Harshad/Niven number and count the number of
Harshad numbers present. (Harshad number is a number that is divisible by the sum
of its digits)
Solution:
import java.util.*;
class Harshard
{
public static void main(String args[])
{
Scanner obj = new Scanner(System.in);
int count=0;
for(int i=0;i<5;i++)
{
System.out.println("Enter a number :");
int n=obj.nextInt();
int c=n;
int sum=0;
while(n!=0)
{
int r=n%10;
sum=sum+r;
n=n/10;
}
if(c%sum==0)
count+=1;
}
System.out.println("Number of Harshard Numbers are : "+count);
}
}

3) NASA wants to measure the distance between Earth and Sun in light years which is
taken as dynamic user input and can’t be stored in primitive data types. Develop a
program which’ll find the sum of the digits of the numbers.
Solution:
import java.util.*;

class Long

public static void main(String args[])

Scanner obj=new Scanner(System.in);

char c;

int sum=0,n;

System.out.print("Enter the long number :");

String s=obj.nextLine();

int l=s.length();

for(int i=0;i<l;i++)

c=s.charAt(i);
n=(int)c-48;

sum=sum+n;

System.out.println("The sum of digits : "+sum);

4) You have been approached by a client who owns a hospital to develop a program
which creates an outer class Hospital having data fields hospitalName, hospitalAddr,
and gethospitalName() method and an inner class Doctor having data field docName,
and setdocAddr(), getdocAddr() methods and access outer class members with inner
class by ’this’ keyword. create Demo class to complete the rest of the program.
Solution:
import java.lang.*;

import java.util.*;

class Hospital
{
String hospitalName,hospitalAddr;
void setHospitalName(String hospitalName)
{
this.hospitalName=hospitalName;
}
String getHospitalName()
{
return hospitalName;
}
void setHospitalAddr(String hospitalAddr)
{
this.hospitalAddr=hospitalAddr;
}
String getHospitalAddr()
{
return hospitalAddr;
}
class Doctor
{
String docName,docAddr;
public void setDocName(String docName)
{
this.docName=docName;
}
public void setDocAddr(String docAddr)
{
this.docAddr=docAddr;
}
public String getDocName()
{
return docName;
}
public String getDocAddr()
{
return docAddr;
}
public void getHospitalDetails()
{
System.out.println(Hospital.this.getHospitalName());
System.out.println(Hospital.this.getHospitalAddr());
}
}
}

class Demo
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String hn,ha,dn,da;
System.out.println("Enter hospital name ");
hn=sc.nextLine();
System.out.println("Enter hospital address ");
ha=sc.nextLine();
System.out.println("Enter doctor name ");
dn=sc.nextLine();
System.out.println("Enter doctor address ");
da=sc.nextLine();
Hospital h=new Hospital();
h.setHospitalName(hn);
h.setHospitalAddr(ha);
Hospital.Doctor d=h.new Doctor();
d.setDocName(dn);
d.setDocAddr(da);
d.getHospitalDetails();
System.out.println(d.getDocName());
System.out.println(d.getDocAddr());
}
}

5) You have been given a task to develop a program which has outer class OUTER and
Inner private class INNER which is used to display your name. Outer class contains a
method which is used to verify the PASSWORD entered by the user and if the
entered PASSWORD is correct, then call the inner class method to display your
name. Write a Demo class and make necessary calls to access OUTER and INNER
classes.

Solution:
import java.lang.*;
import java.util.*;
class Outer
{
void check(String password,String name)
{
String check="KLEF";
if(password.equals(check))
{
Inner a=new Inner();
a.display(name);
}
else
System.out.println("Wrong Password....Re-enter password");
}
private class Inner
{
public void display(String name)
{
System.out.println("My name is "+name);
}
}
}

class Demo
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String name,password;
System.out.println("Enter your name");
name=sc.nextLine();
System.out.println("Enter the password");
password=sc.nextLine();
Outer out=new Outer();
//Outer.Inner in=out.new Inner();
//in.display(name);
out.check(password,name);
}
}

6) Your younger brother, Ankit was given a problem in his class to take in a string and a
floating point number as dynamic user inputs. He comes up to you for help so
develop a program and print the floating point number up to two decimals and
upper case of the string in a single line using a single printf(), convert the floating
number to a string and print it using println(), now concat the both strings and print
it using print().
Solution:
import java.util.*;

class Demo

public static void main(String args[])

float f;

String s;

Scanner sc=new Scanner(System.in);

System.out.println("Enter a floating number:");

f=sc.nextFloat();

System.out.println("Enter a String:");

s=sc.next()+sc.nextLine();

System.out.print("Floating number with precision two and upper case of string is: ");

System.out.printf("%.2f %S\n",f,s);

System.out.print("Floating number converted to String as: ");

String str=Float.toString(f);

System.out.println(str);

System.out.print("Strings Concated as: ");

str=s+str;

System.out.print(str);

}
OOPS LAB-14

1. You have a screening test for the Interview of a Software Company. As a part of it, you
are asked to develop a program using the concept of Abstract class and methods. Your
program should perform the task of taking your interest for allowing or denying your
apps ( such as Instagram or Facebook ) to access your contacts, media, messages, etc.

Solution:
import java.util.Scanner;
abstract class Phone
{
abstract void contacts ();
abstract void messages ();
abstract void photos ();
}
class Instagram extends Phone
{
Scanner sc = new Scanner (System.in);
void contacts ()
{
System.out.println ("Do you want this app to read your contacts 'ALLOW'/'NO'");
String ans = sc.nextLine ();
if (ans.equals ("ALLOW"))
{
System.out.println ("Establishing connection with your gallery");
}
Else
{
System.out.println ("Access Denied");
}
}
}
class Print
{
public static void main (String args[])
{
Phone p = new Instagram ();
p.contacts ();
p.messages ():
p.photos ():
Phone pr = new Facebook ();
pr.contacts ();
pr.messages ();
pr.photos ();
}
}
abstract class Phone
{
abstract void contacts ();
abstract void messages ();
abstract void photos ();
}
class Instagram extends Phone
{
Scanner sc = new Scanner (System.in);
void contacts ()
{
System.out.println ("Do you want this app to read your contacts 'ALLOW'/'NO'");
String ans = sc.nextLine ();
if (ans.equals ("ALLOW"))
{
System.out.println ("Establishing connection with your contacts");
}

Else
{
System.out.println ("Access Denied");
}
}
void messages ()
{
System.out.println ("Do you want this app to read your messages 'ALLOW'/'NO'");
String ans = sc.nextLine ();
if (ans.equals ("ALLOW"))
{

System.out.println ("Establishing connection with your contacts");

Else
{
System.out.println ("Access Denied");
}
}
void photos ()
{
System.out.println ("Do you want this app to access your Photos 'ALLOW'/'NO'");
String ans = sc.nextLine ();
if (ans.equals ("ALLOW"))
{
System.out.println ("Establishing connection with your gallery");
}
Else
{
System.out.println ("Access Denied");
}
}
}
class Facebook extends Phone
{
Scanner sc = new Scanner (System.in);
void contacts ()
{
System.out.println ("Do you want this app to read your contacts 'ALLOW'/'NO'");
String ans = sc.nextLine ();
if (ans.equals ("ALLOW"))
{
System.out.println ("Establishing connection with your contacts"):
}
Else
{
System.out.println ("Access Denied");
}
}
void messages ()
{
System.out.println ("Do you want this app to read your messages 'ALLOW'/'NO'");
String ans = sc.nextLine ();
if (ans.equals ("ALLOW"))
{
System.out.println ("Establishing connection with your contacts");
}
Else
{
System.out.println ("Access Denied"):
}
}
void photos ()
{
System.out.println ("Do you want this app to access your Photos 'ALLOW'/'NO'");
String ans = sc.nextLine ();
if (ans.equals ("ALLOW"))
{
System.out.println("Establishing connection with your gallery");
}
Else
{
System.out.println("Access Denied");
}
}
}
class Print
{
public static void main(String args[])
{
Phone p=new Instagram();
p.contacts();
p.messages():
p.photos():
Phone pr=new Facebook();
pr.contacts();
pr.messages();
pr.photos();
}
}

2. You are participating in a Quiz, and you need to solve the following snippet and
Guess the correct Output.

class A
{
int methodOfA(int i)
{
i /= 10;
return i;
}
}

class B extends A
{
int methodOfB(int i)
{
i *= 20;
return methodOfA(i);
}
}

public class MainClass


{
public static void main(String[] args)
{
B b = new B();
System.out.println(b.methodOfB(100));
}
}

Solution:

Output: 200

3. Ran veer works for Indian Navy. He found the newly recruited and transferred
officers had a problem in finding their work hours. So let us help Ran veer to solve
this problem faced by officers of Indian Navy by implementing a java program that
uses the concept of inheritance, which takes in the input of your designation and
displays the number of hours.

Solution:

import java.io.*;

import java.util.*;

class Crew

int hour;

String pos;

String des;

String post;

void workhour(int hour)

this.hour=hour;

System.out.println("Hello crew!! , work Hours for you is: "+hour);

}
class Captian extends Crew

void position(String pos)

this.pos=pos;

System.out.println("Hello "+pos+" Welcome to INS VIKRANT captian");

class Commander extends Crew

void position(String des)

this.des=des;

System.out.println("Hello : "+pos+" Welcome to INS VIKRANT Commander");

class Worker extends Crew

void position(String post)

this.post=post;

System.out.println("Hello : "+post+ " Welcome to INS VIKRANT");

public class Army

public static void main(String args[])

Scanner in=new Scanner(System.in);

Captian c=new Captian();

System.out.println("PLEASE ENTER YOUR POSITION IN THE INS VIKARANT");

String s=in.next();

if(s.equalsIgnoreCase("Captian"))
{

c.workhour(8);

c.position(s);

if(s.equalsIgnoreCase("Commander"))

c.workhour(10);

c.position(s);

if(s.equalsIgnoreCase("Worker"))

c.workhour(12);

c.position(s);

4. The Vallabhapuram mandal conducts running competition every year as a part of


village fair. The village chief is fond of the number ‘5’, and so he wished to give prizes
to the participants who got first and fifth place. He asks his son to write a program
such that it displays the names of the people who came at 1st and 5th positions.
Now chief is invited to judge a race in his neighboring village but there are only ‘four’
participants in the race. Now help the chief to display only first place person’s name
by correcting the program with exception handling while also displaying the
exception.
Hint: Array Index out of Bond.

Solution:

import java.util.*;

class five

{
public static void main(String args[])

try

Scanner s=new Scanner(System.in);

System.out.println("Enter No of racers");

int x;

x=s.nextInt();

ArrayList<String> arr=new ArrayList<String>(x+1);

System.out.println("Enter name of "+x+" racers as per their position”);

s.nextLine();

for(int i=1;i<=x;i++)

System.out.println("Enter name of "+i+" racer");

String a=s.nextLine();

arr.add(a);

System.out.println("First Place is "+arr.get(0));

System.out.println("Cheif's Favorite Racer is "+arr.get(4));

catch(Exception e)
{

System.out.println("Sorry cheif there is no racer in fifth position(throws Exception "+e+")");

}
5. You have been asked by your faculty to develop a program which contains two
classes generateInteger and generateDouble and these both classes implements a
method generator in the interface Generator. Make sure the method generator
prints three random integers in generateInteger class and three random double
values in class generateDouble.

Solution:

import java.util.*;

interface Generator{

void generator();

class GenerateInteger implements Generator{

Random rand=new Random();

public void generator(){

int randomInteger,i;

for(i=0;i<3;i++){

randomInteger=rand.nextInt(10000);

System.out.println("The random integer generated is: "+randomInteger);

class GenerateDouble implements Generator{

Random rand=new Random();

public void generator(){

double randomDouble,i;

for(i=0;i<3;i++){

randomDouble=rand.nextDouble();

System.out.println("The random double generated is: "+randomDouble);

}
}

class Main{

public static void main(String[] args){

Generator integerGenerator=new GenerateInteger();

integerGenerator.generator();

Generator doubleGenerator=new GenerateDouble();

doubleGenerator.generator();

6. Your mathematics faculty has asked for your help in order to convey a statement to
certain set of students. Develop a program which helps him to convey the line ‘Area
and perimeter can be implemented for 2D figures and Area and Volume can be
implemented for 3D figures’.
Hint- Use Area volume and perimeter as three different interfaces and classes 2D
and 3D to implement those interfaces.

Solution:

import java.util.*;

interface Area{

void getArea();

interface Perimeter{

void getPerimeter();
}

interface Volume{

void getVolume();

class Rectangle implements Area, Perimeter{

public void getArea(){

System.out.println("The Area of Rectangle is Length*Breadth");

public void getPerimeter(){

System.out.println("The perimeter of Rectangle is 2*(Length + Breadth)");

class Cubiod implements Area, Volume{

public void getArea(){

System.out.println("The Area of Cuboid is 2*(Length*Width + Length*Height + Height*Width)");

public void getVolume(){

System.out.println("The Volume of the cuboid is Length*Width*Height");

class Main{

public static void main(String[] args){

Rectangle r=new Rectangle();

r.getArea();

r.getPerimeter();

}
}

7. Chinnu’s mother asked him to go to the shop and get some groceries and he wanted
to store all the list of groceries to get a clarity on bill. He ate an Ice cream on the way
and spent some money. After he got the groceries into the basket ,he found that he
dosen’t have enough amount to get all the items so he removed a few items in the
list considering the available amount. Now display the both lists, before and after
removing the items by using vector method and create the second list by using
cloning method?

Solution:

import java.util.*;

public class Main

public static void main(String args[])

{
Vector Vec= new Vector();

Vector vec2=new Vector();


Vec.add("Rice");

Vec.add("chicken");

Vec.add("strawberries");

Vec.add("grains");

Vec.add("wheat");

System.out.println("Vector: " + Vec);

vec2=(Vector)Vec.clone();

vec2.remove(0);

System.out.println(" the cloned Vector: "+ vec2 );


}

8. The Owner of a Supermarket asks the Employe to maintain a detailed record


consisting Name, Id and Cost of the item available in their supermarket. He also asks
him to get the information of those items in ascending order of the costs. He asks
your help for writing a program which takes in the details through the Scanner class
and add them to the array list. Your program should also display the details of the
items compared in ascending order of the item cost. (Use list and Comparable
interface)

Solution:

import java.util.*;

import java.lang.*;

import java.io.*;

class item

int cost;

String name, id;

public employee(int cost, String name,

String id)

this.cost =cost;

this.name = name;

this.id =id;

public String toString()

return this.cost + " " + this.name +

" " + this.id;

class Sortbysal implements Comparator<item>

public int compare(item a,item b)


{

return a.cost - b.cost;

class comparable

public static void main (String[] args)

ArrayList<employee> ar = new ArrayList<employee>();

for(int i=0;i<2;i++){

Scanner sc = new Scanner(System.in);

int s=sc.nextInt();

String n =sc.nextLine();

String a =sc.nextLine();

ar.add(new item(s,n,a));

Collections.sort(ar, new Sortbycost());

for (int i=0; i<ar.size(); i++)

System.out.println(ar.get(i));

OOPS LAB-15
1. Sahithi was asked to find descending order of the given set of numbers as her
Assignment. Help her out by developing a program which takes in 10 numbers as a
dynamic user input and store them in a Hash set. Then it should sort the numbers
and print them in descending order.
Solution:
import java.util.*;
public class Hs2 {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter no.of values to take:");
int n=sc.nextInt();
HashSet<Integer> hs = new HashSet<Integer>();
for(int i=0;i<n;i++)
{
System.out.println("Enter the number:");
int s=sc.nextInt();
hs.add(s);
}
System.out.println("Original HashSet: "+ hs);
TreeSet<Integer> ts = new TreeSet<Integer>(hs);
TreeSet<Integer> tsRs = (TreeSet<Integer>)ts.descendingSet();
System.out.println("descending order of numbers: " + tsRs)
}
}

2. Priya wants you to develop a program which takes in words from a dictionary as
dynamic user input and stores them in a Hashset. It should then print them in
lexicographical order after converting Hashset into Treeset.
Solution:
import java.util.*;
public class Hs2 {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter no.of values to take:");
int n=sc.nextInt();
HashSet<Integer> hs = new HashSet<Integer>();
for(int i=0;i<n;i++)
{
System.out.println("Enter the number:");
int s=sc.nextInt();
hs.add(s);
}
System.out.println("Original HashSet: "+ hs);
TreeSet<Integer> ts = new TreeSet<Integer>(hs);
System.out.println("Lowest value : " + ts.first());
System.out.println("Highest value : " + ts.last());
}
}

3. Elsa was asked to develop a program which takes in five numbers as dynamic user
input and stores them in an Hashset. He passes the Hashset to two threads. First one
should traverse the set, and the Even numbers present in it should be printed and
the second thread should print the Odd numbers present in the set. Help him out by
writing the program using Runnable Interface.
Solution:
import java.util.*;
class Even implements Runnable
{
String name;
Thread t;
HashSet<Integer> hs=new HashSet<Integer>();
Even(String threadname,HashSet<Integer>hs)
{

name = threadname;
this.hs=hs;
t = new Thread(this, name);
System.out.println("thread one: " + t);
t.start();
}
public void run()
{
try
{
for(int i : hs) {
int x = i;
if(x%2==0)
{
System.out.println(x+" is a Even Number");
}
}
Thread.sleep(3000);
} catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}

class Odd implements Runnable {


String name;
Thread t;
HashSet<Integer> hs= new HashSet<Integer>();
Odd(String threadname,HashSet<Integer>hs)
{
this.hs=hs;
name = threadname;
t = new Thread(this, name);
System.out.println("thread two: " + t);
t.start();
}
public void run()
{
try {
for (int i :hs) {
int x = i;
if(x%2!=0)
{
System.out.println(x+" is a Odd Number");
}
}
Thread.sleep(2000);
}
catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class Multi{
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter no.of values to take:");
int n=sc.nextInt();
HashSet<Integer> hs = new HashSet<Integer>();
for(int i=0;i<n;i++)
{
System.out.println("Enter the number:");
int s=sc.nextInt();
hs.add(s);
}
new Even("Thread-1",hs);
new Odd("Thread-2",hs);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

4. Sowmya was asked to develop a program which takes a no. of Login Credentials as a
dynamic user input and stores them in a HashMap. The User who wants to Login
should provide the credentials in the GUI Login form. If the credentials provided
matches with one of the credentials in the HashMap, then the User Successfully
logins. If the User logins Successfully, then the background colour changes to red
colour.
Solution:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;

class Login
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
HashMap<String,String>map=new HashMap<>();
int n,i;
System.out.println("Number of entries ");
n=sc.nextInt();
String uname,pwd;
System.out.println("Enter username and password");
for(i=0;i<n;i++)
{
uname=sc.next()+sc.nextLine();
pwd=sc.nextLine();
map.put(uname,pwd);
}
JFrame f=new JFrame("Creativity");
f.setLayout(new GridBagLayout());
f.setVisible(true);
f.setSize(400,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p=new JPanel();
JLabel l1=new JLabel("Username");
JLabel l2=new JLabel("Password");
TextField t1=new TextField(20);
TextField t2=new TextField(20);
//TextField t3=new TextField(20);
//TextField t4=new TextField(20);
JButton b=new JButton("SUBMIT");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String uname1=t1.getText();
String pwd1=t2.getText();
if(map.containsKey(uname1))
{
String ch=map.get(uname1);
if(ch.equals(pwd1))
p.setBackground(Color.RED);
}
}
});
p.add(l1);
p.add(t1);
p.add(l2);
p.add(t2);
p.add(b);
//p.add(t3);
//p.add(t4);
f.add(p);
}
}

5. Mihir was asked to develop a game based on stacks. There will be two players in the
game. Every player will get a turn to enter a number and that number will be pushed
into a stack if the given number is divided by a number which is randomly generated
by the game otherwise the top element of the stack will be popped out. The player
whose is left with no numbers in the stack is the loser. Print the Winner of the game.
Solution:
import java.util.*;
import java.lang.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
Stack<Integer> s=new Stack<Integer>();
int x=1;
Random rand = new Random();
while(true)
{
int i= rand.nextInt(4);
if(i==0)
{
i++;
}
System.out.println(i);
if(x==1)
{
System.out.println("Alice trun....");
int n=sc.nextInt();
x=2;
if(n%i==0)
{
s.push(n);
}
else
{
s.pop();
if(s.isEmpty())
{
System.out.println("Bob won the game");
System.exit(0);
}
}
}
else
{
System.out.println("Bob trun....");
int n=sc.nextInt();
x=1;
if(n%i==0)
{
s.push(n);
}
else
{
s.pop();
if(s.isEmpty())
{
System.out.println("Alice won the game");
System.exit(0);
}
}
}

}
}
}

6. Riya wants to develop a Movie Booking site. This site should have the options of
Ticket Booking and Cancellation. Before booking, the user should provide the details
like name, email id and phone number. A booking Id will be generated automatically
for the user to book tickets. If the no. of Tickets requested by the user are available,
then the user will be placed on Confirmation queue, else the user will be placed on
Waiting queue. If any user cancels his booking based on booking the cancelled user
details will be printed and the users in the waiting queue will be moved to
Confirmation queue based on the requirement of tickets. Help him out writing the
program.
Solution:
import java.io.*;
import java.util.*;
class Details{
String Name,Phonenumber,MailId;
int BookingId;
Details(int BookingId,String Name,String Phonenumber,String MailId)
{
this.BookingId=BookingId;
this.Name=Name;
this.Phonenumber=Phonenumber;
this.MailId=MailId;
}

}
public class Main
{
public static void main(String[] args) {
PriorityQueue<Details> q=new PriorityQueue<Details>();
PriorityQueue<Details> w=new PriorityQueue<Details>();
Scanner sc=new Scanner(System.in);
int id=1;
int count=0;
while(true)
{
System.out.println("1.Book Ticket\n2.Cancel\n3.exit");
int x=sc.nextInt();
if(x==1)
{
System.out.println("Enter your name: ");
String name=sc.next();
System.out.println("Enter Phonenumber:");
String Phonenumber=sc.next();
System.out.println("Enter MailId: ");
String MailId=sc.next();
count++;
if(count<=5)
{
q.add(new Details(id,name,Phonenumber,MailId));
System.out.println("Your ticket is conformed BookingId "+id);
id++;
}
else
{
w.add(new Details(id,name,Phonenumber,MailId));
System.out.println("Your ticket is in waiting");
}
}
else if(x==2)
{
System.out.println("Enter your BookingId :");
int id1=sc.nextInt();
for(Details b:q){
if(id1==b.BookingId)
{
q.remove(b);
System.out.println(" cancilation succesfully name :"+b.Name+" Phonenumber:
"+b.Phonenumber);
}
if(w.isEmpty()!=true)
{
q.add(w.peek());
w.remove();
}
}
}
else
{
break;
}
}
}
}

7. Rohit was a seasoned traveller. He liked to visit new places. More than all he was a
meticulous planner. This time he was planning to visit Europe. He wrote down his
travel itinerary like as follows: If he wanted to visit Madrid, Paris, Munich, Warsaw
and Kiev in this order, he would write it down like as:

Madrid Paris 100 Paris Munich 200


Munich Warsaw 150 Warsaw Kiev 120
More formally, if he wanted to go from A to B directly and the price is C dollars, then
he would write (A B C$) on a card. Each move was written on a different card. Rohit
was a great planner, so he would never visit the same place twice. Just before
starting his journey, the cards got shuffled. Help Rohit figure out the actual order of
the cards and the total cost of his journey using HashMap concept.

Solution:
import java.util.HashMap;

import java.util.Map;

import java.util.Scanner;

class first {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int t = sc.nextInt();

int i, j;
String a[], b[], start = &quot;&quot;;

for (i = 0; i &lt; t; i++) {

int n = sc.nextInt();

HashMap &lt; String, String &gt; h1 = new HashMap &lt; String, String &gt; ();

HashMap &lt; String, String &gt; h2 = new HashMap &lt; String, String &gt; ();

HashMap &lt; String, String &gt; h3 = new HashMap &lt; String, String &gt; ();

String s[] = new String[n - 1];

// a=new String[n-1];

// b=new String [n-1];

int x;

String w = &quot;&quot;;

int cost = 0;

for (j = 0; j &lt; n - 1; j++) {

s[j] = sc.next();

String s2 = sc.next();

h1.put(s2, s[j]);

w = sc.next();

x = Integer.parseInt(w.substring(0, w.length() - 1));

cost = cost + x;

h2.put(s2, w);

h3.put(s[j], s2);

for (j = 0; j &lt; n - 1; j++) {

if (h1.containsKey(s[j])) {

continue;

} else start = s[j];

StringBuilder sb = new StringBuilder();

//sb.append(start);

for (j = 0; j &lt; n - 1; j++) {

sb=sb.append(start).append(&quot;&quot;).append(h3.get(start)).append(&quot;&quot;)

.append(h2.get(h3.getstart))).append(&quot;\n&quot;);
start = h3.get(start);

System.out.print(sb);

System.out.println(cost + &quot;$&quot;);

8. Sravs wants to develop an app which sorts the Train Ids based on destination time.
The User provides the destination times of different trains along with Train Ids and
stores them in a HahMap. Help him out writing the program to develop the app.
Solution:
import java.util.*;
public class Main
{
public static void main(String[] args) {
//byValue sort1 = new byValue();
Map<Double,String> t=new HashMap<Double,String>();
Scanner sc=new Scanner(System.in);
System.out.println("Enter no of trains");
String id;
double time;
int n=sc.nextInt();
for(int i=0;i<n;i++)
{
System.out.println("Enter train id");
id=sc.next();
System.out.println("Enter time required to reach destination ");
time=sc.nextDouble();
t.put(time,id);
}
System.out.println("trains in ascending order of time required to reach destination:");
for (String key : t.values()) {
System.out.println(key);
}
}
}

You might also like