Java Lab Record
Java Lab Record
JILSE JACOB
RMCA BATCH-A
Roll No : 43
java lab record
1 OBJECT ORIENTED PROGRAMMING LAB
1. Define a class ‘product’ with data members pcode, pname and price. Create 3 objects of
the class and find the product having the lowest price.
import java.util.*;
int pcode;
String pname;
int price;
int smallest;
p1.pcode=1001;
p1.pname="RAM";
p1.price=7000;
p2.pcode=1002;
p2.pname="Processor";
p2.price=37000;
p3.pcode=1003;
p3.pname="SSD";
p3.price=16700;
if(p1.price<p2.price) {
if(p3.price<p1.price) {
smallest = p3.price;
} else {
S2 - REG - MCA 2021
java lab record
2 OBJECT ORIENTED PROGRAMMING LAB
smallest = p1.price;
} else {
if(p2.price<p3.price) {
smallest = p2.price;
} else {
smallest = p3.price;
OUTPUT
RESULT : The program has been executed and the output was verified.
import java.util.*;
class matrixadd{
int row,col,i,j;
row=sc.nextInt();
col=sc.nextInt();
for(i=0;i<row;i++)
for(j=0;j<col;j++)
mat1[i][j]=sc.nextInt();
System.out.println();
for(i=0;i<row;i++)
S2 - REG - MCA 2021
java lab record
4 OBJECT ORIENTED PROGRAMMING LAB
for(j=0;j<col;j++)
mat2[i][j]=sc.nextInt();
System.out.println();
for(i=0;i<row;i++)
for(j=0;j<col;j++)
mat3[i][j]=mat1[i][j]+mat2[i][j];
for(i=0;i<row;i++)
for(j=0;j<col;j++)
System.out.print(mat3[i][j]+"\t");
System.out.println();
}
S2 - REG - MCA 2021
java lab record
5 OBJECT ORIENTED PROGRAMMING LAB
OUTPUT
RESULT : The program has been executed and the output was verified.
double a, b;
this.a = r;
this.b = i;
return temp;
OUTPUT
RESULT : The program has been executed and the output was verified.
4. Read a matrix from the console and check whether it is symmetric or not.
import java.util.Scanner;
matrix[i][j] = sc.nextInt();
System.out.print(matrix[i][j]+"\t");
S2 - REG - MCA 2021
java lab record
9 OBJECT ORIENTED PROGRAMMING LAB
System.out.println();
if(rows != cols)
else
if(matrix[i][j] != matrix[j][i]) {
symmetric = false;
break; }
} }
if(symmetric)
else
} } sc.close();
} }
OUTPUT
RESULT : The program has been executed and the output was verified.
String names[]={"amal","jyothi","college","of","engineering"};
String temp;
int n= names.length;
int i;
int j;
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(names[i].compareTo(names[j])>0)
temp=names[i];
names[i]=names[j];
names[j]=temp;
for(i=0;i<n;i++)
System.out.println(names[i]);
OUTPUT
RESULT : The program has been executed and the output was verified.
import java.util.*;
int n,i,b,flag=0;
n=s.nextInt();
for(i=0;i<n;i++)
a[i]=s.nextInt();
b=s.nextInt();
for(i=0;i<n;i++)
if(a[i]==b)
flag=1;
break;
S2 - REG - MCA 2021
java lab record
14 OBJECT ORIENTED PROGRAMMING LAB
else
flag=0;
if(flag==1)
else
OUTPUT
RESULT : The program has been executed and the output was verified.
} }
OUTPUT
RESULT : The program has been executed and the output was verified.
import java.util.Scanner;
int empid;
String name;
float salary;
empid = in.nextInt();
name = in.next();
salary = in.nextFloat();
e[i].getInput();
e[i].display();
OUTPUT
RESULT : The program has been executed and the output was verified.
{ int side,as,ar;
{ side=a;
as=a*a;
double radi=r;
double ac=(22/7)*radi*radi;
{ int len=l;
int wid=w;
ar=len*wid;
System.out.println("area of rectangle"+ar);
{ int he=h;
double rad=r;
double acy=(2*(22/7)*rad*he)+((22/7)*rad*rad);
System.out.println("area of cylinder"+acy); }
S2 - REG - MCA 2021
java lab record
21 OBJECT ORIENTED PROGRAMMING LAB
s.area(4);//area of square
s.area(5.52);//area of circle
s.area(5,4);//area of rectangle
OUTPUT
RESULT : The program has been executed and the output was verified.
10 .Create a class ‘Employee’ with data members Empid, Name, Salary, Address and
constructors to initialize the data members. Create another class ‘Teacher’ that inherit the
properties of class employee and contain its own data members department, Subjects taught
and constructors to initialize these data members and also include display function to display
all the data members. Use array of objects to display details of N teachers.
import java.util.*;
class Employee
int empid;
String name,address;
double salary;
this.empid = empid;
this.name = name;
this.address = address;
this.salary = salary;
String subject,department;
public Teacher(int empid, String name, String address, double salary,String department,String
subject ) {
this.subject = subject;
this.department = department;
S2 - REG - MCA 2021
java lab record
23 OBJECT ORIENTED PROGRAMMING LAB
void display()
int n;
n=sc.nextInt();
for(int i=0;i<n;i++) {
int j = i+1;
System.out.println("\n-------------------------------------------------------------------------\n");
for(int i=0;i<n;i++) {
obj[i].display();
OUTPUT
RESULT : The program has been executed and the output was verified.
S2 - REG - MCA 2021
java lab record
25 OBJECT ORIENTED PROGRAMMING LAB
11.Create a class ‘Person’ with data members Name, Gender, Address, Age and
a constructor to initialize the data members and another class ‘Employee’ that
inherits the properties of class Person and also contains its own data members
like Empid, Company_name, Qualification, Salary and its own constructor.
Create another class ‘Teacher’ that inherits the properties of class Employee and
contains its own data members like Subject, Department, Teacherid and also
contain constructors and methods to display the data members. Use array of
objects to display details of N teachers.
import java.util.Scanner;
class Person
{ String name,gender,address;
int age;
super();
this.name = name;
this.gender = gender;
this.address = address;
this.age = age; } }
int empid;
String company_name,qualification;
double salary;
public Employee(String name, String gender, String address, int age, int empid, String
company_name,
this.empid = empid;
this.company_name = company_name;
this.qualification = qualification;
this.salary = salary; } }
String subject,department;
int teacherid;
public Teacher(String name, String gender, String address, int age, int empid, String
company_name,
String qualification, double salary, String subject, String department, int teacherid) {
this.subject = subject;
this.department = department;
this.teacherid = teacherid; }
void display() {
System.out.println("....Personal details...");
System.out.println("...Employee details....");
System.out.println("...Teacher's details...");
int n;
for(int i=0;i<n;i++) {
int id1=s.nextInt();
String cname1=s.next();
double sal1=s.nextDouble();
String qu1=s.next();
int tid1=s.nextInt();
String dept1=s.next();
String sub1=s.next();
obj[i]=new Teacher(nam1,gen1,adr1,age1,id1,cname1,qu1,sal1,sub1,dept1,tid1); }
System.out.println("\n-------------------------------------------------------------------------\n");
for(int i=0;i<n;i++) {
obj[i].display(); } } }
OUTPUT
RESULT : The program has been executed and the output was verified.
12 . Write a program has class Publisher, Book, Literature and Fiction. Read the
information and print the details of books from either the category, using
inheritance.
import java.util.Scanner;
class Publisher {
String Pubname;
Publisher()
Pubname=s.next();
int price;
Book()
title=s.next();
author=s.next();
System.out.println("Enter price");
price=s.nextInt();
}}
{ Literature()
{ System.out.println("Literature Books"); }
void display()
System.out.println("Price: "+price);
}}
{ Fiction()
{ System.out.println("Friction Books"); }
void display()
{ super.display(); }
{ int n;
int a=s.nextInt();
for(int i=0;i<a;i++)
{ L[i]=new Literature(); }
int b=s.nextInt();
for(int i=0;i<b;i++)
{ F[i]=new Fiction(); }
int no;
no=s.nextInt();
switch (no) {
case 1:
for(int i=0;i<a;i++)
L[i].display();
break;
case 2:
for(int i=0;i<b;i++)
F[i].display();
break;
default:
System.out.println("Wrong input"); } }
OUTPUT
RESULT : The program has been executed and the output was verified.
13. Create classes Student and Sports. Create another class Result inherited
from Student and Sports. Display the academic and sports score of a student.
interface student
{ void stresullt(); }
interface sports
{ void spresult(); }
String hundred="First";
String twohundred="Second";
String fivehundred="First";
String relay="Second";
System.out.println("Sports Result");
System.out.println("Hundred Meter:"+hundred);
System.out.println("Relay:"+relay); }
int physics=30;
int chemistry=40;
int maths=45;
int english=50;
int computer=50;
System.out.println("Marks");
System.out.println("Physics:"+physics);
System.out.println("Chemistry:"+chemistry);
System.out.println("Mathematics:"+maths);
System.out.println("English:"+english);
System.out.println("Computer:"+computer); }
r.stresullt();
r.spresult(); } }
OUTPUT
RESULT : The program has been executed and the output was verified.
import java.util.Scanner;
interface Shape
void input();
void area();
void perimeter();
int r = 0;
r= s.nextInt();
ar = pi * r * r;
System.out.println("Area of circle:"+ar);
per = 2 * pi * r;
System.out.println("Perimeter of circle:"+per);
int l = 0, b = 0;
double ar,per;
l = s.nextInt();
b = s.nextInt(); }
{ ar = l * b;
System.out.println("Area of rectangle:"+ar); }
{ per = 2 * (l + b);
System.out.println("Perimeter of rectangle:"+per); } }
{ int n;
System.out.println("1.Area of circle");
System.out.println("2.Perimeter of circle");
System.out.println("3.Area of rectangle");
System.out.println("4.Perimeter of rectangle");
n= s.nextInt();
switch(n) {
case 1:
obj2.input();
obj2.area();
break;
case 2:
obj2.input();
obj2.perimeter();
break;
case 3:
obj2.input();
obj2.area();
break;
case 4:
obj2.input();
S2 - REG - MCA 2021
java lab record
38 OBJECT ORIENTED PROGRAMMING LAB
obj2.perimeter();
break;
default:
System.out.println("Invalid option");
OUTPUT
RESULT : The program has been executed and the output was verified.
15.Prepare bill with the given format using calculate method from interface.
Order No.
interface bill
int productdetails();
String name="A";
System.out.println("Product Id :"+id);
System.out.println("Name :"+name);
System.out.println("Quantity :"+quantity);
System.out.println("Total :"+total);
return(total);
String name="B";
System.out.println("Product Id :"+id);
System.out.println("Name :"+name);
System.out.println("Quantity :"+quantity);
System.out.println("Total :"+total);
return(total); } }
int t3=t1+t2;
OUTPUT
RESULT : The program has been executed and the output was verified.
16.Create a Graphics package that has classes and interfaces for figures
Rectangle, Triangle, Square and Circle. Test the package by finding the
area of these figures.
package Graphiccs;
interface Area1
{
public void Rectangle(); public
void Triangle(); public void
Square(); public void Circle();
public void getRect(); public void
getTri(); public void getSqr(); public
void getCrl();
}
//shapes.java
ra=lr*lb;
ta=0.5*th*tb;
saa=sa*sa;
cr=3.14*cc*cc;
o.getSqr();
o.Square();
o.getCrl();
o.Circle();
}
OUTPUT
RESULT : The program has been executed and the output was verified.
17. Create an Arithmetic package that has classes and interfaces for the 4
basic arithmetic operations. Test the package by implementing all
operations on two given numbers
package Aarithmetic;
interface operations
ad=a+b;
System.out.println("Sum is "+ad);
dif=a-b;
System.out.println("Difference is "+dif);
mult=a*b;
System.out.println("Product is "+mult);
div=a/b;
System.out.println("Quotient is "+div);
OUTPUT
RESULT : The program has been executed and the output was verified.
18. Write a user defined exception class to authenticate the user name and
password.
import java.util.Scanner;
super(msg);
super(msg);
username = s.nextLine();
password = s.nextLine();
try {
if(length < 6)
else if(!password.equals("hello"))
else
catch (UsernameException u) {
u.printStackTrace();
catch (PasswordException p) {
p.printStackTrace();
finally {
OUTPUT
RESULT : The program has been executed and the output was verified.
19. Find the average of N positive integers, raising a user defined exception for
each negative input.
import java.util.Scanner;
import java.util.InputMismatchException;
while (true)
userInput = input.nextDouble();
if (userInput > 0)
N = userInput;
break;
else
while (true)
System.out.print("Enter number:");
try
userInput = input.nextDouble();
total += userInput;
break;
catch (InputMismatchException e)
input.nextLine();
OUTPUT
RESULT : The program has been executed and the output was verified.
20. Define 2 classes; one for generating multiplication table of 5 and other for
displaying first N prime numbers. Implement using threads. (Thread class)
import java.util.*;
int n = 5;
int i,n,p,count,flag;
n=sc.nextInt();
p=2;
i=1;
while(i<=n)
flag=1;
for(count=2;count<=p-1;count++)
if(p%count==0)
flag=0;
break;
if(flag==1)
System.out.print(p+" ") ;
i++;
p++;
a.start();
b.start();
OUTPUT
RESULT : The program has been executed and the output was verified.
21. Define 2 classes; one for generating Fibonacci numbers and other for
displaying even numbers in a given range. Implement using threads. (Runnable
Interface)
public class Mythread {
t.start();
t2.start();
for(int i=0;i<11;i++){
if(i%2 == 1)
System.out.println(i);
int n1=0,n2=1,n3,i,count=10;
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
OUTPUT
RESULT : The program has been executed and the output was verified.
import java.applet.*;
{ g.setColor(Color.red);
g.fillOval(80,70,150,150);
g.drawOval(80,70,150,150);
g.setColor(Color.BLACK);
<html>
<head>
</head>
<body>
<div align="center">
<applet code="circle.class"width="800"height="500">
</applet>
</div>
</body>
</html>
import java.awt.*;
import java.applet.*;
{ g.setColor(Color.YELLOW);
g.fillRect(50,100,180,80);
g.setColor(Color.BLACK);
g.drawRect(50,100,180,80);
<html>
<head>
</head>
<body>
<div align="center">
<applet code="rectapplet.class"width="800"height="500">
S2 - REG - MCA 2021
java lab record
60 OBJECT ORIENTED PROGRAMMING LAB
</applet>
</div>
</body>
</html>
RESULT : The program has been executed and the output was verified.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
TextField t1,t2,t3,t4;
Button b1;
t1=new TextField(15);
t1.setBounds(100,25,50,20);
t2=new TextField(15);
t2.setBounds(100,25,50,20);
t3=new TextField(15);
t3.setBounds(100,25,50,20);
t4=new TextField("Ans");
t4.setBounds(175,50,50,20);
b1.setBounds(175,65,50,40);
add(t1);
add(t2);
add(t3);
add(t4);
add(b1);
S2 - REG - MCA 2021
java lab record
62 OBJECT ORIENTED PROGRAMMING LAB
b1.addActionListener(this);
int i,j,k;
i=Integer.parseInt(t1.getText());
j=Integer.parseInt(t2.getText());
k=Integer.parseInt(t3.getText());
if(i<j)
if(j<k)
t4.setText(""+k);
else
t4.setText(""+j);
else
t4.setText(""+i);
<html>
<head>
</head>
<body>
<div align="center">
</applet>
</div>
</body>
</html>
OUTPUT
RESULT : The program has been executed and the output was verified.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public marks()
setLayout(g1);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(l4);
add(t4);
add(l5);
S2 - REG - MCA 2021
java lab record
66 OBJECT ORIENTED PROGRAMMING LAB
add(t5);
add(l6);
add(t6);
add(b1);
b1.addActionListener(this);
@Override
int m1 = Integer.parseInt(t1.getText());
if(e.getSource()==b1)
int add=m1+m2+m3+m4+m5;
per=add/5;
t6.setText(String.valueOf(per)+" %");
repaint();
if(per>=50)
g.setColor(Color.yellow);
g.setColor(Color.BLACK);
g.setColor(Color.yellow);
g.setColor(Color.BLACK);
g.drawArc(130,820,50,20,0,180);
new marks();
} }
<html><head>
S2 - REG - MCA 2021
java lab record
68 OBJECT ORIENTED PROGRAMMING LAB
</head>
<body><div align="center">
<applet code="marks.class"width="1000"height="1000">
</applet></div>
</body></html>
OUTPUT
RESULT : The program has been executed and the output was verified.
S2 - REG - MCA 2021
java lab record
69 OBJECT ORIENTED PROGRAMMING LAB
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
g.setColor(Color.blue);
g.setColor(textColor);
g.setColor(Color.black);
this.setSize(200,200);
addMouseListener(this);
while(true)
repaint();
try
Thread.sleep(17);
catch (InterruptedException e)
e.printStackTrace();
int x=e.getX(),y=e.getY();
textColor=Color.BLUE;
else
textColor=Color.RED;
repaint();
<html><head></head>
<body><div align="center">
<applet code="house.class"width="800"height="500">
</applet></div>
</body></html>
OUTPUT
RESULT : The program has been executed and the output was verified.
import java.awt.event.*;
calc() {
l1.setBounds(50,100,100,20);
l2.setBounds(50,150,100,20);
l3.setBounds(50,200,100,20);
t1.setBounds(200,100,100,20);
t2.setBounds(200,150,100,20);
t3.setBounds(200,200,100,20);
b1.setBounds(50,250,50,20);
b2.setBounds(110,250,50,20);
b3.setBounds(170,250,50,20);
S2 - REG - MCA 2021
java lab record
74 OBJECT ORIENTED PROGRAMMING LAB
b4.setBounds(230,250,50,20);
f.add(l1);
f.add(l2);
f.add(t1);
f.add(t2);
f.add(t3);
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
f.setLayout(null);
f.setVisible(true);
f.setSize(500,500); }
int i=Integer.parseInt(t1.getText());
int j=Integer.parseInt(t2.getText());
if(e.getSource()==b1) {
t3.setText(String.valueOf(i+j)); }
if(e.getSource()==b2) {
t3.setText(String.valueOf(i-j)); }
if(e.getSource()==b3)
{
S2 - REG - MCA 2021
java lab record
75 OBJECT ORIENTED PROGRAMMING LAB
t3.setText(String.valueOf(i*j));
if(e.getSource()==b4)
t3.setText(String.valueOf(i/j)); }
new calc();
OUTPUT
RESULT : The program has been executed and the output was verified.
27. Develop a program that has a Choice component which contains the
names of shapes such as rectangle, triangle, square and circle. Draw the
corresponding shapes for given parameters as per user’s choice.
import java.applet.*;
import java.awt.*;
import java.awt.Graphics;
import java.awt.event.*;
Choice ch;
int n=4;
int Selection;
ch = new Choice();
ch.addItem("Select a Shape");
ch.addItem("Rectangle");
ch.addItem("Triangle");
ch.addItem("Square");
ch.addItem("Circle");
add(ch);
ch.addItemListener(this);
Selection = ch.getSelectedIndex();
repaint();
super.paint(g);
if (Selection == 1)
{ g.drawRect(50,50,100,150); }
if (Selection == 2)
{ g.drawPolygon(x1,y1,n); }
if (Selection == 3)
{ g.drawRect(50,50,100,100); }
if (Selection == 4)
g.drawOval(70,30,100,100);
}}}
<html><head>
</head>
<body>
<div align="center">
<applet code="figchoice.class"width="800"height="500">
</applet>
</div>
</body>
</html>
S2 - REG - MCA 2021
java lab record
79 OBJECT ORIENTED PROGRAMMING LAB
OUTPUT
RESULT : The program has been executed and the output was verified.
}
public void windowOpened(WindowEvent arg0)
{
System.out.println("Window opened");
}
}
OUTPUT
RESULT : The program has been executed and the output was verified.
import java.awt.event.*;
mousexamp12()
addMouseListener(this);
setSize(400,400);
setLayout(null);
setVisible(true);
Graphics g=getGraphics();
g.setColor(Color.blue);
g.fillOval(e.getX(),e.getY(),30,30);
new mousexamp12();
OUTPUT
RESULT : The program has been executed and the output was verified.
import java.awt.event.*;
Label l;
TextArea a;
keyexamp()
l=new Label();
l.setBounds(20,50,200,20);
a=new TextArea();
a.setBounds(20,80,300,300);
a.addKeyListener(this);
add(l);
add(a);
setSize(400,400);
setLayout(null);
setVisible(true);
String t=a.getText();
String w[]=t.split("\\s");
l.setText("Words="+w.length+" Characters="+t.length());
S2 - REG - MCA 2021
java lab record
86 OBJECT ORIENTED PROGRAMMING LAB
{}
new keyexamp();
OUTPUT
RESULT : The program has been executed and the output was verified.
class Q
int n;
boolean statusFlag=false;
try
while(statusFlag)
wait();
catch(InterruptedException e){}
this.n=n;
System.out.println("Put :"+n);
statusFlag=true;
notify();
try{
while(!statusFlag)
S2 - REG - MCA 2021
java lab record
88 OBJECT ORIENTED PROGRAMMING LAB
wait();
catch(InterruptedException e){}
statusFlag=false;
System.out.println("Got :"+n);
notify();
return n;
Q q;
Producer(Q q)
this.q=q;
int i=0;
while(true)
q.put(i++);
}
S2 - REG - MCA 2021
java lab record
89 OBJECT ORIENTED PROGRAMMING LAB
Q q;
Consumer(Q q)
this.q=q;
new Thread(this,"Consumer").start();
while(true)
q.get();
public class D
Q q=new Q();
}
S2 - REG - MCA 2021
java lab record
90 OBJECT ORIENTED PROGRAMMING LAB
OUTPUT
RESULT : The program has been executed and the output was verified.
32. Program to create a generic stack and do the Push and Pop operations.
StackNode root;
int data;
StackNode next;
if (root == null) {
return true;
else
return false;
if (root == null) {
S2 - REG - MCA 2021
java lab record
92 OBJECT ORIENTED PROGRAMMING LAB
root = newNode;
else {
root = newNode;
newNode.next = temp;
if (root == null) {
System.out.println("Stack is Empty");
else {
popped = root.data;
root = root.next;
return popped;
if (root == null) {
S2 - REG - MCA 2021
java lab record
93 OBJECT ORIENTED PROGRAMMING LAB
System.out.println("Stack is empty");
return Integer.MIN_VALUE;
else {
return root.data;
// Driver code
sll.push(10);
sll.push(20);
sll.push(30);
System.out.println(sll.pop()
OUTPUT
RESULT : The program has been executed and the output was verified.
int n = arr.length;
int temp = 0;
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
System.out.println();
bubbleSort(arr);
OUTPUT
RESULT : The program has been executed and the output was verified.
class PriorityQueue1{
queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Jai");
queue.add("Rahul");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
queue.remove();
queue.poll();
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
OUTPUT
RESULT : The program has been executed and the output was verified.
import java.util.*;
l_list.add("violet");
l_list.add("Green");
l_list.add("Black");
l_list.add("Pink");
l_list.add("blue");
l_list.clear();
}}
OUTPUT
RESULT : The program has been executed and the output was verified.
// in various ways
deque.add("Element 1 (Tail)");
deque.addFirst("Element 2 (Head)");
deque.addLast("Element 3 (Tail)");
deque.push("Element 4 (Head)");
deque.offer("Element 5 (Tail)");
deque.offerFirst("Element 6 (Head)");
System.out.println(deque + "\n");
// or the lastelement.
deque.removeFirst();
deque.removeLast();
OUTPUT
RESULT : The program has been executed and the output was verified.
class arrayjava{
alist.add("appu");
alist.add("ammu");
alist.add("minnu"); alist.add("thomu");
alist.add("pinky"); alist.add("Tom");
//displaying elements
System.out.println(alist);
//displaying elements
System.out.println(alist);
} }
OUTPUT
RESULT : The program has been executed and the output was verified.
class HashMapDemo {
System.out.print(me.getKey() + ":");
System.out.println(me.getValue()); }
} }
OUTPUT
RESULT : The program has been executed and the output was verified.
import java.util.stream.*;
public class HT
map.put("1", "One");
map.put("2", "Two");
map.put("3", "Three");
map.put("4", "Four");
map.put("5", "Five");
map.put("6", "Six");
map.put("7", "Seven");
map.put("8", "Eight");
map.put("9", "Nine");
treeMap.putAll(map);
OUTPUT
RESULT : The program has been executed and the output was verified.
40. Program to list the sub directories and files in a given directory and
also search for a file name.
import java.io.File;
import java.util.*;
import java.io.*;
public class p1 {
public static final String RED="\033[0;31m";
public static final String RESET="\033[0m";
static void RecursivePrint(File[] arr, int index, int level, String search
for) {
// exit condition
if (index == arr.length)
return;
// space for internbal level
for (int i = 0; i < level; i++)
System.out.print("\t");
if(arr[index].getName().toLowerCase().contains(searchfor))
System.out.print(RED);
else
System.out.print(RESET);
// for files
if (arr[index].isFile())
System.out.println(arr[index].getName());
else if (arr[index].isDirectory()) {
System.out.println("[" + arr[index].getName() + "]");
RecursivePrint(arr[index].listFiles(), 0, level + 1, searchfor);
}
RecursivePrint(arr, ++index, level, searchfor);
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the directory path");
String maindirpath = scan.nextLine();
System.out.println("Enter the file/directory name to search");
String searchfor = scan.nextLine();
File maindir = new File(maindirpath);
if (maindir.exists() && maindir.isDirectory()) {
File arr[] = maindir.listFiles();
System.out.println("#############################################
#
###");
System.out.println("Files from main directory" + maindir);
System.out.println("#############################################
#
###");
RecursivePrint(arr, 0, 0, searchfor.toLowerCase()); // array,index
,level,search
}
}
}
OUTPUT
RESULT : The program has been executed and the output was verified.
41. Write a program to write to a file, then read from the file and display
the contents on the console.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.*;
import java.util.*;
import java.io.File;
class read {
public static void main(String[] args) {
String var = "";
Scanner scan = new Scanner(System.in);
System.out.println("Enter the text to create file : type exit to stop"
);
while (!var.endsWith("exit\n"))
var = var + scan.nextLine()+"\n";
try {
File file = new File("output.txt");
FileWriter fw = new FileWriter(file);
fw.write(var);
fw.close();
System.out.println("Reading File content");
FileReader fr = new FileReader("output.txt");
String str = "";
int i;
while ((i = fr.read()) != -1) {
// Storing every character in the string
str += (char) i;
}
System.out.println(str);
fr.close();
} catch (IOException e) {
System.out.println("There are some exception");
}
}
}
Output
RESULT : The program has been executed and the output was verified.