0% found this document useful (0 votes)
16 views86 pages

JAVA Programming Lab Experiments

The document outlines a comprehensive programming curriculum for a Java course at A. D. Patel Institute of Technology, detailing various programming experiments and assignments. It includes topics such as basic Java programs, array manipulation, class definitions, inheritance, interfaces, exception handling, threading, and GUI applications. Each section specifies the requirements for different programming tasks, along with example code snippets and expected functionalities.

Uploaded by

nileshpatel2516
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views86 pages

JAVA Programming Lab Experiments

The document outlines a comprehensive programming curriculum for a Java course at A. D. Patel Institute of Technology, detailing various programming experiments and assignments. It includes topics such as basic Java programs, array manipulation, class definitions, inheritance, interfaces, exception handling, threading, and GUI applications. Each section specifies the requirements for different programming tasks, along with example code snippets and expected functionalities.

Uploaded by

nileshpatel2516
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

A. D.

PATEL INSTITIUTE Of TECHNOLOGY

NEW VALLABH VIDYANAGAR

COMPUTER SCIENCE AND DESIGN

Name: Rohan Visavadiya

Enroll No.: 12302130601059


Subject: Programming with JAVA
Course Code: 202044502
ROHAN VISAVADIYA

CSD 12302130601059
____________

C-13

SEM -4 24 25

PROGRAMMING WITH JAVA


~INDEX~
A D PATEL
INSTITUTE OF A.Y. 2024-25, SEMESTER 4
TECHNOLOGY SUBJECT CODE: 202044502
SUBJECT NAME: Programming with JAVA
DEPARTMENT OF COMPUTER
SCIENCE & DESIGN

Name: Rohan Visavadiya Enrolment No: 12302130601059

Sr. Page
No Name of the Experiment Date No. Marks Signature

Basic Program
1. Study of class path and java runtime environment
01 2. Write a program to
Implement command line calculator
Write To prints Fibonacci series.
Array:
1. Define a class Array with following member
02 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 float
[][] matrixMultiplication(Matrix second )
//multiply two matrices and return result void
displayMatrix(float [][]a) //display content of
argument array void displayMatrix() //display
content 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
3. Write a program to demonstrate usage of
different methods of Wrapper class
4. Write a program to demonstrate usage of
String and StringBuffer class
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”

Basic Program using Class


1. Create a class BankAccount that has Depositor
03 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 [Link]
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.
04 Inheritance and interface
1. class Cricket having data
membername, 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.
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
qrstuvwxyz
Cipher Text: q a z w s x e d c r f v t g b
yhnujmikolp
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 [Link]
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.
Define following classes and
4. 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

05 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() }
}
1. Write appropriate Constructor and create
instance of Outer and inner class and call the
methods in main function
2. Write a program to demonstrate usage of static
inner class, local inner class and anonymous inner
class
Generics
06 1. Declare a class InvoiceDetail which accepts a type
parameter which is of type Number with following
data members
class InvoiceDetail {
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)

07 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.
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.

08 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
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.
09 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.
2. Write a program to Sort
Array,ArrayList,String,List,Map and Set
File Handling Using Java:
10
1. Write a programme to count occurrence of a
given words in a file.
2. Write a program to print it seltf.
3. Write a program to display list of all the files of
given directory
Networking :
11 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 GUI
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.

2. Write a program which fill the


rectangle with the selected color when
button pressed.
13 Assignment - 1
14 Assignment - 2
Programming with Java
(202044502)

Practical -1
Basic Program

1. Study of class path and java runtime environment

public class A1 {
public static void main(String[] args) {
for(int i=0;i<10;i++){
[Link]("Rohannnnn");
}
}
}

Rohannnnn
Rohannnnn
Rohannnnn
Rohannnnn
Rohannnnn
Rohannnnn
Rohannnnn
Rohannnnn
Rohannnnn
Rohannnnn

2. Write a program to
● Implement command line calculator
import [Link];

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

Scanner sc = new Scanner([Link]);


double result = cal(sc);
[Link]("Result: " + result);
[Link]();

public static double cal(Scanner sc) {

Page | 0
Programming with Java
(202044502)

int a, b;

[Link]("Enter the Operator (+, -, *, /):");


String operator = [Link]();
[Link]("A =");
a = [Link]();
[Link]("B =");
b = [Link]();

switch (operator) {
case "+":

return a + b;

case "-":
return a - b;

case "*":
return a * b;

case "/":
if (b != 0) {

return (double) a / b;
} else {
[Link]("Error: Division by zero");
break;

default:
[Link]("Syntax Error");

Page | 1
Programming with Java
(202044502)

break;
}
return 0;

}
}

● Write To prints Fibonacci series.


public class A3 {

public static void main(String[] args) {


int n = 10;
[Link]("Fibonacci series up to " + n + ":");
for(int i=0;i<=n;i++){

[Link](Fibonacci(i)+" ");
}
}
public static int Fibonacci(int n){

if(n==0||n==1){
return n;
} int fib1=Fibonacci(n-
1); int fib2=Fibonacci(n-
2); int fib=fib1+fib2;

Page | 2
Programming with Java
(202044502)

return fib;
}
}

