Java Lab Manul - Merged

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

A D PATEL INSTITIUTEOF TECHNOLOGY

(A Constituent Collage Of CVM University)

NEW VALLABH VIDYANAGAR

DEPARTMENT OF COMPUTER SCIENCE & DESIGN

Programming With Java

Submitted By
Jha Harshkumar Rajeshraman
12302130603006

JAVA (202040403)
A.Y.2023-2024
Certificate

This is to certify that Mr.Jha Harshkumar Rajeshraman


Of sem 4th Roll No. 12302130603006 has satisfactorily
completed her term work in Programming With Java
for the term ending in 2023/2024 . No. of practicals 12
out of 12 in the subject of Programming With Java.
Date:-

Sign Of faculty Head Of Department

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

3 Basic Program using Class 22


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 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. 3. Define a class with the
Name, Basic salary and dearness allowance as data
members.Calculate and print the Name, Basic
salary(yearly), dearness allowance and tax deduced at
source(TDS) and net salary, where TDS is charged on
gross salary which is basic salary + dearness allowance
and TDS rate is as per following table.
Gross Salary TDS
Rs. 100000 and below NIL
Above Rs. 100000 10% on excess over
100000
DA is 74% of Basic Salary for all. Use appropriate member
function.

4 1. class Cricket having data members name, age and 31


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. 2. Define a class Cripher with
following data Field: String plainText; int key Functions:
Cipher(String plaintext,int key) abstract String
Encryption( ) abstract String Decryption( ) Derived two
classes Substitution_Cipher and Caesar_Cipher override
Encyption() and Decyption() Method. in substitute cipher
every character of string is replace with another
character. For example. In this method you will
replace the letters using the following scheme.
Plain Text: a b c d e f g h i j k l m n o p q r s t u v w x y z
Cipher Text: q a z w s x e d c r f v t g b y h n u j m i k o l p
So if string consist of letter “gcet” then encrypted string
will be ”ezsj” and decrypt it to get original string
In ceaser cipher encrypt the string same as program 5 of
LAB 5.
3. Declare an interface called Property containing a
method computePrice to compute
and return the price. The interface is to be implemented
by following two classes i) Bungalow and ii) Flat.
Both the classes have following data members
- name
- constructionArea
The class Bungalow has an additional data member called
landArea. Define 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.
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;
public Cone (double radius, double height) public double
volume()

public void describe() } public class Rectangle implements


TwoDShape { private double width, height; public
Rectangle (double width, double height) public double
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

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.

Consumer consumes number of elements and notifies other


thread when queue become empty.

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

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.
Practical:-1
Basic Program
1. Study of class path and java runtime environment
➢ There are two ways of set a path variable
1. By ordinary method
2. By command prompt

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

JDK andpaste to the variable value -> click on

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;

public int add(int a,int b)


{
return a+b;
}
public int sub(int a,int b)
{
return a-b;
}
public int mul(int a,int b)
{
return a*b;
}
public int div(int a,int b)
{
return a/b;
}
}

class CalDemo
{
public static void main(String [] args)
{

int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);

Calculator ob =new Calculator();


int a=ob.add(x,y);

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:-

● Write To prints Fibonacci series.


class Fibonacci

public static void main(String []args)

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:

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.

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 search_data(int num)


{ int flag=0; for(int
i=0;i<n;++i)
{
if(data[i]==num)
{
flag=1;
System.out.println("Found element "+num+" at "+i+" index");
break;
}
}
if(flag==0)
{
System.out.println("Element not found");
}
}

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:-

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 float [][]
matrixMultiplication(Matrix second ) //multiply two matrices
and return
result
void displayMatrix(float [][]a) //display content of argument
array
void displayMatrix() //display content

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(int row, int col)


{
this.mat = new float[row][col];
}

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++)
{

for (int j = 0; j < a.length; j++)


{
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}

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;
}

float[][] matrixMultiplication(Matrix first, Matrix second)


{
float sum = 0;
float arr[][] = new float[3][3]; for (int i = 0; i < arr.length; i++)
14 | P a g e
{
for (int j = 0; j < arr.length; j++)
{
for (int k = 0; k < arr.length; k++)
{
sum += (first.mat[i][k] * second.mat[k][j]);
}
arr[i][j] = sum; sum = 0;
}
}
return arr;
}

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


