Oops Solutions Lab PDF
Oops Solutions Lab PDF
Oops Solutions Lab PDF
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
int f=1;
if(num==0)
return 1;
else
return num*fact(num-1);
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);
b)
import java.util.*;
double area=a*a;
return area;
double area=a*b;
return area;
double s=(a+b+c)/2;
double area=Math.sqrt(s*(s-a)*(s-b)*(s-c));
return area;
{
double area,n1=5,n2=3,n3=3;
area=Calc_area(n1);
area=Calc_area(n1,n2);
area=Calc_area(n1,n2,n3);
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;
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
int count=5;
double init_bact=32.8;
while(count>=0)
{
init_bact-=(0.0028*init_bact);
count--;
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
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;
(eng_g*eng_c) +(ts_g*ts_c)+(ds_g*ds_c))/19.5;
Solution :
class Deposit
current +=amount;
return current;
class Withdrawal
{
if(amount>current)
System.out.println("Insufficient balance");
else
current-=amount;
return current;
class Bank
float current=20000;
current=d.deposit(current,20000);
current=wd.withdrawal(current,1000);
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
String empName="rahul";
empObj.displayDetail();
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
int rx=3,ry=2;
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));
if(s<max)
max=s;
ind=i;
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
winner(a,b);
int pavan=0,praveen=0;
for(int i=0;i<10;i++)
pavan++;
pavan++;
pavan++;
praveen++;
praveen++;
praveen++;
else if(a[i]==b[i])
continue;
}
if(pavan>praveen)
else if(praveen>pavan)
else(praveen==pavan)
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;
obj.x=10;
obj.y=20;
System.out.println("Before swapping");
obj.swap(obj);
System.out.println("After swapping");
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;
a.total=500;
safari(a);
lunch(a);
movie(a);
a.total=a.total-30;
a.total=a.total-40;
}
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;
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()
Lottery(int tv)
token_value1=tv;
token_value2=0;
token_value1=tv1;
token_value2=tv2;
int check()
{
int flag=0;
int check=rand.nextInt(6);
flag=1;
Else
flag=0;
if(flag==1)
return 1;
Else
return 0;
int choice=sc.nextInt();
Lottery b;
Lottery c;
int result=-1;
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:
int result=b.check();*/
if(result == 1)
else
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
if(acc==null)
acc=new Atm();
return acc;
if(Balance==0)
System.out.println("Insufficient Balance");
else if(Balance-m<0)
System.out.println("Insufficient Balance");
else
Balance=Balance-m;
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 Singleton()
if(obj==null)
obj=new Singleton();
return obj;
this.counter-=1;
obj.remaining();
class Main
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
this.name=name;
return name;
this.age=age;
return age;
this.location=location;
return location;
this.id=id;
}
return id;
class Type
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());
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
Employee()
empId=0;
empName="#";
empDept="#";
this.empId=empId;
this.empName=empName;
this.empDept=empDept;
Employee e;
int n,id;
String name,dept;
n=s.nextInt();
id=s.nextInt();
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);
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
this.total=total;
this.male=male;
}
this.female=female;
return total;
return male;
return female;
int t,m,f;
t=s.nextInt();
c.setTotal(t);
m=s.nextInt();
c.setMale(m);
f=s.nextInt();
c.setFemale(f);
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;
this.Name=Name;
this.age=age;
this.Country=Country;
class 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("Name : "+PlayerDetails.Name);
System.out.println("Age : "+PlayerDetails.age);
System.out.println("Country : "+PlayerDetails.Country);
class FootballPlayer
player PlayerDetails;
int Goals;
int Matches;
this.Goals=Goals;
this.Matches=Matches;
this.PlayerDetails=PlayerDetails;
void display()
System.out.println("Age : "+PlayerDetails.age);
System.out.println("Country : "+PlayerDetails.Country);
class Display
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");
}
}
}
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()
creditBill credit_Bill;
double individualBill;
this.credit_Bill=credit_Bill;
this.individualBill=individua lBill;
creditBill credit_Bill;
double individualBill;
return (individualBill/
credit_Bill.totalBill())*100;
return (individualBill/
credit_Bill.totalBill())*100;
creditBill credit_Bill;
credit_Bill=r;
credit_Bill=s; System.out.println("Srikanth
Kalyan k=new
Kalyan();
credit_Bill=k;
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.*;
System.out.println(Village.food());
System.out.println(Village.avgincome());
System.out.println(Village.water());
package out;
return income/population;
return tonsoffood/population;
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 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{
super(7,8 0);
System.out.println("After Father's ill condition his son took his place to develop his fathers
company");
class Company{
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
class gen1 {
gen1( )
System.out.println("ca ll");
}
}
gen2( )
System.out.println("messa ge");
gen3( )
System.out.println("camer a");
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
double billafteroffer;
billafteroffer = bill-(0.3*bill);
double billafteroffer;
double billafteroffer;
billafteroffer = bill-(0.20*bill);
class Personbill
System.out.println("Apply coupon");
Scanner sc = new Scanner(System.in);
if(coupon.equals("RAMZA N"))
totalbill.offer(Bill);
if(coupon.equals("CHRISTMAS"))
CHRISTMAS();
totalbill.offer(Bill);
if(coupon.equals("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.*;
rankRequired ();
fee();
if(hostal)
Hostal();
@Override
@Override
@Override
@Override
System.out.println("1.Male\n2.Female");
int x=sc.nextInt();
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);
}
}
Solution:
import java.util.Scanner;
{
public static void main(String[] args)
int i;
for(i=0;i<2;i++)
int yes ;
int x = scanner.nextInt();
try
int f = (x%10);
int g = ((x%100)/10);
int d = (x/100);
catch(Exception e)
System.out.println(e);
} scanner.close();
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:
int age=2;
try {
if(age<18){
int b=1/0;
catch (ArithmeticException e) {
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;
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
String name=sc.next();
int runs=sc.nextInt();
float avg=sc.nextFloat();
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:
String Name;
int nameLength;
int specialSetCount=0,i;
StringBuilder sb;
this.Name=Name;
Name=Name.toLowerCase();
nameLength=sb.length();
for(i=0;i<nameLength-1;i++)
specialSetCount++;
//System.out.println(sb.charAt(i)+","+sb.charAt(i+1));
if(specialSetCount >= 2)
System.out.println("Congragulations Punk");
else
String Name;
int nameLength;
int specialSetCount=0,i;
StringBuilder sb;
this.Name=Name;
Name=Name.toLowerCase();
for(i=0;i<nameLength-1;i++)
specialSetCount++;
if(specialSetCount >= 2)
System.out.println("Congragulations Punk");
else
class Main
mallOne.specialSet("pavan");
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:
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);
String team;
int match,won,lost,nor,points;
float nrr;
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).
• 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.
Pizza
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.
[L.O.3]
Solution:
import java.util.*;
public InvalidPizzaException(String s)
super(s);
return true;
else
return false;
}
class VegPizza extends Pizza
Boolean test=super.validate(size,type);
try{
if(test==false)
this.size=size;
this.type=type;
}catch(InvalidPizzaException e)
System.out.println("Exception caught");
float x=50*size;
if(type.equals("DELUXE"))
x+=100;
else if(type.equals("SUPREME"))
x+=150;
return x;
Boolean test=super.validate(size,type);
try{
if(test==false)
this.size=size;
this.type=type;
}catch(InvalidPizzaException e)
System.out.println("Exception caught");
float x=100*size;
if(type.equals("DELUXE"))
x+=150;
else if(type.equals("SUPREME"))
x+=200;
return x;
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;
return totalSale;
}*/
String t=s.nextLine();
Pizza p;
if(t.equals("veg"))
p=new VegPizza();
else
p=new NonVegPizza();
float g=PizzaOnline.order(p);
totalSale+=g;
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;
}
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();
{
System.out.println("Printers are ready to print the data");
System.out.println(" ");
System.out.println("Please enter your service from us");
switch (choice) {
case 1:
e.Print();
break;
case 2:
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;
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 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.*;
f.add(b1);
f.add(b2);
f.add(b3);
f.add(l);
f.add(ex);
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();
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);
}
});
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 {
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
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");
}
}
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");
void hai_Order(){
}
}
class Test {
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;
}
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 {
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"));
Collections.sort(listOne);
Collections.sort(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;
list.add("Wood");
list.add("Art");
list.add("GAllery");
list.add("Nails");
list2 = (ArrayList)list.clone();
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;
}
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.*;
String Ramid,Rambrand,store;
int price;
this.Rambrand=Rambrand;
this.Ramid=Ramid;
this.store=store;
this.price=price;
if(price==r.price)
return 0;
else if(price>r.price)
return 1;
else
return -1;
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.start();
try {
Thread.sleep(3000);
catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
String name;
Thread t;
Thread2(String threadname) {
name = threadname;
t.start();
try
Thread.sleep(2000);
catch (InterruptedException e) {
System.out.println(name + "Interrupted");
String name;
Thread t;
Thread3(String threadname) {
name = threadname;
try {
Thread.sleep(500);
catch (InterruptedException e) {
System.out.println(name + "Interrupted");
class MultiThreadDemo {
new Thread1("Thread-1");
new Thread2("Thread-2");
new Thread3("Thread-3");
try {
Thread.sleep(2000);
catch (InterruptedException e) {
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{
if(x==0)
if(x==1)
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);
}
}
Number n;
MyThread_1(Number n){
this.n=n;
n.display(20,0);
Number n;
MyThread_2(Number n){
this.n=n;
n.display(20,1);
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 {
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[];
name = threadname;
this.ar=ar;
t.start();
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");
String name;
Thread t;
char ar[];
this.ar=ar;
name = threadname;
t.start();
try {
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");
}
class Multi{
char ar[]={'a','g','c','f','j'};
new Consonant("Thread-1",ar);
new Vowel("Thread-2",ar);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
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();
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
for(int i=0;i<5;i++)
synchronized(this)
{
String name=Thread.currentThread().getName();
class Check
t1.start();
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("Good"+ t + "everyone!!");
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);}
String position=in.next();
String dest=in.next();
String org=in.next();
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());
}
}
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 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;
}
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);
}
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
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);
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>();
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 {
}
}
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;
}
}
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
int n,positive=0,negative=0,total=0;
float avg=0;
n=sc.nextInt();
int number;
number=sc.nextInt();
if(number>0)
positive++;
if(number<0)
negative++;
total+=number;
/*
int i=1;
int number;
number=sc.nextInt();
if(number>0)
positive++;
}
if(number<0)
negative++;
total+=number;
int i=1;
int number;
number=sc.nextInt();
if(number>0)
positive++;
if(number<0)
negative++;
total+=number;
while(i<=n);
*/
avg=total/n;
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
char c;
int sum=0,n;
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;
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
float f;
String s;
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);
String str=Float.toString(f);
System.out.println(str);
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"))
{
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);
}
}
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;
this.hour=hour;
}
class Captian extends Crew
this.pos=pos;
this.des=des;
this.post=post;
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);
Solution:
import java.util.*;
class five
{
public static void main(String args[])
try
System.out.println("Enter No of racers");
int x;
x=s.nextInt();
s.nextLine();
for(int i=1;i<=x;i++)
String a=s.nextLine();
arr.add(a);
catch(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();
int randomInteger,i;
for(i=0;i<3;i++){
randomInteger=rand.nextInt(10000);
double randomDouble,i;
for(i=0;i<3;i++){
randomDouble=rand.nextDouble();
}
}
class Main{
integerGenerator.generator();
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 Main{
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.*;
{
Vector Vec= new Vector();
Vec.add("chicken");
Vec.add("strawberries");
Vec.add("grains");
Vec.add("wheat");
vec2=(Vector)Vec.clone();
vec2.remove(0);
Solution:
import java.util.*;
import java.lang.*;
import java.io.*;
class item
int cost;
String id)
this.cost =cost;
this.name = name;
this.id =id;
class comparable
for(int i=0;i<2;i++){
int s=sc.nextInt();
String n =sc.nextLine();
String a =sc.nextLine();
ar.add(new item(s,n,a));
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.");
}
}
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:
Solution:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
class first {
int t = sc.nextInt();
int i, j;
String a[], b[], start = "";
int n = sc.nextInt();
HashMap < String, String > h1 = new HashMap < String, String > ();
HashMap < String, String > h2 = new HashMap < String, String > ();
HashMap < String, String > h3 = new HashMap < String, String > ();
// a=new String[n-1];
int x;
String w = "";
int cost = 0;
s[j] = sc.next();
String s2 = sc.next();
h1.put(s2, s[j]);
w = sc.next();
cost = cost + x;
h2.put(s2, w);
h3.put(s[j], s2);
if (h1.containsKey(s[j])) {
continue;
//sb.append(start);
sb=sb.append(start).append("").append(h3.get(start)).append("")
.append(h2.get(h3.getstart))).append("\n");
start = h3.get(start);
System.out.print(sb);
System.out.println(cost + "$");
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);
}
}
}