Page | 3
Programming with Java
(202044502)

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.
import [Link].*;
public class Array {

public int[] data;


public Array() {

[Link] = new int[10];


}
public Array(int size) {

[Link] = new int[size];


}
public Array(int[] data) {

Page | 4
Programming with Java
(202044502)

[Link] = [Link](data, [Link]);


}
public void reverseArray() {

int left = 0;
int right = [Link] - 1;
while (left < right) {

int temp = data[left];


data[left] = data[right];
data[right] = temp;
left++;
right--;

}}
public int maximumArray() {
int max = data[0];
for (int i = 1; i < [Link]; i++) {

if (data[i] > max) {


max = data[i];
}}
return max;
}
public int averageOfArray() {

int sum = 0;
for (int value : data) {

sum += value;
}
return sum / [Link];

}
public void sorting() {

[Link](data);

Page | 5
Programming with Java
(202044502)

}
public void display() {

[Link]([Link](data));
}
public int search(int no) {

for (int i = 0; i < [Link]; i++) {


if (data[i] == no) {
return i;
}}
return -1;
}
public int size() {

return [Link];
}
public static void main(String[] args) {

Array array1 = new Array(); Array array2 = new


Array(5); Array array3 = new Array(new int[] { 4, 2,
7, 1, 9 }); [Link]("Original Arrays:");
[Link](); [Link](); [Link]();
[Link]();

[Link]();
int max = [Link]();
int avg = [Link]();
int searchIndex = [Link](7);
[Link]("\nModified Arrays:");
[Link]();

Page | 6
Programming with Java
(202044502)

[Link](); [Link]();
[Link]("\nResults:");
[Link]("Maximum of array3: " + max);
[Link]("Average of array3: " + avg);
[Link]("Index of 7 in array3: " + searchIndex);

}}

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

Page | 7
Programming with Java
(202044502)

