Java Lab Manul - Merged
Java Lab Manul - Merged
Java Lab Manul - Merged
Submitted By
Jha Harshkumar Rajeshraman
12302130603006
JAVA (202040403)
A.Y.2023-2024
Certificate
External/Internal Examiner
Index
NO List of Practical Page Date sign
No.
Basic Program 1. Study of class path and java runtime 1
1 environment 2. Write a program to
● Implement command line calculator
● Write To prints Fibonacci series.
Array: 6
2 1. Define a class Array with following member Field:
int data[];
Function:
Array( ) //create array data of size 10
Array(int size) // create array of size size
Array(int data[]) // initialize array with parameter array
void Reverse _an _array () //reverse element of an array
int Maximum _of _array () // find maximum element of
array
int Average_of _array() //find average of element of array
void Sorting () //sort element of array void display()
//display element of array
int search(int no) //search element and return index else
return -1
int size(); //return size of an array
Use all the function in main method. Create different
objects with different constructors.
2. Define a class Matrix with following
Field:
int row, column;
float mat[][]
Function:
Matrix(int a[][])
Matrix()
Matrix(int rwo, int col)
void readMatrix() //read element of array
float [][] transpose( ) //find transpose of first matrix
Array:
1. Define a class Array with following member Field:
int data[];
Function:
Array( ) //create array data of size 10
Array(int size) // create array of size size
Array(int data[]) // initialize array with parameter array
void Reverse _an _array () //reverse element of an array
int Maximum _of _array () // find maximum element of
array
int Average_of _array() //find average of element of array
void Sorting () //sort element of array void display()
//display element of array
int search(int no) //search element and return index else
return -1
int size(); //return size of an array
Use all the function in main method. Create different
objects with different constructors.
2. Define a class Matrix with following
Field:
int row, column;
float mat[][]
Function:
Matrix(int a[][])
Matrix()
Matrix(int rwo, int col)
void readMatrix() //read element of array
float [][] transpose( ) //find transpose of first matrix
5 Inner Class: 50
Define two nested classes: Processor and RAM inside the
outer class: CPU with following
data members
class CPU { double
price;
class Processor{ // nested class
double cores; double catch()
String manufacturer; double
getCache()
void displayProcesorDetail()
}
protected class RAM{ // nested protected class
// members of protected nested class
double memory; String
manufacturer; Double
clockSpeed; double
getClockSpeed()
void displayRAMDetail()
}
}
1. Write appropriate Constructor and create
instance of Outer and inner class and call the methods in
main function
Write a program to demonstrate usage of static inner
class, local inner class and anonymous inner class
6 Generics 57
1. Declare a class InvoiceDetail which accepts a type
parameter which is of type
Number with following data members
class InvoiceDetail <N extends Number> {
private String invoiceName; private N
amount; private N Discount
// write getters, setters and constructors
}
Call the methods in Main class
2. Implement Generic Stack
3. Write a program to sort the object of Book class
using comparable and comparator
interface. (Book class consist of book id, title, author and
publisher as data members)
7 Exception Handing 67
1. Write a program for creating a Bank class, which is used
to manage the bank
account of customers. Class has two methods, Deposit ()
and withdraw (). Deposit method display old balance and
new balance after depositing the specified amount.
Withdrew method display old balance and new balance
after withdrawing. If
balance is not enough to withdraw the money, it throws
ArithmeticException and
if balance is less than 500rs after withdrawing then it
throw custom exception, NotEnoughMoneyException.
2. Write a complete program for calculation average of n
+ve integer numbers of Array A.
a. Read the array form keyboard
b. Raise and handle Exception if
i. Element value is -ve or non-integer. ii. If n is zero.
8 Threading 73
1. Write a program to find prime number in given range
using both method of
multithreading. Also run the same program using executor
framework
2. Assume one class Queue that defines queue of fix size
says 15.
● Assume one class producer which implements
Runnable, having priority
NORM_PRIORITY +1
● One more class consumer implements Runnable,
having priority
NORM_PRIORITY-1
● Class TestThread is having main method with
maximum priority, which creates
1 thread for producer and 2 threads for consumer.
● Producer produces number of elements and put on the
queue. when queue becomes full it notifies other threads.
9 Collection API: 80
1. Write a program to demostrate user of ArrayList,
LinkedList ,LinkedHashMap,
TreeMap and HashSet Class. And also implement CRUD
operation without database connection using Collection
API.
2. Write a program to Sort
Array,ArrayList,String,List,Map and Set
10 File Handling Using Java: 88
1. Write a programme to count occurrence of a given
words in a file.
2. Write a program to print it seltf.
Write a program to display list of all the files of given
directory
11 Networking 92
1. Implement Echo client/server program using TCP 2.
Write a program using UDP which give name of the audio
file to server and server reply with content of audio file
12 1. Write a programme to implement an investement 99
value calculator using the data
By ordinary method
Step 1: Open a Environment Variables Dialog box by search box
1|Page
Step 2: Click on New Button -> Enter PATH as a variable name and copy the path of bin file of
By Command Prompt
Syntax: set path=”<drive>:[%PATH%]”;
2|Page
2. Write a program to
● Implement command line calculator
class Calculator
{
int a;
int b;
class CalDemo
{
public static void main(String [] args)
{
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
3|Page
System.out.println("sum: "+a);
int b=ob.sub(x,y);
System.out.println("sub: "+b);
int c=ob.mul(x,y);
System.out.println("mul: "+c);
int d=ob.div(x,y);
System.out.println("div: "+d);
}
}
Output:-
int n1=0;
int n2=1;
int i; int
n3; int
count=20;
4|Page
System.out.println(+n1);
for(i=2;i<count;++i)
n3=n1+n2;
System.out.println(" "+n3);
n1=n2;
n2=n3;
Output:-
5|Page
Practical:-2
Array:
1. Define a class Array with following member Field:
class Array
{
int n,max=0; int
data[]=new int[100];
float sum=0,avg=0;
Array()
{
n=10; for(int
i=0;i<n;++i) {
6|Page
data[i]=0;
}
}
Array(int size)
{
n=size;
for(int i=0; i<n; ++i)
{
data[i]=0;
}
}
Array(int a[])
{
n=a.length;
for(int i=0; i<n; ++i)
{
data[i]=a[i];
}
}
void Sum()
{
for(int i=0;i<n;++i)
{
sum+=data[i];
}
System.out.println("Sum of the elements are: "+sum);
}
void average()
{
avg=sum/n;
System.out.println("Average of the elements are: "+avg);
}
7|Page
void display()
{
System.out.println("Elements Are:");
for(int i=0;i<n;++i)
{
System.out.print(data[i]+" ");
}
System.out.println(" ");
System.out.println("Sum of the elements are: "+sum);
System.out.println("Average of the elements are: "+avg);
}
void Find_Max_Element()
{
max=data[0];
for(int i=0;i<n;++i)
{
8|Page
if(data[i]>max)
{
max=data[i];
}
}
System.out.println("Maximum element in the array is: "+max);
}
void Reverse_order()
{
System.out.println("Elements in Reverse order are:");
for(int i=n-1;i>=0;--i)
{
System.out.print(data[i]+" ");
}
System.out.println(" ");
}
void Sorted_data()
{
int temp; for(int
i=0;i<n;++i)
{
for(int j=i+1;j<n;++j)
{
if(data[i]>data[j])
{
temp=data[i]; data[i]=data[j]; data[j]=temp;
}
}
}
System.out.println("Elements after array is Sorted are:"); for(int
i=0;i<n;++i)
{
9|Page
System.out.print(data[i]+" ");
}
System.out.println(" ");
}
}
class ArrayDemo
{
public static void main(String args[])
{
Array a1=new Array();
Array a2=new Array(9);
int a[]={4,3,2,1,5,6,8,7,9};
Array a3=new Array(a);
a3.Sum(); a3.average();
a3.search_data(2);
a3.Find_Max_Element();
a3.display();
a3.Reverse_order();
a3.Sorted_data();
}
}
10 | P a g e
OutPut:-
11 | P a g e
float maximum_of_array() // return maximum element of first
array
float average_of_array( ) // return average of first array
create three object of Matrix class with different constructors
in main and test all the functions in main
import java.util.Scanner;
public class Matrix
{
Scanner sc = new Scanner(System.in); int row,column; float mat[][];
public Matrix()
{
this.mat = new float[3][3];
}
public Matrix(float[][] a)
{
this.mat = a;
}
void readMatrix()
{
for (int i = 0; i < mat.length; i++)
{
for (int j = 0; j < mat.length; j++)
{
mat[i][j] = sc.nextFloat();
}
}
}
float[][] transpose()
12 | P a g e
{
float mat1[][] = new float[3][3]; for (int i = 0; i < mat.length; i++)
{
for (int j = 0; j < mat.length;j++)
{
mat1[i][j] = mat[j][i];
}
}
return mat1;
}
void displayMatrix(float[][] a)
{
for (int i = 0; i < a.length; i++)
{
void displayMatrix()
{
for (int i = 0; i < mat.length; i++)
{
for (int j = 0; j < mat.length; j++)
{
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
}
float maximum_of_array()
{
13 | P a g e
float max = 0; for (int i = 0; i <
mat.length; i++)
{
for (int j = 0; j < mat.length; j++)
{
if (mat[i][j] > max)
{
} else
{
max = mat[i][j];
}
}
return max;
}
float average_of_array()
{
float avg = 0; int count = 0; for
(int i = 0; i < mat.length; i++)
{
for (int j = 0; j < mat.length; j++)
{
avg = avg + mat[i][j]; count++;
}
}
avg = avg / count;
return avg;
}
15 | P a g e
System.out.println("Displaying average of array B: " + avg);
System.out.println("Product of Matrices A and B is: "); d.mat
= d.matrixMultiplication(a, b);
Double d= 22.11;
String t=d.toString();
System.out.println("t:"+t);
}
}
OutPut:-
17 | P a g e
{
System.out.println(a);
System.out.println(a.replace('H','B'));
System.out.println(a);
sb.append(",I ammutable");
sb.reverse();
18 | P a g e
OutPut:-
class Cipher
19 | P a g e
String plainText; int
key;
this.plainText = plainText;
this.key = key;
String Encryption()
this.plainText.toCharArray();
arr[i] = ((char)(arr[i]+3));
encrypted_str = String.valueOf(arr);
return encrypted_str;
20 | P a g e
String Decryption()
String decrypted_str;
arr[i] = ((char)(arr[i]-3));
decrypted_str;
OutPut:-
21 | P a g e
Practical:-3
1. Create a class BankAccount that has Depositor name , Acc_no,
Acc_type, Balance as
Data Members and void createAcc() . void Deposit(), void
withdraw() and void
BalanceInquiry as Member Function. When a new Account is
created assign next serial no as account number. Account
number starts from 1
import java.util.Scanner;
class BankAccount {
balance;
accNo = nextAccountNumber++;
22 | P a g e
System.out.println("Enter Depositor Name: ");
depositorName = sc.nextLine();
accType = sc.nextLine();
balance = sc.nextDouble();
balance += amount;
} else
23 | P a g e
// Member Function to withdraw money
balance -= amount;
} else
24 | P a g e
}
account.createAcc();
// Perform transactions
account.deposit();
account.withdraw();
account.balanceInquiry();
} OutPut:-
25 | P a g e
2. Create a class time that has hour, minute and second as data
members. Create a
parameterized constructor to initialize Time Objects. Create a
member Function
Time Sum (Time, Time) to sum two time objects.
public class Time {
second; //
Parameterized
constructor to initialize
int second) {
this.hour = hour;
this.minute = minute;
this.second = second;
26 | P a g e
sumMinute = time1.minute + time2.minute; int
sumMinute++;
sumHour -= 24;
27 | P a g e
System.out.println("Sum of time1 and time2: " + sumTime.hour + " hours, " +
OutPut:-
((netSalary -100000)*tds);
class EmployeeDemo
29 | P a g e
public static void main (String [] args)
System.out.println(e1);
} OutPut:-
30 | P a g e
Practical:-4
1. class Cricket having data members name, age and member
methods display() and
setdata(). class Match inherits Cricket and has data members
no_of_odi, no_of_test.
Create an array of 5 objects of class Match. Provide all the
required data through command line and display the
information.
import java.util.Scanner; class
cricket
String name;
setdata()
age=obj.nextInt();
void display()
31 | P a g e
System.out.println("The age of the cricket player is " + age);
int no_of_odi;
int no_of_test;
void setdata()
super.setdata();
System.out.println("Enter number of odi and test matches played by the cricket player ");
void display()
super.display();
class pa
32 | P a g e
{
i=0;i<5;i++)
i=0;i<5;i++)
ob[i].display();
33 | P a g e
OutPut:-
34 | P a g e
2. Define a class Cripher with following data
Field:
String plainText; int
key
Functions:
Cipher(String plaintext,int key)
abstract String Encryption( )
cipher(String plaintext,int k)
plainText=plaintext; key=k;
String Decryption();
{ int d;
char ab;
String encode="abcdefghijklmnopqrstuvwxyz";
String decode="qazwsxedcrfvtgbyhnujmikolp";
Substitution_Cipher(String s,int k)
super(s,k);
String Encryption()
36 | P a g e
char xy[]=plainText.toCharArray();
for(int i=0;i<xy.length;i++)
d=encode.indexOf(xy[i]);
ab=decode.charAt(d); test[i]=ab;
plainText;
String Decryption()
char xy[]=plainText.toCharArray();
for(int i=0;i<xy.length;i++)
plainText;
37 | P a g e
{
super(plain,key);
String Encryption()
i=0;i<xy.length;i++)
xy[i]=(char)(xy[i]+key);
plainText;
String Decryption()
i=0;i<xy.length;i++)
xy[i]=(char)(xy[i]-key);
38 | P a g e
plainText=new String(xy); return
plainText;
class pb
ob.Encryption();
System.out.println();
39 | P a g e
OutPut:-
40 | P a g e
computePrice for both classes for computing total price. Use
following rules for computing total price by summing up sub-
costs:
Construction cost(for both classes):Rs.500/- per sq.feet
Additional cost ( for Flat) : Rs. 200000/-
( for Bungalow ): Rs. 200/- per sq.
feet for landArea
Land cost ( only for Bungalow ): Rs. 400/- per sq. feet
Define method main to show usage of method computePrice.
interface property
{ int
cost=0;
int lname,constructionarea;
41 | P a g e
name=s;
constructionarea=a;
lname=b;
return cost;
{ int
cost=0;
int constructionarea;
flat(String s,int a)
name=s;
constructionarea=a;
cost+=(500*constructionarea) + 200000;
42 | P a g e
return cost;
class pc
OutPut:-
43 | P a g e
4. Define following classes and interfaces.
public interface GeometricShape { public
void describe();
}
public interface TwoDShape extends GeometricShape { public
double area();
}
public interface ThreeDShape extends GeometricShape { public
double volume();
}
public class Cone implements ThreeDShape {
private double radius; private double height;
describe()
}
public class Rectangle implements TwoDShape {
private double width, height; public Rectangle
(double width, double height) public double
44 | P a g e
area() public double perimeter() public void
describe()
}
public class Sphere implements ThreeDShape {
private double radius; public Sphere (double
radius) public double volume() public void
describe()
}
Define test class to call various methods of Geometric Shape
interface GeometricShape
45 | P a g e
class Cone implements ThreeDShape
double vol;
(double r, double h)
radius=r;
height=h;
vol= (3.14*radius*radius*height)/3;
return vol;
System.out.println("This Is Cone.");
System.out.println("Radius=" +radius);
System.out.println("Height=" +height);
46 | P a g e
class Rectangle implements TwoDShape
(double w, double h)
width=w; height=h;
are=width*height; return
are;
peri=2*(width+height); return
peri;
System.out.println("This Is Rectangle");
System.out.println("Width=" +width);
System.out.println("Height=" +height);
47 | P a g e
}
Sphere (double r)
radius=r;
vol= (3.14*radius*radius*radius*4)/3;
return vol;
System.out.println("This Is Sphere");
System.out.println("Radius=" +radius );
class pd
48 | P a g e
public static void main(String args[])
s=new Sphere(4);
c.describe();
r.describe();
:-" +r.perimeter());
s.describe();
OutPut:-
49 | P a g e
Practical:-5
Inner Class:
Define two nested classes: Processor and RAM inside the outer
class: CPU with following
data members
class CPU { double price; class
Processor{ // nested class
double cores; double catch()
String manufacturer; double
getCache() void
displayProcesorDetail()
}
protected class RAM{ // nested protected class
// members of protected nested class double
memory;
String manufacturer;
Double clockSpeed;
double getClockSpeed() void
displayRAMDetail()
50 | P a g e
}
}
1.Write appropriate Constructor and create instance of Outer
and inner class and call the methods in main function
import java.util.Scanner; class
CPU
double price;
class Processor
{ // nested class
double cores;
String manufacturer;
Processor(double core,String S)
cores=core;
manufacturer=S;
double getCache()
{ double
d;
System.out
.println("E
nter the
51 | P a g e
cache you
want:");
d=ob.nextFloat();
return d;
void displayProcesorDetail()
System.out.println("/MANUFACTURER:"+manufacturer);
System.out.println("CORES:"+cores);
System.out.println("CACHE:"+getCache());
double memory;
String manufacturer;
manufacturer=m;
memory=memo;
52 | P a g e
}
double getClockSpeed()
{ double
clockSpeed;
clockSpeed=sc.nextDouble(); return
clockSpeed;
void displayRAMDetail()
System.out.println("MANUFACTURER :- "+manufacturer);
System.out.println("MEMORY :-"+memory);
System.out.println("CLOCKSPPED :-"+getClockSpeed());
class paa
53 | P a g e
b.displayProcesorDetail();
c.displayRAMDetail();
OutPut:-
class outer
54 | P a g e
static class inner
{ void
MESSAGE()
void displ()
class inner
void MESSAGE()
{ outer.inner obj=new
outer.inner();
obj.MESSAGE();
outer ob=new
outer(); ob.displ();
55 | P a g e
{
void displ()
System.out.println("Anonymous CLASS");
};
k.displ();
Output:-
56 | P a g e
Practical:-6
Generics
1. Declare a class InvoiceDetail which accepts a type parameter
which is of type
Number with following data members
class InvoiceDetail <N extends Number> {
private String invoiceName; private N
amount; private N Discount
// write getters, setters and constructors
}
Call the methods in Main class
class InvoiceDetail<N extends Number>
discount)
57 | P a g e
{
return invoiceName;
this.invoiceName = invoiceName;
public N getAmount()
return amount;
this.amount = amount;
public N getDiscount()
return discount;
}
58 | P a g e
{
this.discount = discount;
public N getTotalAmount()
class Main
59 | P a g e
Output:-
60 | P a g e
if (top == -1)
{
System.out.println("Stack Underflow");
return null;
}
else
return A.get(top);
}
void pop()
{
if (top == -1)
{
System.out.println("Stack Underflow");
}
else top--;
}
booleanempty()
{ return top == -1; }
public String toString()
{
String Ans = "";
for (int i = 0; i< top; i++)
{
Ans += String.valueOf(A.get(i)) + "->";
}
Ans += String.valueOf(A.get(top)); return Ans;
}
}
class main
{
public static void main(String[] args)
{
stack<Integer> s1 = new stack<>(5); s1.push(17);
s1.push(27);
s1.push(37);
s1.push(47);
s1.push(57);
System.out.println( "s1 after pushing 17, 27, 37, 47 and 57 :\n" + s1); s1.pop();
61 | P a g e
System.out.println("s1 after pop :\n" + s1);
stack<Float> s3 = new
stack<>(2); s3.push(570.0f);
s3.push(370.0f);
System.out.println("\ns3 after pushing 2 elements :\n" + s3);
System.out.println("top element of s3:\n"+ s3.top());
}
OUTPUT:
62 | P a g e
3. Write a program to sort the object of Book class using
comparable and comparator
interface. (Book class consist of book id, title, author and
publisher as data members)
import java.util.ArrayList; import
java.util.Collections; import
java.util.Comparator; import
java.util.List;
publisher;
this.publisher = publisher;
63 | P a g e
// Getters and setters
return id;
return title;
return author;
return publisher;
other.id);
64 | P a g e
@Override public
String toString() {
return "Book ID: " + id + ", Title: " + title + ", Author: " + author + ", Publisher: " +
publisher;
main(String[] args) {
System.out.println(book);
65 | P a g e
System.out.println("\nSorting using Comparator (by author):");
books) {
System.out.println(book);
}
}
Output:-
66 | P a g e
Practical:-7
Exception Handing
1. Write a program for creating a Bank class, which is used to
manage the bank
account of customers. Class has two methods, Deposit () and
withdraw (). Deposit
method display old balance and new balance after depositing
the specified amount.
Withdrew method display old balance and new balance after
withdrawing. If
balance is not enough to withdraw the money, it throws
ArithmeticException and
if balance is less than 500rs after withdrawing then it throw
custom exception,
NotEnoughMoneyException.
import java.util.Scanner; class
NotMoneyException extends Exception
{
public String toString()
{
return "Money is not Enough";
}
}
class Bank
{
int balance,acc; static int a=0; Bank(int b)
{
67 | P a g e
a++;
acc=a;
balance=b;
}
void deposit()
{
int b;
Scanner s=new Scanner(System.in);
System.out.println("Enter The Amount To Be Deposited:-
"); b=s.nextInt(); balance+=b;
}
balance-=b;
}
void display()
{
System.out.println("Balance is:- "+balance);
}
}
68 | P a g e
class demobank
{
public static void main (String args[])
{
Bank ob=new Bank(500);
System.out.println("Balance Of The Account Is Rs500.");
try
{
ob.deposit();
ob.withdraw();
ob.display();
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(NotMoneyException e)
{
System.out.println(e);
}
}
Output:-
69 | P a g e
2. Write a complete program for calculation average of n +ve
integer numbers of Array A.
a. Read the array form keyboard
b. Raise and handle Exception if
i. Element value is -ve or non-integer. ii.
If n is zero.
import java.util.Scanner; class InvalidElementException
extends Exception
class demosum
int n;
n=sc.nextInt();
int ar[]=new int[n];
70 | P a g e
System.out.println("Enter elements :");
try
for(int i=0;i<ar.length;i++)
ar[i]=sc.nextInt();
if(ar[i]<0 )
catch(InvalidElementException e)
System.out.println(e);
int s=0;
for(int i=0;i<ar.length;i++)
s+=ar[i];
71 | P a g e
int avg=s/ar.length;
System.out.println("avarage :"+avg);
Output:-
72 | P a g e
Practical:-8
Threading
1. Write a program to find prime number in given range using
both method of
multithreading. Also run the same program using executor
framework
import java.util.Scanner; class
int first,last;
this.first=first; this.last=last;
i = first;i<= last;i++){
if(isPrime(i)){
System.out.println(i);
try{
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
73 | P a g e
}
return true;
}
{ int
first,last;
System.out.println("Ending: ");
last = s.nextInt();
74 | P a g e
multiThread m = new multiThread();
m.setValues(first,last);
m.start();
Output:-
2. Assume one class Queue that defines queue of fix size says
15.
● Assume one class producer which implements Runnable,
having priority
NORM_PRIORITY +1
75 | P a g e
● One more class consumer implements Runnable, having
priority
NORM_PRIORITY-1
● Class TestThread is having main method with maximum
priority, which creates
1 thread for producer and 2 threads for consumer.
● Producer produces number of elements and put on the queue.
when queue becomes full it notifies other threads.
java.util.Scanner;
queue.add(arr[i]); count++;
76 | P a g e
System.out.println(queue);
if (queue.isEmpty()){
isEmpty = true;
if (count==15){
isFull = true;
arr[i] = random.nextInt(50);
System.out.println(arr[i]);
77 | P a g e
queue.gettingArray(arr);
consume();
queue.queue.poll();
System.out.println(queue.queue);
} } public class pr08_2 { public static void main(String[] args)
78 | P a g e
p.setPriority(Thread.NORM_PRIORITY+1); c1.setPriority(Thread.NORM_PRIORITY-
1); c2.setPriority(Thread.NORM_PRIORITY-1);
p.start();
p.join();
c1.start();
Output:-
79 | P a g e
Practical:-9
Collection API:
1. Write a program to demostrate user of ArrayList, LinkedList
,LinkedHashMap,
TreeMap and HashSet Class. And also implement CRUD
operation without database connection using
Collection API.
import java.util.*; public class oop {
//ARRAYLIST
System.out.println("ARRAYLIST:");
cars.add("VOLVO"); cars.add("MAYBACH");
cars.add("MERCEDES"); cars.add("AUDI");
Collections.sort(cars); for
(String i:cars) {
System.out.println(i);
//LINKED LIST
80 | P a g e
System.out.println("\nLINKEDLIST:");
a.addFirst(8);
a.addLast(4);
a.addFirst(3);
a.addFirst(9);
a.addLast(7);
a.removeFirst();
a.removeLast();
System.out.println("FIRST:"+a.getFirst());
System.out.println("LAST:"+a.getLast());
System.out.println("ALL:");
for(int i: a) {
System.out.println(i);
map.put(100,"Amit"); map.put(101,"Vijay");
map.put(102,"Rahul");
map.put(104,"Sohil");
map.remove(104);
81 | P a g e
System.out.println("After removing key-104 : "+map);
System.out.println("Keys: "+map.keySet());
System.out.println("Values: "+map.values());
//TREEMAP
System.out.println("\nTREE MAP:");
map1.put(100,"Amit"); map1.put(102,"Ravi");
map1.put(101,"Vijay"); map1.put(103,"Rahul");
System.out.println("descendingMap: "+map1.descendingMap());
//Returns key-value pairs whose keys are less than or equal to the specified key.
System.out.println("headMap: "+map1.headMap(102,true));
//Returns key-value pairs whose keys are greater than or equal to the specified key.
System.out.println("tailMap: "+map1.tailMap(102,true));
set.add("Ravi");
set.add("Vijay");
set.add("Ravi"); set.add("Ajay");
82 | P a g e
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}}
Output:-
83 | P a g e
2. Write a program to Sort Array,ArrayList,String,List,Map and
Set
import java.util.*;
System.out.println("ARRAY:");
Arrays.sort(arr);
//ARRAYLIST
System.out.println("\nARRAYLIST:");
nums.add(3); nums.add(1);
System.out.print(" "+i);
Collections.sort(nums);
84 | P a g e
System.out.println();
System.out.print(" "+i);
// //STRING
System.out.println("\nSTRING:");
Arrays.sort(names);
System.out.println();
//LIST
System.out.println("\nLIST:");
Integer[] numbers = new Integer[] { 15, 11, 9, 55, 47, 18, 1123, 520, 366, 420 };
Collections.sort(numbersList);
System.out.println(numbersList);
//
//HASHSET
System.out.println("\nHASHSET:");
85 | P a g e
Arrays.asList(15, 11, 9, 55, 47, 18, 1123, 520, 366, 420) );
Collections.sort(numbersList1); numbersSet =
new LinkedHashSet<>(numbersList1);
System.out.println(numbersSet);
//MAP
System.out.println("\nMAP:");
map.put(50, "jay");
map.put(20, "nirav");
map.put(60, "tipu");
map.put(70, "vishvam");
map.put(120, "nidhI");
map.put(10, "tipu");
86 | P a g e
Output:-
87 | P a g e
Practical:-10
File Handling Using Java:
1. Write a program to count occurrence of a given words in a file.
import java.io.*; public class pr10_1{ public static void
String line;
int count = 0;
br.close();
88 | P a g e
}
Output:-
throws IOException {
int i;
FileInputStream fin;
if(args.length != 1) {
return;
System.out.print((char) i);
} while(i != -1);
fin.close();
89 | P a g e
Output:-
// File object
System.out.println(
"**********************************************");
System.out.println(
System.out.println(
"**********************************************");
90 | P a g e
System.out.println(file.getName());
Output:-
91 | P a g e
Practical:-11
Networking
// Echo loop
String message;
while ((message = in.readLine()) != null) {
System.out.println("Received from client: " + message);
out.println("Server echo: " + message); // Send the echoed message back to the client
}
92 | P a g e
}
}
Echo Client
import java.io.*; import
java.net.*;
93 | P a g e
socket.close(); } catch
(IOException e) {
e.printStackTrace();
}
}
}
Output:-
2. Write a program using UDP which give name of the audio file
to server and server reply with content of audio file UDP
Server
import java.io.*; import
UDPServer { private
final int
MAX_PACKET_SIZE =
65507;
94 | P a g e
public static void main(String[] args) {
try {
while (true) {
FileInputStream(file);
fileInputStream.read(fileContent);
fileInputStream.close();
} else {
95 | P a g e
String errorMessage = "File not found!";
receivePacket.getAddress(), receivePacket.getPort());
socket.send(sendPacket);
} catch (IOException e) {
e.printStackTrace();
UDP Client
import java.io.*; import
java.net.*;
"localhost";
try {
96 | P a g e
DatagramSocket socket = new DatagramSocket();
filenameBytes = filename.getBytes();
socket.send(sendPacket);
inputStream.read(receiveBuffer)) != -1) {
97 | P a g e
System.out.write(receiveBuffer, 0, bytesRead);
inputStream.close();
userInput.close();
socket.close(); } catch
(IOException e) {
e.printStackTrace();
Output:-
98 | P a g e
Practical:-12
1. Write a programme to implement an investement value
calculator using the data
inputed by user. textFields to be included are amount, year,
interest rate and future
value. The field “future value” (shown in gray) must not be altered
by user.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public InvestmentCalculator()
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
99 | P a g e
JLabel amountLabel = new JLabel("Amount:");
panel.add(amountLabel);
panel.add(amountField);
panel.add(yearLabel);
panel.add(yearField);
panel.add(interestRateLabel);
panel.add(interestRateField);
panel.add(futureValueLabel);
panel.add(futureValueField);
calculateButton.addActionListener(new ActionListener()
100 | P a g e
public void actionPerformed(ActionEvent e)
calculateFutureValue();
});
add(panel, BorderLayout.CENTER);
add(calculateButton, BorderLayout.SOUTH);
setVisible(true);
try
futureValueField.setText(String.format("%.2f", futureValue));
101 | P a g e
} catch (NumberFormatException ex)
futureValueField.setText("Invalid Input");
SwingUtilities.invokeLater(new Runnable()
new InvestmentCalculator();
});
102 | P a g e
2. Write a program which fill the rectangle with the selected color
when button
pressed.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public ColorFillDemo() {
103 | P a g e
setTitle("I Am A JFrame");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
@Override
super.paintComponent(g);
g.setColor(currentColor);
};
redButton.addActionListener(this);
greenButton.addActionListener(this);
blueButton.addActionListener(this);
104 | P a g e
buttonPanel.add(redButton);
buttonPanel.add(greenButton);
buttonPanel.add(blueButton);
add(panel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
if (e.getSource() == redButton) {
currentColor = Color.RED;
currentColor = Color.GREEN;
currentColor = Color.BLUE;
panel.repaint();
SwingUtilities.invokeLater(new Runnable() {
105 | P a g e
public void run() {
new ColorFillDemo();
});
106 | P a g e