{
float mat1[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
Matrix a = new Matrix();
Matrix b = new Matrix(3,3);
Matrix c = new Matrix(mat1);
Matrix d = new Matrix();
System.out.println("Enter matrix A: ");
a.readMatrix();
System.out.println("Enter matrix B: "); b.readMatrix();
System.out.println("Transpose of matrix C: ");
c.mat = c.transpose(); for (int i = 0; i <
c.mat.length; i++)
{
for (int j = 0; j < c.mat.length; j++)
{
System.out.print(c.mat[i][j]+ " ");
}
System.out.println();
}
System.out.println("Displaying matrix A: ");
a.displayMatrix(); System.out.println();
float max = b.maximum_of_array();
System.out.println("Maximum of array B: " + max);
System.out.println(); float avg =
b.average_of_array();

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);

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


{
for (int j = 0; j < 3; j++)
{
System.out.print(d.mat[i][j] + " ");
}
System.out.println();
}
}
}
OutPut:-

3. Write a program to demonstrate usage of different


methods of Wrapper class
public class wapper
16 | P a g e
{
public static void main (String [] args) throws Exception
{
System.out.println("Using valueOf() method to create an object of a Wrapper class from a
String passed into it.");
Integer a=Integer.valueOf("100");
System.out.println("a: "+ a);
System.out.println("Using parseDataType()method to convert a given String to
primitive type " ); String s ="22"; int b=Integer.parseInt(s);
System.out.println("b:"+b);
System.out.println("Using toString()method to convert a Wrapper class type object into a
String.");

Double d= 22.11;
String t=d.toString();
System.out.println("t:"+t);
}
}

OutPut:-

Write a program to demonstrate usage of String and


StringBuffer class
public class ayu

17 | P a g e
{

public static void main(String [] args)

System.out.println("Printing String a");

String a="Hello,String isimmutable";

System.out.println(a);

System.out.println("\nWhen changes are made in a String object,they do not get


updated in same string,and rather a new object is created with new changes");
System.out.print("\n New String object created with changes:");

System.out.println(a.replace('H','B'));

System.out.println("\nOlder String a still remains the same as before as Strings are


immutable in JAVA.Printing String a");

System.out.println(a);

System.out.println("\nCreating a StringBuffer which provides modification functionalities


");

StringBuffer sb=new StringBuffer("I am a StringBuffer");

System.out.print("\nString Buffer sb:"+ sb);

sb.append(",I ammutable");

System.out.println("\nsbafter updation: "+sb);

sb.reverse();

System.out.println("Reversing sb:" + sb);

18 | P a g e
OutPut:-

5. Define a class Cipher with following data


Field:
String plainText;
int key Functions:
Cipher(String plaintext,int key)
String Encryption( )
String Decryption( )
Read string and key from command prompt and replace every
character of string with character which is key place down
from current character. Example plainText = “GCET”
Key = 3
Encryption function written following String
“ JFHW”
Decryption function will convert encrypted string to original
form “GCET”

import java.util.Scanner; public

class Cipher

19 | P a g e
String plainText; int

key;

Cipher(String plainText, int key)

this.plainText = plainText;

this.key = key;

String Encryption()

String encrypted_str; char arr[] =

this.plainText.toCharArray();

for (int i = 0; i < this.plainText.length(); i++)

arr[i] = ((char)(arr[i]+3));

encrypted_str = String.valueOf(arr);

return encrypted_str;

20 | P a g e
String Decryption()

String decrypted_str;

char arr[] = this.plainText.toCharArray();

for (int i = 0; i < this.plainText.length(); i++)

arr[i] = ((char)(arr[i]-3));

decrypted_str = this.plainText.toString(); return

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 {

private String depositorName;

private int accNo; private

String accType; private double

balance;

private static int nextAccountNumber = 1;

// Member Function to create an account

public void createAcc() {

Scanner sc = new Scanner(System.in);

// Assign next serial number as the account number

accNo = nextAccountNumber++;

22 | P a g e
System.out.println("Enter Depositor Name: ");

depositorName = sc.nextLine();

System.out.println("Enter Account Type: ");

accType = sc.nextLine();

System.out.println("Enter Initial Balance: ");

balance = sc.nextDouble();

System.out.println("Account created successfully!");

// Member Function to deposit money

public void deposit() {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the amount to deposit: ");

double amount = sc.nextDouble(); if (amount > 0)

balance += amount;

System.out.println("Deposit successful. Updated Balance: " + balance);

} else

System.out.println("Invalid amount. Deposit failed.");

23 | P a g e
// Member Function to withdraw money

public void withdraw()

Scanner sc = new Scanner(System.in);

System.out.println("Enter the amount to withdraw: ");

double amount = sc.nextDouble(); if (amount > 0 &&

amount <= balance)

balance -= amount;

System.out.println("Withdrawal successful. Updated Balance: " + balance);

} else

System.out.println("Invalid amount or insufficient balance. Withdrawal failed.");

// Member Function to check balance

public void balanceInquiry()

System.out.println("Account Number: " + accNo);

System.out.println("Depositor Name: " + depositorName);

System.out.println("Account Type: " + accType);

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

24 | P a g e
}

public class BankAccountDemo { public static

void main(String[] args) { BankAccount

account = new BankAccount();

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 {

private int hour; private

int minute; private int

second; //

Parameterized

constructor to initialize

Time objects public

Time(int hour, int minute,

int second) {

this.hour = hour;

this.minute = minute;

this.second = second;

// Member function to sum two time objects

public static Time sum(Time time1, Time time2) {

int sumHour = time1.hour + time2.hour; int

26 | P a g e
sumMinute = time1.minute + time2.minute; int

sumSecond = time1.second + time2.second;

// Adjust seconds and minutes if they exceed 60

if (sumSecond >= 60) { sumSecond -= 60;

sumMinute++;

if (sumMinute >= 60) {

sumMinute -= 60; sumHour++;

// Adjust hours if they exceed 24

if (sumHour >= 24) {

sumHour -= 24;

return new Time(sumHour, sumMinute, sumSecond);

public static void main(String[] args) {

// Creating two Time objects

Time time1 = new Time(10, 30, 45);

Time time2 = new Time(4, 45, 20);

// Summing the two time objects

Time sumTime = Time.sum(time1, time2);

// Displaying the sum

27 | P a g e
System.out.println("Sum of time1 and time2: " + sumTime.hour + " hours, " +

sumTime.minute + " minutes, " + sumTime.second + " seconds.");

OutPut:-

3. Define a class with the Name, Basic salary and dearness


allowance as data
members.Calculate and print the Name, Basic salary(yearly),
dearness allowance
and tax deduced at source(TDS) and net salary, where TDS is
charged on gross
salary which is basic salary + dearness allowance and TDS rate
is as per following table.
Gross Salary TDS
Rs. 100000 and NIL
below
Above Rs. 100000 10% on excess
over 100000
DA is 74% of Basic Salary for all. Use appropriate member
function.
28 | P a g e
class Employee

private String name; private

int basicsalary; private static

double da =0.74; private

double tds=0.1; private

double netSalary; Employee

(String name,int basicsalary)

this.name= name; this.basicsalary=basicsalary;

public String toString()

return("name: "+name+"basicsalary:"+basicsalary+"netSalary: "+netSalary);

public void calculateNetSalary()

netSalary = basicsalary +(da*basicsalary);

if(netSalary > 100000) netSalary = netSalary -

((netSalary -100000)*tds);

class EmployeeDemo

29 | P a g e
public static void main (String [] args)

Employee e1 = new Employee("Abc",250000); e1.calculateNetSalary();

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;

int age; void

setdata()

System.out.println("Enter the name and age of cricket player ");

Scanner obj= new Scanner(System.in); name=obj.next();

age=obj.nextInt();

void display()

System.out.println("The name of the cricket player is " + name);

31 | P a g e
System.out.println("The age of the cricket player is " + age);

class match extends cricket

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 ");

Scanner obj= new Scanner(System.in); no_of_odi=obj.nextInt(); no_of_test=obj.nextInt();

void display()

super.display();

System.out.println("The odi matches played by " + name + " is " + no_of_odi);

System.out.println("The test matches played by " + name + " is " + no_of_test);

class pa

public static void main( String args[])

32 | P a g e
{

match ob[]=new match[5];

System.out.println("Enter the details of player"); for(int

i=0;i<5;i++)

ob[i]=new match(); ob[i].setdata();

System.out.println("The details are as follows"); for(int

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( )

abstract String Decryption( )


Derived two classes Substitution_Cipher and Caesar_Cipher
override
Encyption() and Decyption() Method. in substitute cipher every
character of
string is replace with another character. For example. In this
method you will replace the letters using the following
scheme.
Plain Text: a b c d e f g h i j k l m n o p q r s t u v w x y z
Cipher Text: q a z w s x e d c r f v t g b y h n u j m i k o l p
So if string consist of letter “gcet” then encrypted string will be
”ezsj” and decrypt it
to get original string
In ceaser cipher encrypt the string same as program 5 of LAB 5.
35 | P a g e
abstract class cipher

String plainText; int key;

cipher(String plaintext,int k)

plainText=plaintext; key=k;

abstract String Encryption(); abstract

String Decryption();

class Substitution_Cipher extends cipher

{ 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();

char test[]=new char[xy.length];

for(int i=0;i<xy.length;i++)

d=encode.indexOf(xy[i]);

ab=decode.charAt(d); test[i]=ab;

plainText=new String(test); return

plainText;

String Decryption()

char xy[]=plainText.toCharArray();

char test[]=new char[xy.length];

for(int i=0;i<xy.length;i++)

d=decode.indexOf(xy[i]); ab=encode.charAt(d); test[i]=ab;

plainText=new String(test); return

plainText;

class caesar_cipher extends cipher

37 | P a g e
{

caesar_cipher(String plain, int key)

super(plain,key);

String Encryption()

char xy[]=plainText.toCharArray(); for(int

i=0;i<xy.length;i++)

xy[i]=(char)(xy[i]+key);

plainText=new String(xy); return

plainText;

String Decryption()

char xy[]=plainText.toCharArray(); for(int

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

public static void main(String args[])

Substitution_Cipher ob=new Substitution_Cipher("adit",7);

caesar_cipher ob1=new caesar_cipher("adit",4);

System.out.println("SUBSTITUTION CIPHER :-");

ob.Encryption();

System.out.println("ENCODED STRING is :- "+ob.plainText); ob.Decryption();

System.out.println("DECODED STRING is :- "+ob.plainText);

System.out.println();

System.out.println("CAESAR CIPHER :-"); ob1.Encryption();

System.out.println("ENCODED STRING is :-"+ob1.plainText); ob1.Decryption();

System.out.println("DECODED STRING is :-"+ob1.plainText);

39 | P a g e
OutPut:-

Declare an interface called Property containing a method


computePrice to compute
and return the price. The interface is to be implemented by
following two classes i)
Bungalow and ii) Flat.
Both the classes have following data members
- name
- constructionArea
The class Bungalow has an additional data member called
landArea. Define

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

public int computerprice();

class bunglow implements property

{ int

cost=0;

String name= new String();

int lname,constructionarea;

bunglow (String s,int a,int b)

41 | P a g e
name=s;

constructionarea=a;

lname=b;

public int computerprice()

cost=cost+(500*constructionarea) + (200*lname) + (400*lname);

return cost;

class flat implements property

{ int

cost=0;

String name=new String();

int constructionarea;

flat(String s,int a)

name=s;

constructionarea=a;

public int computerprice()

cost+=(500*constructionarea) + 200000;

42 | P a g e
return cost;

class pc

public static void main(String args[])

property p=new bunglow("viren",400,200);

System.out.println("The total cost of bunglow:=" + p.computerprice() + "/-");

property q=new flat("flat 101",400);

System.out.println("The total cost of flat:=" + p.computerprice() + "/-");

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;

public Cone (double radius, double height)


public double volume() public void

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

public void describe();

interface TwoDShape extends GeometricShape

public double area();

interface ThreeDShape extends GeometricShape

public double volume();

45 | P a g e
class Cone implements ThreeDShape

double vol;

private double radius; private

double height; public Cone

(double r, double h)

radius=r;

height=h;

public double volume()

vol= (3.14*radius*radius*height)/3;

return vol;

public void describe()

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 are,peri; private double

width, height; public Rectangle

(double w, double h)

width=w; height=h;

public double area()

are=width*height; return

are;

public double perimeter()

peri=2*(width+height); return

peri;

public void describe()

System.out.println("This Is Rectangle");

System.out.println("Width=" +width);

System.out.println("Height=" +height);

47 | P a g e
}

class Sphere implements ThreeDShape

double vol; private

double radius; public

Sphere (double r)

radius=r;

public double volume()

vol= (3.14*radius*radius*radius*4)/3;

return vol;

public void describe()

System.out.println("This Is Sphere");

System.out.println("Radius=" +radius );

class pd

48 | P a g e
public static void main(String args[])

Cone c=new Cone(9,15);

Rectangle r=new Rectangle(6,5); Sphere

s=new Sphere(4);

c.describe();

System.out.println("Volume :- " +c.volume());

r.describe();

System.out.println("Area :- " +r.area()); System.out.println("Perimeter

:-" +r.perimeter());

s.describe();

System.out.println("Volume :- " +s.volume());

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:");

Scanner ob = new Scanner(System.in);

d=ob.nextFloat();

return d;

void displayProcesorDetail()

System.out.println("/MANUFACTURER:"+manufacturer);

System.out.println("CORES:"+cores);

System.out.println("CACHE:"+getCache());

protected class RAM

{ // nested protected class

// members of protected nested class

double memory;

String manufacturer;

RAM(String m,double memo)

manufacturer=m;

memory=memo;

52 | P a g e
}

double getClockSpeed()

{ double

clockSpeed;

System.out.println("Enter Clock SPEED:");

Scanner sc=new Scanner(System.in);

clockSpeed=sc.nextDouble(); return

clockSpeed;

void displayRAMDetail()

System.out.println("MANUFACTURER :- "+manufacturer);

System.out.println("MEMORY :-"+memory);

System.out.println("CLOCKSPPED :-"+getClockSpeed());

class paa

public static void main(String args[])

CPU a=new CPU();

CPU.Processor b=a.new Processor(8,"ACER");

53 | P a g e
b.displayProcesorDetail();

CPU.RAM c=a.new RAM("ACER",8);

c.displayRAMDetail();

OutPut:-

2. Write a program to demonstrate usage of static inner class,


local inner class and anonymous inner class
abstract class anony

abstract void displ();

class outer

static int data=20;

54 | P a g e
static class inner

{ void

MESSAGE()

System.out.println("STATIC CLASS"+"\n"+"Given Data is:- "+data);

void displ()

class inner

void MESSAGE()

System.out.println("Local inner class");

inner a=new inner(); a.MESSAGE();

public static void main(String args[])

{ outer.inner obj=new

outer.inner();

obj.MESSAGE();

outer ob=new

outer(); ob.displ();

anony k=new anony()

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>

private String invoiceName; private N amount; private N

discount; public InvoiceDetail(String invoiceName, N amount, N

discount)

this.invoiceName = invoiceName; this.amount

= amount; this.discount = discount;

public String getInvoiceName()

57 | P a g e
{

return invoiceName;

public void setInvoiceName(String invoiceName)

this.invoiceName = invoiceName;

public N getAmount()

return amount;

public void setAmount(N amount)

this.amount = amount;

public N getDiscount()

return discount;
}

public void setDiscount(N discount)

58 | P a g e
{

this.discount = discount;

public N getTotalAmount()

return (N) (Number) (amount.doubleValue() - discount.doubleValue());

class Main

public static void main(String[] args)

InvoiceDetail<Double> invoice = new InvoiceDetail<>("Invoice 001", 100.0, 10.0);

System.out.println("Invoice Name: " + invoice.getInvoiceName());

System.out.println("Amount: " + invoice.getAmount());

System.out.println("Discount: " + invoice.getDiscount());

System.out.println("Total Amount: " + invoice.getTotalAmount());

59 | P a g e
Output:-

2. Implement Generic Stack


import java.io.*; import
java.util.*; class stack<T>
{
ArrayList<T> A; int top = -1;
int size; stack(int size)
{
this.size = size;
this.A = new ArrayList<T>(size);
}
void push(T X)
{
if (top + 1 == size)
{
System.out.println("Stack Overflow");
}
else
{
top = top + 1; if (A.size() > top)
A.set(top, X); else
A.add(X);
}
}
T top()
{

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<String> s2 = new stack<>(3); s2.push("hello");


s2.push("world");
s2.push("java");
System.out.println("\ns2 after pushing 3 elements :\n" + s2);
System.out.println("s2 after pushing 4th element :");
s2.push("GFG");

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;

// Book class definition


class Book implements Comparable<Book> {

private int id; private

String title; private String

author; private String

publisher;

// Constructor public Book(int id, String title, String author,


String publisher) {

this.id = id; this.title =

title; this.author = author;

this.publisher = publisher;

63 | P a g e
// Getters and setters

public int getId() {

return id;

public String getTitle() {

return title;

public String getAuthor() {

return author;

public String getPublisher() {

return publisher;

// Implementing Comparable interface based on book id


@Override public int compareTo(Book

other) { return Integer.compare(this.id,

other.id);

// toString method to print book details

64 | P a g e
@Override public

String toString() {

return "Book ID: " + id + ", Title: " + title + ", Author: " + author + ", Publisher: " +
publisher;

public class Book1 { public static void

main(String[] args) {

// Creating a list of books

List<Book> books = new ArrayList<>(); books.add(new Book(3, "Java

Basics", "John Smith", "ABC Publications")); books.add(new Book(1, "Python

Programming", "Alice Johnson", "XYZ Press"));

books.add(new Book(2, "Data Structures and Algorithms", "Bob Williams", "DEF


Books"));

// Sorting using Comparable (by book id)

System.out.println("Sorting using Comparable (by book id):");

Collections.sort(books); for (Book book : books) {

System.out.println(book);

// Sorting using Comparator (by author)

Comparator<Book> authorComparator = Comparator.comparing(Book::getAuthor);

65 | P a g e
System.out.println("\nSorting using Comparator (by author):");

Collections.sort(books, authorComparator); for (Book book :

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;
}

void withdraw() throws NotMoneyException


{
int b;
Scanner s=new Scanner(System.in); System.out.println("Enter The Amount To Be
Withdrawn:- "); b=s.nextInt();
if(balance<500)
{
throw new NotMoneyException();
}
if(b>balance)
{
throw new ArithmeticException();

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

public String toString()

return "Element must be positive int";

class demosum

public static void main(String args[])

Scanner sc=new Scanner(System.in);

int n;

System.out.println("Enter Number of element :");

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 )

throw new InvalidElementException();

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

multiThread extends Thread{

int first,last;

public void setValues(int first,int last) {

this.first=first; this.last=last;

public void run(){ for (int

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
}

public boolean isPrime(int n){

if(n <= 1){


return false;

for(int i = 2; i <= Math.sqrt(n);i++){

if (n%i ==0) return false;

return true;
}

public class prime

public static void main(String[] args)

{ int

first,last;

Scanner s = new Scanner(System.in);

System.out.println("Enter the range of numbers for finding the prime numbers");

System.out.println("Starting: "); first = s.nextInt();

System.out.println("Ending: ");

last = s.nextInt();

74 | P a g e
multiThread m = new multiThread();

m.setValues(first,last);

System.out.println("The list of Prime numbers are as follows: ");

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.

Consumer consumes number of elements and notifies other


thread when queue become empty.
import java.util.PriorityQueue;

import java.util.Random; import

java.util.Scanner;

class queue{ producer p = new producer(); static PriorityQueue<Integer>

queue = new PriorityQueue<Integer>(15); static void gettingArray(int

...arr){ int count=0;

System.out.println("Adding Elements into Queue: ");

for (int i = 0; i < arr.length; i++) {

queue.add(arr[i]); count++;

76 | P a g e
System.out.println(queue);

if (queue.isEmpty()){

isEmpty = true;

if (count==15){

isFull = true;

static boolean isFull,isEmpty;

class producer implements Runnable{

public void run(){ produce();

public void produce() {

Random random = new Random();

Scanner s = new Scanner(System.in); System.out.println("Enter the numbers you want


to generate [MAX = 15]: ");

int isize = s.nextInt();

int[] arr = new int[isize];

System.out.println("Generating Random Numbers: ");

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

arr[i] = random.nextInt(50);

System.out.println(arr[i]);

77 | P a g e
queue.gettingArray(arr);

class consumer implements Runnable{


public void run(){

consume();

public void consume(){

System.out.println("Enter the number of elements you want to consume: ");

Scanner s = new Scanner(System.in);

int c = s.nextInt(); for

(int i = 0; i < c; i++) {

queue.queue.poll();

System.out.println("Queue after consuming elements: ");

System.out.println(queue.queue);
} } public class pr08_2 { public static void main(String[] args)

throws InterruptedException { producer pro = new producer();

consumer con1 = new consumer(); consumer con2 = new

consumer(); queue q = new queue();

Thread p = new Thread(pro);

Thread c1 = new Thread(con1);

Thread c2 = new Thread(con2);

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 {

public static void main(String[] args) {

//ARRAYLIST

System.out.println("ARRAYLIST:");

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

cars.add("VOLVO"); cars.add("MAYBACH");

cars.add("MERCEDES"); cars.add("AUDI");

cars.add("ROLLS ROYCE"); cars.remove("VOLVO");

System.out.println("Print the first element in the cars[]: "+cars.get(0));

Collections.sort(cars); for

(String i:cars) {

System.out.println(i);

//LINKED LIST

80 | P a g e
System.out.println("\nLINKEDLIST:");

LinkedList<Integer> a = new LinkedList<Integer>();

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);

//LINKED HASH MAP

System.out.println("\nLINKED HASH MAP:");

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

map.put(100,"Amit"); map.put(101,"Vijay");

map.put(102,"Rahul");

map.put(104,"Sohil");

System.out.println("Before removing key-104 : "+map);

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());

System.out.println("Key-Value pairs: "+map.entrySet());

//TREEMAP

System.out.println("\nTREE MAP:");

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

map1.put(100,"Amit"); map1.put(102,"Ravi");

map1.put(101,"Vijay"); map1.put(103,"Rahul");

//Maintains descending order

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));

//Returns key-value pairs exists in between the specified key. System.out.println("subMap:

"+map1.subMap(100, false, 102, true)); System.out.println("\nHASH SET:");

HashSet<String> set=new HashSet<String>();

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.*;

public class dsa{ public static <Int> void

main(String[] args) { //ARRAY

System.out.println("ARRAY:");

int [] arr = {8,7,9,6,5,2,1,0,4};

System.out.println("The Original array is "+Arrays.toString(arr));

Arrays.sort(arr);

System.out.print("The Sorted array is "+Arrays.toString(arr));

//ARRAYLIST

System.out.println("\nARRAYLIST:");

ArrayList<Integer> nums = new ArrayList<>(5);

nums.add(9); nums.add(0); nums.add(6);

nums.add(3); nums.add(1);

System.out.print("Before Sorting: ");

for (int i:nums ) {

System.out.print(" "+i);

Collections.sort(nums);

84 | P a g e
System.out.println();

System.out.print("After Sorting: ");

for (int i:nums ) {

System.out.print(" "+i);

// //STRING

System.out.println("\nSTRING:");

String[] names = {"Aakash","Jagdish","Varni","Hinal","Chandu","Sharda"};

System.out.print("Before Sorting: "+Arrays.toString(names));

Arrays.sort(names);

System.out.println();

System.out.print("After Sorting: "+Arrays.toString(names));

//LIST

System.out.println("\nLIST:");

Integer[] numbers = new Integer[] { 15, 11, 9, 55, 47, 18, 1123, 520, 366, 420 };

List<Integer> numbersList = Arrays.asList(numbers);

Collections.sort(numbersList);

System.out.println(numbersList);

//

//HASHSET

System.out.println("\nHASHSET:");

HashSet<Integer> numbersSet = new LinkedHashSet<>(

85 | P a g e
Arrays.asList(15, 11, 9, 55, 47, 18, 1123, 520, 366, 420) );

List<Integer> numbersList1 = new ArrayList<Integer>(numbersSet) ;

Collections.sort(numbersList1); numbersSet =

new LinkedHashSet<>(numbersList1);

System.out.println(numbersSet);

//MAP

System.out.println("\nMAP:");

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

map.put(50, "jay");

map.put(20, "nirav");

map.put(60, "tipu");

map.put(70, "vishvam");

map.put(120, "nidhI");

map.put(10, "tipu");

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

System.out.println("Data is sorted by Key "+treeMap);

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

main(String[] args) throws IOException {

String line;

int count = 0;

//Opens a file in read mode

FileReader file = new FileReader("text.txt");

BufferedReader br = new BufferedReader(file);

//Gets each line till end of file is reached

while((line = br.readLine()) != null) {

//Splits each line into words

String words[] = line.split(" ");

//Counts each word

count = count + words.length;

System.out.println("Number of words present in given file: " + count);

br.close();

88 | P a g e
}

Output:-

2. Write a program to print it seltf.


import java.io.*;

class pr10_2{ public static void main(String args[])

throws IOException {

int i;

FileInputStream fin;

if(args.length != 1) {

System.out.println("Usage: ShowFile filename");

return;

fin = new FileInputStream(args[0]);

do { i = fin.read(); if(i != -1)

System.out.print((char) i);

} while(i != -1);

fin.close();

89 | P a g e
Output:-

3. Write a program to display list of all the files of given


directory
import java.io.File; public class pr10_3 {

public static void main(String[] args) {

// Provide full path for directory(change accordingly)

String maindirpath = " C:\\Users\\DELL\\Desktop\\notepad";

// File object

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(

"**********************************************");

for (File file : arr) {

90 | P a g e
System.out.println(file.getName());

Output:-

91 | P a g e
Practical:-11
Networking

1. Implement Echo client/server program using TCP Echo


Server
import java.io.*; import
java.net.*;

public class EchoServer { public static


void main(String[] args) { try {
ServerSocket serverSocket = new ServerSocket(9090); // Create server socket on
port 9090
System.out.println("Server started. Waiting for client...");

Socket clientSocket = serverSocket.accept(); // Wait for a client connection


System.out.println("Client connected.");

// Setup input/output streams


BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

// 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
}

// Close streams and sockets


in.close(); out.close();
clientSocket.close();
serverSocket.close(); } catch
(IOException e) {
e.printStackTrace();
}

92 | P a g e
}
}

Echo Client
import java.io.*; import
java.net.*;

public class EchoClient { public static


void main(String[] args) { try {
Socket socket = new Socket("localhost", 9090); // Connect to server on
localhost:9090
System.out.println("Connected to server.");

// Setup input/output streams


BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

// Send messages to the


server String message;
while (true) {
System.out.print("Enter message (type 'exit' to quit): ");
message = userInput.readLine(); out.println(message);
// Send message to server

if ("exit".equalsIgnoreCase(message)) // Check if user wants to exit


break;

String response = in.readLine(); // Receive response from server


System.out.println("Server response: " + response);
}

// Close streams and


socket userInput.close();
in.close(); out.close();

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

java.net.*; public class

UDPServer { private

static final int PORT =

9090; private static

final int

MAX_PACKET_SIZE =

65507;

94 | P a g e
public static void main(String[] args) {

try {

DatagramSocket socket = new DatagramSocket(PORT);

byte[] receiveBuffer = new byte[MAX_PACKET_SIZE];

System.out.println("Server started. Waiting for client...");

while (true) {

DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,


receiveBuffer.length); socket.receive(receivePacket);

String filename = new String(receivePacket.getData(), 0, receivePacket.getLength());

// Read audio file and send its content

File file = new File(filename); if (file.exists()) {

byte[] fileContent = new byte[(int) file.length()];

FileInputStream fileInputStream = new

FileInputStream(file);

fileInputStream.read(fileContent);

fileInputStream.close();

DatagramPacket sendPacket = new DatagramPacket(fileContent,


fileContent.length, receivePacket.getAddress(),
receivePacket.getPort()); socket.send(sendPacket);

System.out.println("File content sent to client.");

} else {
95 | P a g e
String errorMessage = "File not found!";

DatagramPacket sendPacket = new DatagramPacket(errorMessage.getBytes(),


errorMessage.getBytes().length,

receivePacket.getAddress(), receivePacket.getPort());

socket.send(sendPacket);

System.out.println("File not found, error message sent to client.");

} catch (IOException e) {

e.printStackTrace();

UDP Client
import java.io.*; import

java.net.*;

public class UDPClient { private static final int PORT

= 9090; private static final String SERVER_IP =

"localhost";

public static void main(String[] args) {

try {

96 | P a g e
DatagramSocket socket = new DatagramSocket();

BufferedReader userInput = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter the name of the audio file: ");

String filename = userInput.readLine();

// Send filename to server byte[]

filenameBytes = filename.getBytes();

DatagramPacket sendPacket = new DatagramPacket(filenameBytes,


filenameBytes.length, InetAddress.getByName(SERVER_IP), PORT);

socket.send(sendPacket);

// Receive audio file content from server byte[]

receiveBuffer = new byte[65507]; // Max packet size

DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,


receiveBuffer.length); socket.receive(receivePacket);

// Display received content

System.out.println("Received file content from server:");

ByteArrayInputStream inputStream = new


ByteArrayInputStream(receivePacket.getData());

int bytesRead; while ((bytesRead =

inputStream.read(receiveBuffer)) != -1) {
97 | P a g e
System.out.write(receiveBuffer, 0, bytesRead);

// Close streams and socket

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 class InvestmentCalculator extends JFrame {

private JTextField amountField, yearField, interestRateField, futureValueField;

public InvestmentCalculator()

setTitle("Investment Value Calculator");

setSize(300, 200);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLocationRelativeTo(null);

JPanel panel = new JPanel();

panel.setLayout(new GridLayout(4, 2, 10, 10));

99 | P a g e
JLabel amountLabel = new JLabel("Amount:");

amountField = new JTextField();

JLabel yearLabel = new JLabel("Year:");

yearField = new JTextField();

JLabel interestRateLabel = new JLabel("Interest Rate (%):");

interestRateField = new JTextField();

JLabel futureValueLabel = new JLabel("Future Value:");

futureValueField = new JTextField();

futureValueField.setEditable(false); // Making future value field read-only

panel.add(amountLabel);

panel.add(amountField);

panel.add(yearLabel);

panel.add(yearField);

panel.add(interestRateLabel);

panel.add(interestRateField);

panel.add(futureValueLabel);

panel.add(futureValueField);

JButton calculateButton = new JButton("Calculate");

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);

private void calculateFutureValue()

try

double amount = Double.parseDouble(amountField.getText());

int years = Integer.parseInt(yearField.getText());

double interestRate = Double.parseDouble(interestRateField.getText()) / 100;

double futureValue = amount * Math.pow((1 + interestRate), years);

futureValueField.setText(String.format("%.2f", futureValue));

101 | P a g e
} catch (NumberFormatException ex)

futureValueField.setText("Invalid Input");

public static void main(String[] args)

SwingUtilities.invokeLater(new Runnable()

public void run()

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 class ColorFillDemo extends JFrame implements ActionListener {

private JPanel panel;

private JButton redButton, greenButton, blueButton;

private Color currentColor = Color.WHITE;

public ColorFillDemo() {

103 | P a g e
setTitle("I Am A JFrame");

setSize(300, 200);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLocationRelativeTo(null);

panel = new JPanel() {

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

g.setColor(currentColor);

g.fillRect(50, 50, 200, 100);

};

redButton = new JButton("Red");

greenButton = new JButton("Green");

blueButton = new JButton("Blue");

redButton.addActionListener(this);

greenButton.addActionListener(this);

blueButton.addActionListener(this);

JPanel buttonPanel = new JPanel();

104 | P a g e
buttonPanel.add(redButton);

buttonPanel.add(greenButton);

buttonPanel.add(blueButton);

add(panel, BorderLayout.CENTER);

add(buttonPanel, BorderLayout.SOUTH);

setVisible(true);

public void actionPerformed(ActionEvent e) {

if (e.getSource() == redButton) {

currentColor = Color.RED;

} else if (e.getSource() == greenButton) {

currentColor = Color.GREEN;

} else if (e.getSource() == blueButton) {

currentColor = Color.BLUE;

panel.repaint();

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

105 | P a g e
public void run() {

new ColorFillDemo();

});

106 | P a g e

You might also like