result
void displayMatrix(float [][]a) //display content of argument array
void displayMatrix() //display content
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 [Link];
public class Matrix {

private int row, column;


private float[][] mat;
public Matrix(int a[][]) {
[Link] = [Link];
[Link] = a[0].length;
[Link] = new float[row][column];
for (int i = 0; i < row; i++) {

for (int j = 0; j < column; j++) {


[Link][i][j] = a[i][j];
}}}
public Matrix() {
[Link] = 0;
[Link] = 0;
[Link] = null;

}
public Matrix(int row, int column) {

[Link] = row;
[Link] = column;
[Link] = new float[row][column];

Page | 8
Programming with Java
(202044502)

public void readMatrix() {


Scanner sc = new Scanner([Link]);
[Link]("Enter the element of Matrix:");
for (int i = 0; i < row; i++) {

for (int j = 0; j < column; j++) {


[Link][i][j] = [Link]();
}
}
}

public float[][] transpose() {


float[][] transpose = new float[column][row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {

transpose[j][i] = [Link][i][j];
}
}
return transpose;

public float[][] matrixMultiplication(Matrix second) {


if ([Link] != [Link]) {

[Link]("MAtrix cna not be multiplied!!");


return null;

}
float[][] result = new float[[Link]][[Link]];
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < [Link]; j++) {
for (int k = 0; k < [Link]; k++) {

Page | 9
Programming with Java
(202044502)

result[i][j] += [Link][i][k] * [Link][k][j];


}
}
}
return result;

public void displayMatrix(float[][] a) {


for (int i = 0; i < [Link]; i++) {

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


[Link](a[i][j] + " ");

}
[Link]();
}

public void displayMatrix() {


for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {

[Link]([Link][i][j] + " ");


}
[Link]();
}
}

public float maximumOfArray() {


float max = [Link][0][0];
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {

Page | 10
Programming with Java
(202044502)

if ([Link][i][j] > max) {


max = [Link][i][j];

}
}
}
return max;

public float averageOfArray() {


float sum = 0;
for (int i = 0; i < row; i++) {

for (int j = 0; j < column; j++) {

sum += [Link][i][j];
}

}
return sum / (row * column);
}

public static void main(String[] args) {


int[][] arr1 = { { 1, 2, 3 }, { 4, 5, 6 } };
int[][] arr2 = { { 2, 1 }, { 3, 4 }, { 5, 6 } };

Matrix matrix1 = new Matrix(arr1);


Matrix matrix2 = new Matrix();
[Link]();
Matrix matrix3 = new Matrix(3, 2);

[Link]("Matrix 1:");
[Link]();

Page | 11
Programming with Java
(202044502)

[Link]("Matrix 2:");
[Link]();
[Link]("Matrix 3:");
[Link]();

[Link]("Transpose of Matrix 1:");


[Link]([Link]());

[Link]("Multiplication of Matrix 1 and Matrix 2:");


float[][] product = [Link](matrix2);
if (product != null) {

[Link](product);

[Link]("Maximum of Matrix 1: " + [Link]());


[Link]("Average of Matrix 1: " + [Link]());
}

Page | 12
Programming with Java
(202044502)

3. Write a program to demonstrate usage of different methods of Wrapper class


public class WrapperDemo {

public static void main(String[] args) {


Integer num1=10;
Integer num2=20;

[Link]("num1:"+num1);
[Link]("num2:"+num2);

int sum=[Link]()+[Link]();
[Link]("Sum: "+sum);

int compareResult = [Link](num2);


[Link]("Compare result (num1 vs num2): " + compareResult);

boolean isEqual = [Link](num2);


[Link]("Are num1 and num2 equal? " + isEqual);

String strNum = "25";


Integer parsedNum = [Link](strNum);
[Link]("Parsed Integer: " + parsedNum);

String strFromInteger = [Link]();


[Link]("String representation of num1: " + strFromInteger);

int maxValue = [Link](num1, num2);


[Link]("Maximum value between num1 and num2: " + maxValue);

int minValue = [Link](num1, num2);

Page | 13
Programming with Java
(202044502)

[Link]("Minimum value between num1 and num2: " + minValue);

int absValue = [Link](-5, 10);


[Link]("Absolute sum of -5 and 10: " + absValue);

Integer valueOfExample = [Link](30);


[Link]("Value of example: " + valueOfExample);

4. Write a program to demonstrate usage of String and StringBuffer class


public class StringDemo {

public static void main(String[] args) {


String str1 = "Hello";
String str2 = "World";

String result1 = str1 + " " + str2;


[Link]("Concatenated String: " + result1);

int length1 = [Link]();


[Link]("Length of str1: " + length1);

Page | 14
Programming with Java
(202044502)

char charAtIndex = [Link](0);


[Link]("Character at index 0 in str2: " + charAtIndex);

String substring1 = [Link](6);


[Link]("Substring from index 6: " + substring1);

boolean isEqual = [Link]("Hello");


[Link]("Is str1 equal to 'Hello'? " + isEqual);

StringBuffer buffer = new StringBuffer("Java");

[Link](" is").append(" awesome");


[Link]("Appended String: " + [Link]());

[Link](4, "not ");


[Link]("Inserted String: " + [Link]());

[Link]();
[Link]("Reversed String: " + [Link]());

Page | 15
Programming with Java
(202044502)

Practical-3
Basic Program using Class 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 [Link].*;

public class BankAccount {


private String depositorName;
private int accountNumber;
private String accountType;
private double balance;

private static int nextAccountNumber = 1;

public BankAccount() {
[Link] = nextAccountNumber++;

public void createAcc() {


Scanner scanner = new Scanner([Link]);
[Link]("Enter depositer name:");
[Link] = [Link]();
[Link]("Enter account type:");
[Link] = [Link]();
[Link]("Enter initial balance: ");

Page | 16
Programming with Java
(202044502)

[Link] = [Link]();
[Link]("Account created successfully!");

public void deposit(double amount) {


[Link] += amount;
[Link](amount + "Deposited Successfully.");
}

public void withdraw(double amount) {


if (amount <= [Link]) {
[Link] -= amount;
[Link](amount + "Withdrawn successfully.");

} else {

[Link]("Insufficient balance.");
}
}

public void balanceInquiry() {


[Link]("Current balance: " + [Link]);
}

public static void main(String[] args) {


BankAccount account1 = new BankAccount();
[Link]();
[Link](1000);
[Link]();
[Link](500);
[Link]();

Page | 17
Programming with Java
(202044502)

}}

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;

public Time(int hour, int minute, int second) {


[Link] = hour;
[Link] = minute;
[Link] = second;
}

public static Time sum(Time t1, Time t2) {


int totalSeconds = [Link] + [Link];
int carryMinutes = totalSeconds / 60;
int remainingSeconds = totalSeconds % 60;

int totalMinutes = [Link] + [Link] + carryMinutes;

Page | 18
Programming with Java
(202044502)

int carryHours = totalMinutes / 60;


int remainingMinutes = totalMinutes % 60;

int totalHours = [Link] + [Link] + carryHours;

return new Time(totalHours, remainingMinutes, remainingSeconds);


}

public void displayTime() {


[Link]("%02d:%02d:%02d\n", hour, minute, second);
}

public static void main(String[] args) {


Time time1 = new Time(10, 30, 45);
Time time2 = new Time(2, 15, 20);
Time sumTime = [Link](time1, time2);
[Link]("Time 1:");
[Link]();
[Link]("Time 2:");
[Link]();
[Link]("Sum of Time 1 and Time 2:");
[Link]();

}}

Page | 19
Programming with Java
(202044502)

3. Define a class with the Name, Basic salary and dearness allowance as data
[Link] 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.

public class Employee {


private String name;
private double basicSalary;
private double dearnessAllowance;
public Employee(String name, double basicSalary) {

[Link] = name;
[Link] = basicSalary;
[Link] = 0.74 * basicSalary;

}
private double calculateGrossSalary() {

return basicSalary + dearnessAllowance;


}
private double calculateTDS() {

double grossSalary = calculateGrossSalary();


if (grossSalary <= 100000) {

return 0;
} else {
return 0.1 * (grossSalary - 100000);

Page | 20
Programming with Java
(202044502)

}
}
private double calculateNetSalary() {

return calculateGrossSalary() - calculateTDS();


}
public void displaySalaryDetails() {

[Link]("Name: " + name);


[Link]("Basic Salary (Yearly): " + basicSalary);
[Link]("Dearness Allowance: " + dearnessAllowance);
double grossSalary = calculateGrossSalary();
[Link]("Gross Salary: " + grossSalary);
double tds = calculateTDS();
[Link]("Tax Deducted at Source (TDS): " + tds);
[Link]("Net Salary: " + calculateNetSalary());

}
public static void main(String[] args) {

Employee employee = new Employee("John", 80000);


[Link]();

}
}

Page | 21
Programming with Java
(202044502)

Practical-4
Inheritance and interface
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 [Link].*;

class Cricket {
String name;
int age;

void display(){
[Link]("Name: "+name);
[Link]("Age: "+age);

void setData(String name,int age){


[Link]=name;
[Link]=age;

}
}
class Match extends Cricket{
int no_of_odi;
int no_of_test;

void displayMatchInto(){
display();
[Link]("Number of ODIs: "+no_of_odi);
Page | 22
Programming with Java
(202044502)

[Link]("Number of Tests: " + no_of_test);


}
}
public class Main {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

Match[] matches = new Match[5];

for (int i = 0; i < [Link]; i++) {


Match match = new Match();

[Link]("Enter name for player " + (i + 1) + ":");


String name = [Link]();

[Link]("Enter age for player " + (i + 1) + ":");


int age = [Link]([Link]());

[Link]("Enter number of ODIs for player " + (i + 1) + ":");


int noOfODI = [Link]([Link]());

[Link]("Enter number of Tests for player " + (i + 1) + ":");


int noOfTest = [Link]([Link]());

[Link](name, age);
match.no_of_odi = noOfODI;
match.no_of_test = noOfTest;
matches[i] = match;

Page | 23
Programming with Java
(202044502)

[Link]("Player Information:");
for (int i = 0; i < [Link]; i++) {

[Link]("Player " + (i + 1) + ":");


matches[i].displayMatchInto();
[Link]();

}}}

Page | 24
Programming with Java
(202044502)

2. 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 [Link]
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 {

double computePrice();
}

class Bungalow implements Property {


String name;
double constructionArea;
double landArea;

Bungalow(String name, double constructionArea, double landArea) {


[Link] = name;
[Link] = constructionArea;
[Link] = landArea;

Page | 25
Programming with Java
(202044502)

@Override
public double computePrice() {

double constructionCost = 500 * constructionArea;


double landCost = 400 * landArea;
double totalCost = constructionCost + landCost;
return totalCost;

}
}

class Flat implements Property {


String name;
double constructionArea;

Flat(String name, double constructionArea) {


[Link] = name;
[Link] = constructionArea;

@Override
public double computePrice() {

double constructionCost = 500 * constructionArea;


double additionalCost = 200000;
double totalCost = constructionCost + additionalCost;
return totalCost;

}
}

Page | 26
Programming with Java
(202044502)

public class Main1 {


public static void main(String[] args) {
Bungalow bungalow = new Bungalow("Bungalow A", 1500, 2000);
[Link]("Total price for Bungalow: Rs. " + [Link]());

Flat flat = new Flat("Flat X", 1000);


[Link]("Total price for Flat: Rs. " + [Link]());

}
}

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

Page | 27
Programming with Java
(202044502)

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
Program:
[Link]
public class Cone implements ThreeDShape {

private double radius; private double


height; public Cone(double radius, double
height) {

[Link] = radius;
[Link] = height;

}
@Override
public double volume() {

return ([Link] * radius * radius * height) / 3;


}

Page | 28
Programming with Java
(202044502)

@Override
public void describe() {
[Link]("This is a cone.");
}
}
[Link]
public interface GeometricShape {

void describe();
}
[Link]
public class Rectangle implements TwoDShape {

private double width, height;


public Rectangle(double width, double height) {

[Link] = width;
[Link] = height;

}
@Override
public double area() {

return width * height;


}
public double perimeter() {

return 2 * (width + height);


}
@Override
public void describe() {

[Link]("This is a rectangle.");
}
}

Page | 29
Programming with Java
(202044502)

[Link]
public class Sphere implements ThreeDShape {

private double radius;


public Sphere(double radius) {

[Link] = radius;
}
@Override
public double volume() {

return (4.0 / 3.0) * [Link] * [Link](radius, 3);


}
@Override
public void describe() {

[Link]("This is a sphere.");
}
}
[Link]
import [Link].*;
public class TestGeometricShapes {

public static void main(String[] args) {


GeometricShape[] shapes = new GeometricShape[3];
shapes[0] = new Cone(3, 4);
shapes[1] = new Rectangle(5, 6);
shapes[2] = new Sphere(7);

for (GeometricShape shape : shapes) {


[Link]();
if (shape instanceof TwoDShape) {
[Link]("Area: " + ((TwoDShape) shape).area());
if (shape instanceof Rectangle) {

Page | 30
Programming with Java
(202044502)

[Link]("Perimeter: " + ((Rectangle) shape).perimeter());


}
} else if (shape instanceof ThreeDShape) {
[Link]("Volume: " + ((ThreeDShape) shape).volume());
}
[Link]();

}
}
}
[Link]
public interface ThreeDShape extends GeometricShape {

double volume();
}
[Link]
public interface TwoDShape extends GeometricShape {

double area();

Page | 31
Programming with Java
(202044502)

Practical-5
Inner Class and packages:
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

class CPU {
double price;
class Processor{
Page | 32
Programming with Java
(202044502)

double cores;
String manufacturer;

Processor(double cores,String manufacturer){


[Link]=cores;
[Link]=manufacturer;

}
double getCach(){
return 0.0;

}
void displayProcessorDetail(){

[Link]("Processor Cores: "+ cores);


[Link]("Processor Manufacturer"+manufacturer);
}

protected class RAM{


double memory;
String manufacturer;
Double clockSpeed;

RAM(double memory,String manufacturer,Double clockSpeed){


[Link]=memory;
[Link]=manufacturer;
[Link]=clockSpeed;

}
double getClockSpeed(){

return 0.0;
}

Page | 33
Programming with Java
(202044502)

void displayRAMDetail(){
[Link]("RAM Memory: "+ memory);
[Link]("RAM Manufacturer: "+ manufacturer);
[Link]("RAM Clock Speed: "+ clockSpeed);

}
}
}
public class Main1{

public static void main(String[] args){


CPU cpu=new CPU();
[Link]=500.0;

[Link] processor=[Link] Processor(8,"Intel");


[Link]();

[Link] ram = [Link] RAM(16,"Corsair",2400.0);


[Link]();

}
}

Page | 34
Programming with Java
(202044502)

Packages:
1) Implement a program that defines package figures, which has a class
circle inherited from a class shape in it. Include the methods in the class
to calculate area and display the necessary information. Also include a
class, which has main to carry out above-mentioned operations.
2) Create a package new_figures, which has classesrectangle and triangle
inherited from class shape of package figures. Thus import the package
[Link] out necessary operations tocalculate area and display the
necessary information.
3) Modify the above programs by importing both the packages in a file outside
both the packages, which contains main class.

Figures/[Link]

class CPU {

double price;
class Processor{

double cores;
String manufacturer;

Processor(double cores,String manufacturer){

[Link]=cores;
[Link]=manufacturer;

}
double getCach(){

return 0.0;
}

void displayProcessorDetail(){

[Link]("Processor Cores: "+ cores);

[Link]("Processor Manufacturer"+manufacturer);

Page | 35
Programming with Java
(202044502)

protected class RAM{

double memory;
String manufacturer;

Double clockSpeed;

RAM(double memory,String manufacturer,Double clockSpeed){

[Link]=memory;
[Link]=manufacturer;

[Link]=clockSpeed;

double getClockSpeed(){

return 0.0;

}
void displayRAMDetail(){

[Link]("RAM Memory: "+ memory);


[Link]("RAM Manufacturer: "+ manufacturer);

[Link]("RAM Clock Speed: "+ clockSpeed);

}
}

public class Main1{

public static void main(String[] args){

CPU cpu=new CPU();


[Link]=500.0;

[Link] processor=[Link] Processor(8,"Intel");

[Link]();

Page | 36
Programming with Java
(202044502)

[Link] ram = [Link] RAM(16,"Corsair",2400.0);

[Link]();

}
Figures/[Link]

package figures;

public class Shape {

// Base class for shapes


}

New_figures/[Link]
package New_figures;

import [Link];

public class Rectangle extends Shape {

private double width, height;

public Rectangle(double width, double height) {

[Link] = width;
[Link] = height;

public double area() {

return width * height;


}

public void displayInfo() {

[Link]("Rectangle with width: " + width + " and height: " + height);
[Link]("Area: " + area());

}
}

Page | 37
Programming with Java
(202044502)

New_figures/[Link]

package New_figures;
import [Link];

public class Triangle extends Shape {

private double base, height;

public Triangle(double base, double height) {

[Link] = base;
[Link] = height;

public double area() {

return 0.5 * base * height;


}

public void displayInfo() {

[Link]("Triangle with base: " + base + " and height: " + height);
[Link]("Area: " + area());

Page | 38
Programming with Java
(202044502)

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
import [Link];

class InvoiceDetail<N extends Number> {


private String invoiceName;
private N amount;
private N discount;

// Constructor
public InvoiceDetail(String invoiceName, N amount, N discount) {
[Link] = invoiceName;
[Link] = amount;
[Link] = discount;

// Getters
public String getInvoiceName() {

return invoiceName;
Page | 39
Programming with Java
(202044502)

public N getAmount() {
return amount;

public N getDiscount() {
return discount;
}

// Setters
public void setInvoiceName(String invoiceName) {

[Link] = invoiceName;
}

public void setAmount(N amount) {


[Link] = amount;

public void setDiscount(N discount) {


[Link] = discount;

}
}
public class Main1{

public static void main(String[] args) {


InvoiceDetail<BigDecimal> invoice = new InvoiceDetail<>("Invoice 123", new
BigDecimal("100.00"), new BigDecimal("10.00"));

[Link]("Invoice Name: " + [Link]());


[Link]("Amount: " + [Link]());
Page | 40
Programming with Java
(202044502)

[Link]("Discount: " + [Link]());


}

2. 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 [Link];
import [Link];
import [Link];

class Book implements Comparable<Book> {


private int id;
private String title;
private String author;
private String publisher;

public Book(int id, String title, String author, String publisher) {


[Link] = id;
[Link] = title;
[Link] = author;
[Link] = publisher;
}

Page | 41
Programming with Java
(202044502)

// Implementing Comparable interface based on book id


@Override
public int compareTo(Book other) {

return [Link] - [Link];


}

// Getter methods
public int getId() {
return id;
}

public String getTitle() {


return title;
}

public String getAuthor() {


return author;

public String getPublisher() {


return publisher;

// Override toString() for better printing of Book objects


@Override
public String toString() {

return "Book{" +

"id=" + id +
", title='" + title + '\'' +

Page | 42
Programming with Java
(202044502)

", author='" + author + '\'' +


", publisher='" + publisher + '\'' +
'}';

}
}

class BookComparator implements Comparator<Book> {


// Implementing Comparator interface based on book title
@Override
public int compare(Book b1, Book b2) {

return [Link]().compareTo([Link]());
}
}

public class Main2 {


public static void main(String[] args) {
ArrayList<Book> books = new ArrayList<>();
[Link](new Book(101, "Java Programming", "John Doe", "ABC Publications"));
[Link](new Book(103, "Python Basics", "Jane Smith", "XYZ Publishers"));
[Link](new Book(102, "Data Structures in C", "Alice Johnson", "PQR Books"));

// Sorting using Comparable (based on book id)


[Link]("Sorting books by id (using Comparable):");
[Link](books);
for (Book book : books) {

[Link](book);
}

[Link]();

Page | 43
Programming with Java
(202044502)

// Sorting using Comparator (based on book title)


[Link]("Sorting books by title (using Comparator):");
[Link](books, new BookComparator());
for (Book book : books) {

[Link](book);
}
}

Page | 44
Programming with Java
(202044502)

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.
// Custom Exception for insufficient balance
class NotEnoughMoneyException extends Exception {

public NotEnoughMoneyException(String message) {


super(message);
}
}

// Bank class to manage bank accounts


class Bank {
private double balance;

// Constructor to initialize balance


public Bank(double balance) {

[Link] = balance;
}

// Method to deposit money


public void deposit(double amount) {

double oldBalance = balance;


Page | 45
Programming with Java
(202044502)

balance += amount;
[Link]("Old Balance: " + oldBalance);
[Link]("New Balance after depositing " + amount + ": " + balance);

// Method to withdraw money


public void withdraw(double amount) throws ArithmeticException,
NotEnoughMoneyException {

if (balance < amount) {


throw new ArithmeticException("Balance is not enough to withdraw the money.");

} else {
double oldBalance = balance;
balance -= amount;
[Link]("Old Balance: " + oldBalance);
[Link]("New Balance after withdrawing " + amount + ": " + balance);
if (balance < 500) {

throw new NotEnoughMoneyException("Balance is less than 500rs after


withdrawing.");
}
}

}
}

public class Main1 {


public static void main(String[] args) {

Bank bank = new Bank(1000);

try {
[Link](500);
[Link](800);

Page | 46
Programming with Java
(202044502)

} catch (ArithmeticException e) {
[Link]("Exception: " + [Link]());
} catch (NotEnoughMoneyException e) {
[Link]("Exception: " + [Link]());
}
}

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 [Link];
public class Main2 {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

try {
[Link]("Enter the number of elements in the array: ");
int n = [Link]();

Page | 47
Programming with Java
(202044502)

if (n <= 0) {
throw new IllegalArgumentException("Number of elements should be greater than
zero.");

}
int[] arr = new int[n];
double sum = 0;
[Link]("Enter the elements of the array:");
for (int i = 0; i < n; i++) {

arr[i] = [Link]();
if (arr[i] < 0) {

throw new IllegalArgumentException("Element value should be positive.");


}
sum += arr[i];

}
double average = sum / n;
[Link]("Average of the array elements: " + average);

} catch (IllegalArgumentException e) {
[Link]("Exception: " + [Link]());

}
[Link]();

Page | 48
Programming with Java
(202044502)

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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];

class PrimeFinder implements Runnable {


private final int start;
private final int end;
private final List<Integer> primes;

public PrimeFinder(int start, int end) {


[Link] = start;
[Link] = end;
[Link] = new ArrayList<>();

@Override
public void run() {
for (int num = start; num <= end; num++) {

if (isPrime(num)) {
[Link](num);
}
}
Page | 49
Programming with Java
(202044502)

public List<Integer> getPrimes() {


return primes;

private boolean isPrime(int num) {


if (num <= 1) return false;
for (int i = 2; i <= [Link](num); i++) {

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


}
return true;

}
}

public class Multi {


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

int startRange = 1;
int endRange = 100;

// Using Multithreading
int threads = [Link]().availableProcessors();
int chunk = (endRange - startRange + 1) / threads;
List<PrimeFinder> primeFinders = new ArrayList<>();
List<Thread> threadList = new ArrayList<>();

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


int start = startRange + i * chunk;
int end = (i == threads - 1) ? endRange : start + chunk - 1;

Page | 50
Programming with Java
(202044502)

PrimeFinder primeFinder = new PrimeFinder(start, end);


[Link](primeFinder);
Thread thread = new Thread(primeFinder);
[Link](thread);
[Link]();

for (Thread thread : threadList) {


[Link]();

List<Integer> primeNumbers = new ArrayList<>();


for (PrimeFinder primeFinder : primeFinders) {
[Link]([Link]());

[Link]("Prime numbers found using Multithreading:");


[Link](primeNumbers);

// Using Executor Framework


ExecutorService executor = [Link](threads);
[Link](); // clear the list for reuse

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


int start = startRange + i * chunk;
int end = (i == threads - 1) ? endRange : start + chunk - 1;
PrimeFinder primeFinder = new PrimeFinder(start, end);
[Link](primeFinder);

Page | 51
Programming with Java
(202044502)

[Link]();
[Link](1, [Link]);

for (PrimeFinder primeFinder : primeFinders) {


[Link]([Link]());

[Link]("Prime numbers found using Executor Framework:");


[Link](primeNumbers);
}
}

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.

Page | 52
Programming with Java
(202044502)

import [Link].*;
class Queue {

private final int maxSize;


private final LinkedList<Integer> elements;

public Queue(int maxSize) {


[Link] = maxSize;
[Link] = new LinkedList<>();
}

public synchronized void produce(int element) {


while ([Link]() >= maxSize) {

try {
wait();

} catch (InterruptedException e) {
[Link]();
}
}
[Link](element);
[Link]("Produced: " + element);
notifyAll();

public synchronized int consume() {


while ([Link]()) {
try {
wait();

} catch (InterruptedException e) {
[Link]();

Page | 53
Programming with Java
(202044502)

}
}
int element = [Link]();
[Link]("Consumed: " + element);
notifyAll();
return element;

}
}

class Producer implements Runnable {


private final Queue queue;

public Producer(Queue queue) {


[Link] = queue;

@Override
public void run() {
for (int i = 1; i <= 20; i++) {

[Link](i);
try {

[Link](500);
} catch (InterruptedException e) {
[Link]();
}
}
}
}

Page | 54
Programming with Java
(202044502)

class Consumer implements Runnable {


private final Queue queue;

public Consumer(Queue queue) {


[Link] = queue;
}

@Override
public void run() {

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


[Link]();
try {
[Link](1000);
} catch (InterruptedException e) {

[Link]();
}
}
}
}

public class TestThread {


public static void main(String[] args) {

Queue queue = new Queue(15);

Thread producerThread = new Thread(new Producer(queue));


[Link](Thread.NORM_PRIORITY + 1);

Thread consumerThread1 = new Thread(new Consumer(queue));


[Link](Thread.NORM_PRIORITY - 1);

Page | 55
Programming with Java
(202044502)

Thread consumerThread2 = new Thread(new Consumer(queue));


[Link](Thread.NORM_PRIORITY - 1);

[Link]();
[Link]();
[Link]();

try {
[Link]();
[Link]();
[Link]();

} catch (InterruptedException e) {
[Link]();

}
}
}

Page | 56
Programming with Java
(202044502)

Practical-9
Collection API:
1. Write a program to demostrate user of ArrayList, LinkedList ,LinkedHashMap,
TreeMap and HashSet Class.

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class CollectionDemo {


public static void main(String[] args) {
// ArrayList demonstration
ArrayList<String> arrayList = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");

[Link]("ArrayList elements:");
for (String fruit : arrayList) {
[Link](fruit);

}
[Link]();

// LinkedList demonstration
LinkedList<String> linkedList = new LinkedList<>();
[Link]("Red");

Page | 57
Programming with Java
(202044502)

[Link]("Green");
[Link]("Blue");

[Link]("LinkedList elements:");
for (String color : linkedList) {
[Link](color);
}
[Link]();

// LinkedHashMap demonstration
LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<>();
[Link](1, "One");
[Link](2, "Two");
[Link](3, "Three");

[Link]("LinkedHashMap elements:");
for (Integer key : [Link]()) {

[Link]("Key: " + key + ", Value: " + [Link](key));


}
[Link]();

// TreeMap demonstration
TreeMap<Integer, String> treeMap = new TreeMap<>();
[Link](3, "Three");
[Link](1, "One");
[Link](2, "Two");

[Link]("TreeMap elements (sorted by key):");


for (Integer key : [Link]()) {

Page | 58
Programming with Java
(202044502)

[Link]("Key: " + key + ", Value: " + [Link](key));


}
[Link]();

// HashSet demonstration
HashSet<String> hashSet = new HashSet<>();
[Link]("Cat");
[Link]("Dog");
[Link]("Rabbit");
[Link]("HashSet elements (unordered):");
for (String animal : hashSet) {

[Link](animal);
}
[Link]();

}
}

Page | 59
Programming with Java
(202044502)

[Link] a program to Sort Array,ArrayList,String,List,Map and Set.


import [Link].*;
public class SortCollections {
public static void main(String[] args) {
// Sort array int[] arr = {5, 2, 8, 1, 6}; [Link](arr);
[Link]("Sorted array: " + [Link](arr)); // Sort ArrayList
ArrayList<Integer> arrayList = new ArrayList<>([Link](5, 2, 8, 1, 6));
[Link](arrayList); [Link]("Sorted ArrayList: " +
arrayList); // Sort String String str = "hello"; char[] charArray =
[Link](); [Link](charArray); String sortedStr = new
String(charArray); [Link]("Sorted String: " + sortedStr); // Sort
List List<Integer> list = [Link](5, 2, 8, 1, 6); [Link](list);
[Link]("Sorted List: " + list); // Sort Map by keys Map<Integer,
String> map = new HashMap<>(); [Link](3, "Three"); [Link](1, "One");
[Link](2, "Two"); TreeMap<Integer, String> sortedMapByKey = new
TreeMap<>(map); [Link]("Sorted Map by keys: " +
sortedMapByKey); // Sort Set Set<Integer> set = new HashSet<>
([Link](5, 2, 8, 1, 6)); TreeSet<Integer> sortedSet = new TreeSet<>
(set); [Link]("Sorted Set: " + sortedSet);

}
}

Page | 60
Programming with Java
(202044502)

Practical-10
File Handling Using Java:
1. Write a program to count occurrence of a given words in a file.
Create [Link] file
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class WordCount {


public static void main(String[] args) {

String fileName = "[Link]";


String[] wordsToCount = {"apple", "banana", "orange"};

Map<String, Integer> wordCounts = new HashMap<>();

try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {


String line;
while ((line = [Link]()) != null) {
for (String word : wordsToCount) {

int count = [Link](word, 0);


count += countOccurrences(line, word);
[Link](word, count);

}
}
} catch (IOException e) {
[Link]();

Page | 61
Programming with Java
(202044502)

// Print word counts


for ([Link]<String, Integer> entry : [Link]()) {

[Link]([Link]() + ": " + [Link]());


}

private static int countOccurrences(String line, String word) {


int count = 0;
int index = [Link](word);
while (index != -1) {

count++;
index = [Link](word, index + 1);

}
return count;
}
}

2. Write a program to print itself.


import [Link];
import [Link];
import [Link];
public class PrintSelf {

public static void main(String[] args) {

Page | 62
Programming with Java
(202044502)

String fileName = "[Link]";


try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {

String line;
while ((line = [Link]()) != null) {

[Link](line);
}
} catch (IOException e) {
[Link]();

}
}
}

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


import [Link];

public class ListFiles {


public static void main(String[] args) {
String directoryPath = "/path/to/directory";

File directory = new File(directoryPath);


File[] files = [Link]();

if (files != null) {
for (File file : files) {
if ([Link]()) {

[Link]([Link]());

}
}

Page | 63
Programming with Java
(202044502)

} else {
[Link]("Directory does not exist or is not accessible.");
}
}

Page | 64
Programming with Java
(202044502)

Practical-11
Networking
1. Implement Echo client/server program using TCP
[Link]:
import [Link].*;
import [Link].*;

public class EchoClient {


public static void main(String[] args) {

try (Socket socket = new Socket("localhost", 6666)) {


BufferedReader reader = new BufferedReader(new InputStreamReader([Link]));
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);

String line;
while ((line = [Link]()) != null) {
[Link](line);
[Link]("Server response: " + [Link]());
}

} catch (IOException e) {
[Link]();
}
}

Page | 65
Programming with Java
(202044502)

[Link]:
import [Link].*;
import [Link].*;

public class EchoClient {


public static void main(String[] args) {

try (Socket socket = new Socket("localhost", 6666)) {


BufferedReader reader = new BufferedReader(new InputStreamReader([Link]));
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);

String line;
while ((line = [Link]()) != null) {
[Link](line);
[Link]("Server response: " + [Link]());

}
} catch (IOException e) {
[Link]();
}

Page | 66
Programming with Java
(202044502)

2. Write a program using UDP which give name of the audio file to server and server
reply with content of audio file.
➢ Client Code:

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class AudioClient {


private static final int PORT = 1234;
private static final String SERVER_ADDRESS = "localhost";

public static void main(String[] args) {


try {
InetAddress serverAddress = [Link](SERVER_ADDRESS);

DatagramSocket socket = new DatagramSocket();

// Send file name to server


String fileName = "[Link]";
byte[] fileNameBytes = [Link]();
DatagramPacket fileNamePacket = new DatagramPacket(fileNameBytes,
[Link], serverAddress, PORT);
[Link](fileNamePacket);

// Receive file content from server


byte[] fileContent = new byte[1024];
Page | 67
Programming with Java
(202044502)

DatagramPacket fileContentPacket = new DatagramPacket(fileContent,


[Link]);

[Link](fileContentPacket);

// Save file content to disk


String fileContentString = new String([Link](), 0,
[Link]());

[Link]("Received file content: " + fileContentString);


FileInputStream fis = new FileInputStream(fileContentString);
BufferedInputStream bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream("received_" + fileName);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = [Link](buffer, 0, [Link])) != -1) {

[Link](buffer, 0, bytesRead);

}
[Link]();
[Link]();
[Link]();

[Link]();

} catch (SocketException e) {
[Link]();
} catch (UnknownHostException e) {
[Link]();
} catch (IOException e) {
[Link]();

}
}

Page | 68
Programming with Java
(202044502)

}
➢ Server Code:

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class AudioServer {


private static final int PORT = 1234;

public static void main(String[] args) {


try {
DatagramSocket socket = new DatagramSocket(PORT);

// Receive file name from client


byte[] fileNameBytes = new byte[1024];

DatagramPacket fileNamePacket = new DatagramPacket(fileNameBytes,


[Link]);
[Link](fileNamePacket);
String fileName = new String([Link](), 0,
[Link]());

[Link]("Received file name: " + fileName);

// Send file content to client


byte[] fileContent = "[Link] content".getBytes();
DatagramPacket fileContentPacket = new DatagramPacket(fileContent,
[Link], [Link](), [Link]());

Page | 69
Programming with Java
(202044502)

[Link](fileContentPacket);

[Link]();

} catch (SocketException e) {
[Link]();
} catch (IOException e) {
[Link]();

}
}
}

Page | 70
Programming with Java
(202044502)

Practical-12
GUI
1. Write a program to implement an investment value calculator using the data
inputted by user. text Fields 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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class InvestmentCalculator extends JFrame {

private JPanel contentPane;


private JTextField amountField;
private JTextField yearField;
private JTextField interestRateField;
private JTextField futureValueField;

public static void main(String[] args) {


[Link](new Runnable() {
Page | 71
Programming with Java
(202044502)

public void run() {


try {
InvestmentCalculator frame = new InvestmentCalculator();
[Link](true);

} catch (Exception e) {
[Link]();

}
}
});
}

public InvestmentCalculator() {
initialize();
}

private void initialize() {


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
[Link](new EmptyBorder(5, 5, 5, 5));
[Link](new BorderLayout(0, 0));
setContentPane(contentPane);

JPanel inputPanel = new JPanel();


[Link](inputPanel, [Link]);
[Link](new GridLayout(0, 2, 0, 0));

JLabel amountLabel = new JLabel("Amount:");


[Link](amountLabel);

Page | 72
Programming with Java
(202044502)

amountField = new JTextField();


[Link](amountField);
[Link](10);

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


[Link](yearLabel);

yearField = new JTextField();


[Link](yearField);
[Link](10);

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


[Link](interestRateLabel);

interestRateField = new JTextField();


[Link](interestRateField);
[Link](10);

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


[Link](futureValueLabel);

futureValueField = new JTextField();


[Link](false);
[Link](futureValueField);
[Link](10);

JButton calculateButton = new JButton("Calculate");


[Link](calculateButton, [Link]);

Page | 73
Programming with Java
(202044502)

[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
double amount = [Link]([Link]());
int year = [Link]([Link]());
double interestRate = [Link]([Link]());

double futureValue = amount * [Link](1 + interestRate, year);


[Link]([Link]("%.2f", futureValue));

}
});

}
}

2. Write a program which fill the rectangle with the selected color when button
pressed.
import [Link].*;
import [Link].*;

public class ColorFillButton extends Frame implements ActionListener {

private Panel rectanglePanel;


private Color selectedColor = [Link];

Page | 74
Programming with Java
(202044502)

private Button redButton, greenButton, blueButton;

public ColorFillButton() {
super("Color Fill Button");

rectanglePanel = new Panel();


[Link]([Link]);
[Link](new Dimension(100, 50));

redButton = new Button("Red");


greenButton = new Button("Green");
blueButton = new Button("Blue");

setLayout(new FlowLayout());
add(rectanglePanel);
add(redButton);
add(greenButton);
add(blueButton);

[Link](this);
[Link](this);
[Link](this);

setSize(300, 150);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


if ([Link]() == redButton) {

Page | 75
Programming with Java
(202044502)

selectedColor = [Link];
} else if ([Link]() == greenButton) {
selectedColor = [Link];
} else if ([Link]() == blueButton) {
selectedColor = [Link];
}

[Link](selectedColor);
[Link](); // Ensure immediate visual update

public static void main(String[] args) {


new ColorFillButton();
}

Page | 76

You might also like