0% found this document useful (0 votes)
12 views77 pages

Java OOP Lab Manual for B.Tech 2024

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

Java OOP Lab Manual for B.Tech 2024

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

SREENIDHI INSTITUTE OF SCIENCE & TECHNOLOGY

(An Autonomous Institution approved by UGC and affiliated to JNTUH)


(Accredited by NAAC with ‘A” Grade, Accredited by NBA of AICTE and
Recipient of World Bank under TEQIP-I and II )
Yamnampet, Ghatkesar Mandal, Hyderabad - 501 301.

LABORATORY MANUAL

FOR

Object Oriented Programming through Java

B. TECH 2nd Year 1st Semester


COMMON TO CSE /IT/ECM

DEPARTMENT OF
INFORMATION TECHNOLOGY
2024-2025
1 2 3 4 5 6 7 8 9 10 11 12
H M L
H: High M: Medium L: Low

Syllabus for [Link]. II year I Semester


Information Technology
OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB
(Common to CSE, IT and ECM)

Code: 9EC62 L T P C
- - 4 2
Course objective :
Understand, design an execute the programs involving concepts of Java and Object oriented programming
principles.

COURSE OUTCOMES: After completing this course, the student will be able to
1 Write programs to generate Prime numbers, Roots of quadratic equation and
Fibonacci series.

2 Write small application such as banking system.


3 Write programs on operator, function overloading and dynamic method dispatch.
4 Write programs to implement interface and packages.
5 Explain and write programs to implement threads.
6 Write programs to implement applets and event handling.
7 Write an application to implement client and server scenario.

List of Programs:

1. A) Write a program to print prime numbers up to a given number.


B) Write a program to print roots of a quadratic equation ax2+bx+c=0.
C) Write a program to print Fibonacci sequence up to a given number.

2.A) Define a class to represent a bank account and include the following members Instance variables:
(i)Name of depositor
(ii)Account No
(iii)Type of account
(iv)Balance amount in the account

Instance Methods:
To assign instance variables (Constructors-Zero argument and parameterized)
[Link] deposit an amount
[Link] withdraw amount after checking the balance
(iv) To display name and address
Define ExecuteAccount class in which define main method to test above class.
B) In the above account class, maintain the total no. of account holders present in the bank and also define a
method to display it. Change the main method appropriately.
C) In main method of ExecuteAccount class, define an array to handle five accounts.
1
D) In Account class constructor, demonstrate the use of “this” keyword.
E) Modify the constructor to read data from keyboard.
F) Overload the method deposit() method (one with argument and another without argument)
G) In Account class, define set and get methods for each instance variable.
Example:
For account no variable, define the methods
getAccountNo() and setAccountNo(int accno)
In each and every method of Account class, reading data from and writing data to instance variables
should be done through these variables.

3.A) Define Resister class in which we define the following members:


Instance variables:
resistance
Instance Methods:
giveData():To assign data to the resistance variable
displayData(): To display data in the resistance variable
constructors
Define subclasses for the Resistor class called SeriesCircuit and ParallelCircuit in which define
methods : calculateSeriesResistance( ) and calculateParallelResistance() [Link] the
methods should take two Resistor objects as arguments and return Resistor object as [Link] main
method , define another class called ResistorExecute to test the above class.
B) Modify the above two methods which should accept array of Resistor objects as argument and return
Resistor object as result.
4 .A) Write a program to demonstrate method overriding.
B)Write a program to demonstrate the uses of “super” keyword (three uses)
C)Write a program to demonstrate dynamic method dispatch (i.e .Dynamic polymorphism).

5) A) Write a program to check whether the given string is palindrome or not.


B)Write a program for sorting a given list of names in ascending order.
C)Write a program to count the no. of words in a given text.

6. A) Define an interface “GeomtricShape” with methods area( ) and perimeter( ) (Both method’s return
type and parameter list should be void and empty respectively.
Define classes like Triangle, Rectangle and Circle implementing the “GeometricShape”
interface and also define “ExecuteMain” class in which include main method to test the above class
B) Define a package with name “sortapp” in which declare an interface “SortInterface” with method sort(
) whose return type and parameter list should be void and [Link] “subsortapp” as subpackage
of “sortapp” package in which define class “SortImpl” implementing “SortInterface” in which sort()
method should print a message linear sort is used.
Define a package “searchingapp” in which declare an interface “SearchInterface” with search( )
method whose return type and parameter list should be void and empty respectively.
Define “searchingimpl” package in which define a “SearchImpl” class implementing “SearchInterface”
defined in “searchingapp” package in which define a search( ) method which should print a message
linear search is used.
Define a class ExecutePackage with main method using the above packages(classes and its methods).
Use ArrayList class of Collections Framework to and use algorithms to search and sort the elemnt of an
array.

7) Modify the withdraw() method of Account class such that this method should throw
“InsufficientFundException” if the account holder tries to withdraw an amount that leads to condition
2
where current balance becomes less than minimum balance otherwise allow the account holder to
withdraw and update the balance accordingly.
8. A) Define two threads such that one thread should print even numbers and another thread should print
odd numbers.
B) Modify the Account class to implement thread synchronization concept.
C) Define two threads such that one thread should read a line of text from text file and another thread
should write that line of text to another file. (Thread communication example).
D) Write a program to implement thread priority.

9) Design the user screen as follows and handle the events appropriately.
Add Window
First Number
Second Number
Result
ADD SUBTRACT

10) Write a program to simulate a calculator


11) Write a Java program for handling mouse events and key events.
12) a) Write a program for handling window events.
b) Develop an applet that displays a simple message..
13) Develop a client that sends data to the server and also develop a server that sends data to the client (two
way communication)
14) Develop a client/server application in which client read a file name from keyboard and send the file name
to the server, and server will read the file name from client and send the file contents to the client.

Programs Beyond the Syllabus

15) Write a program to illustrate the scope of default , private, protected and public access modifiers
for variables and methods in java .
16).Write a java program to illustrate the usage of multiple catch blocks in java.
17) Develop a program for passing parameters to an Applet.

3
INDEX

[Link] NAME OF THE PROGRAM Page .N


o.
1 (A)Write a program to print prime numbers up to a given number 8
(B)Write a program to print roots of a quadratic equation ax2+bx+c=0
(C)Write a program to print Fibonacci sequence up to a given number
2 ( A) Define a class to represent a bank account and include the following 12
members Instance variables:
(i)Name of depositor
(ii)Account No
(iii)Type of account
(iv)Balance amount in the account

Instance Methods:
To assign instance variables (Constructors-Zero argument and
parameterized)
3. To deposit an amount
4. To withdraw amount after checking the balance
(iv) To display name and address
Define ExecuteAccount class in which define main method to test above
class.
B) In the above account class, maintain the total number of account holders
present in the bank and also define a method to display it. Change the main
method appropriately.
C) In main method of Execute Account class, define an array to handle five
accounts
D) In Account class constructor, demonstrate the use of “this” keyword
E) Modify the constructor to read data from keyboard
F) Overload the method deposit () method (one with argument and
another without argument)
G) In Account class, define set and get methods for each instance variables.
Example:
For account no variable, define the methods
getAccountNo() and setAccountNo(int accno)
In each and every method of Account class, reading data from and writing
data to instance variables should be done through these variables.
3 A) Define Resister class in which we define the following members: 27
Instance variables:
resistance
Instance Methods:
giveData():To assign data to the resistance variable
displayData(): To display data in the resistance variable
4
constructors
Define subclasses for the Resistor class called SeriesCircuit and
ParallelCircuit in which define methods :
calculateSeriesResistance( ) and calculateParallelResistance()
[Link] the methods should take two Resistor objects as
arguments and return Resistor object as [Link] main method ,
define another class called ResistorExecute to test the above class.
B) Modify the above two methods which should accept array of Resistor
objects as argument and return Resistor object as result.
4 A). Write a program to demonstrate method overriding. 31
B). Write a program to demonstrate the uses of “super” keyword (three
uses)
C). Write a program to demonstrate dynamic method dispatch
(ie. Dynamic polymorphism)
5 A) Write a program to check whether the given string is palindrome or not. 36
B) Write a program for sorting a given list of names in ascending order
C) Write a program to count the number of words in a given text.
6 A) Define an interface “GeomtricShape” with methods area( ) and 40
perimeter( ) (Both method’s return type and parameter list should
be void and empty respectively.
Define classes like Triangle, Rectangle and Circle implementing the
“GeometricShape”
interface and also define “ExecuteMain” class in which include main
method to test the above class.

B) Define a package with name “sortapp” in which declare an interface


“SortInterface” with method sort( ) whose return type and
parameter list should be void and [Link] “subsortapp” as
subpackage of “sortapp” package in which define class “SortImpl”
implementing “SortInterface” in which sort() method should print a
message linear sort is used.
Define a package “searchingapp” in which declare an interface
“SearchInterface” with search( ) method whose return type and
parameter list should be void and empty respectively.
Define “searchingimpl” package in which define a “SearchImpl” class
implementing “SearchInterface” defined in “searchingapp” package
in which define a search( ) method which should print a message
linear search is used.
Define a class ExecutePackage with main method using the above
packages(classes and its methods).
Use ArrayList class of Collections Framework to and use algorithms
to search and sort the elemnt of an array.
7 Modify the withdraw() method of Account class such that this method 44
should throw “Insufficient Fund Exception” if the account holder tries to

5
withdraw an amount that leads to condition where current balance becomes
less than minimum balance otherwise allow the account holder to withdraw
and update balance accordingly.
8 A) Define two threads such that one thread should print even numbers and 46
another thread should print even numbers.
B). Modify the Account class to implement synchronization concept.
C). Define two threads such that one thread should read a line of text file and
another thread should write that line of text to another file (Thread
communication example)
D). Write a program to implement thread priority.
9 Design the user screen as follows and handle the events appropriately. 54
Add Window
First Number
Second Number
Result
ADD SUBTRACT

10 Write a Java program to simulate a calculator. 56


11 Write a Java program for handling mouse events and key events. 61
12 a) Write a program for handling window events. 66

b) Develop an applet that displays a simple message.

13 Develop a client that sends data to the server and also develop a server that 69
sends data to the client (two way communication)
14 Develop a client server application in which client read a file name from the 72
key board and send the file name to the server, and server will read the file
name from client and send the file contents to the client.
15. Write a program to illustrate the scope of default ,private,protected and 74
public access modifiers for variables and methods in java .
16 Write a java program to illustrate the usage of multiple catch blocks in java. 76

17 Develop a program for passing parameters to an Applet. 77

6
OOP THROUGH JAVA LAB

1A) Write a program to print prime numbers up to a given number.

import [Link];
class Test {
void check(int num) {
[Link] ("Prime numbers up to "+num+" are:");
for (int i=1;i<=num;i++)
for (int j=2;j<i;j++) {
if(i%j==0)
break;
else if((i%j!=0)&&(j==i-1))
[Link](“ “+i);
}
}
} //end of class Test

class Prime {
public static void main(String args[ ]) {
Test obj1=new Test();
Scanner input=new Scanner([Link]);
[Link]("Enter the value of n:");
int n=[Link]();
[Link](n);
}
}

7
B) Write a program to print roots of a quadratic equation ax2+bx+c=0.
import [Link].*;
import [Link].*;
class quad{
public static void main(String args[]){
Scanner s=new Scanner([Link]);
[Link]("enter the values for a,b & c");
int a=[Link]();
int b=[Link]();
int c=[Link]();

double d,e;

d=((b*b)-(4*a*c));
if(d==0){
[Link]("expression has real&equal roots");
e=(-b)/(2*a);
[Link]("roots are:"+e+"\t"+e);
}
if(d>0){
[Link]("expression has real&unreal roots");

e=(-b+[Link](d))/(2*a);

[Link]("roots are:"+e+"\t");
e=(-[Link](d))/(2*a);
[Link](e);
}
if(d<0){
[Link]("expression has imaginary rotts");
}
}
}

8
C) Write a program to print Fibonacci sequence up to a given number.

import [Link];

class Fib {
public static void main(String args[ ]) {
Scanner input=new Scanner([Link]);
int i,a=0,b=1,c=0,t;
[Link]("Enter value of t:");
t=[Link]();
[Link](a);
[Link](" "+b);
for(i=0;i<t-2;i++) {
c=a+b;
a=b;
b=c;
[Link](" "+c);
}

[Link]();
[Link](t+"th value of the series is: "+c);
}
}

9
10
2A) Define a class to represent a bank account and include the following members
Instance Variables:
i) Name of depositor
ii) Account no
iii) Type of account
iv) Balance amount in the account
Instance Methods:
i) To assign instance variables (Customer-Zero argument and parameterized)
ii) To deposit an amount
iii) To withdraw amount after checking the balance
iv) To display name and address
Define ExecuteAccount class in which define main method to test above class.

2A) Define a class to represent a bank account and include the following members
Instance Variables:
i) Name of depositor
ii) Account no
iii) Type of account
iv) Balance amount in the account
Instance Methods:
i) To assign instance variables (Constructors-Zero argument and parameterized)
ii) To deposit an amount
iii) To withdraw amount after checking the balance
iv) To display name and address
Define ExecuteAccount class in which define main method to test above class.
import [Link].*;
class BankAccount
{
String name,type;
int acctno;
double balance;
double wbalance;
Scanner s = new Scanner([Link]);
public BankAccount()
{
name="abc";
type="saving";
acctno=1234567890;
balance=10000.00;
}
public BankAccount(String n,String t,int an,double bl)
{
name=n;
type=t;
acctno=an;
balance=bl;
}
void deposit()
{
double dat;
11
[Link]("Enter the amount to deposit: ");
dat=[Link]();
if(dat>0)
{
balance+=dat;
}
else
[Link]("Enter the valid Amount");
}
void withdraw()
{
[Link]("Enter the amount to withdraw : ");
wbalance=[Link]();
if(wbalance>0)
{
balance-=wbalance;
}
else
[Link]("Enter the valid Amount");
}
void display()
{
[Link]("Account Holder Name: "+name);
[Link]("Account Number: "+acctno);
[Link]("Account Number: "+type);
[Link]("Account Balance: "+balance);
[Link]();
}
}
class ExecuteAccountA
{
public static void main(String args[])
{
BankAccount ba1=new BankAccount();
BankAccount ba2=new BankAccount("Sreenivas","Saving",1234567891,20000);
[Link]("1st Account holder Details : \n");
[Link]();
[Link]();
[Link]();
[Link]();
[Link]("2nd Account holder Details : \n");
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output:

12
B) In the above account class, maintain the total number of account holders present in the bank and also
define a method to display it. Change the main method appropriately.

import [Link].*;
class BankAccount
{
String name,type;
int acctno;
double balance;
double wbalance;
static int count=0;
Scanner s = new Scanner([Link]);
public BankAccount()
{
name="abc";
type="saving";
acctno=1234567890;
balance=10000.00;
count++;
}
public BankAccount(String n,String t,int an,double bl)
{
13
name=n;
type=t;
acctno=an;
balance=bl;
count++;
}
void deposit()
{
double dat;
[Link]("Enter the amount to deposit: ");
dat=[Link]();
if(dat>0)
{
balance+=dat;
}
else
[Link]("Enter the valid Amount");
}
void withdraw()
{
[Link]("Enter the amount to withdraw : ");
wbalance=[Link]();
if(wbalance>0)
{
balance-=wbalance;
}
else
[Link]("Enter the valid Amount");
}
void display()
{
[Link]("Account Holder Name: "+name);
[Link]("Account Number: "+acctno);
[Link]("Account Number: "+type);
[Link]("Account Balance: "+balance);
[Link]();
}
static void totalAccounts()
{
[Link]("Total [Link] Accounts :"+count);
}
}
class ExecuteAccountB
{
public static void main(String args[])
{
BankAccount ba1=new BankAccount();
BankAccount ba2=new BankAccount("Sreenivas","Saving",1234567891,20000);
BankAccount ba3=new BankAccount("Sreenu","Saving",1234567892,30000);
BankAccount ba4=new BankAccount();
14
BankAccount ba5=new BankAccount("Srinu","Saving",1234567893,15000);
[Link]();
}
}
Output:

C) In main method of ExecuteAccount class, define an array to handle five accounts.

import [Link].*;
class BankAccount
{
String name,type;
int acctno;
double balance;
double wbalance;
static int count=0;
Scanner s = new Scanner([Link]);
public BankAccount()
{
name="abc";
type="saving";
acctno=1234567890;
balance=10000.00;
count++;
}
public BankAccount(String n,String t,int an,double bl)
{
name=n;
type=t;
acctno=an;
balance=bl;
count++;
}
void deposit()
{
double dat;
[Link]("Enter the amount to deposit: ");
dat=[Link]();
if(dat>0)
{
balance+=dat;
}
else

15
[Link]("Enter the valid Amount");
}
void withdraw()
{
[Link]("Enter the amount to withdraw : ");
wbalance=[Link]();
if(wbalance>0)
{
balance-=wbalance;
}
else
[Link]("Enter the valid Amount");
}
void display()
{
[Link]("Account Holder Name: "+name);
[Link]("Account Number: "+acctno);
[Link]("Account Number: "+type);
[Link]("Account Balance: "+balance);
[Link]();
}
static void totalAccounts()
{
[Link]("Total [Link] Accounts :"+count);
}
}
class ExecuteAccountC
{
public static void main(String args[])
{
BankAccount[] ba=new BankAccount[5];
ba[0]=new BankAccount("Sreenivas","Saving",1234567891,20000);
ba[1]=new BankAccount("Sreenu","Saving",1234567892,30000);
ba[2]=new BankAccount();
ba[3]=new BankAccount("Srinu","Saving",1234567893,15000);
ba[4]=new BankAccount();
[Link]("Five Accounts Details: ");
for(int i=0;i<[Link];i++)
ba[i].display();
}
}
Output:

16
D) In Account class constructor, demonstrate the use of “this” keyword.
import [Link].*;
class BankAccount
{
String name,type;
int acctno;
double balance;
double wbalance;
static int count=0;
Scanner s = new Scanner([Link]);
public BankAccount()
{
name="abc";
type="saving";
acctno=1234567890;
balance=10000.00;
count++;
}
public BankAccount(String name,String type,int acctno,double balance)
{
[Link]=name;
[Link]=type;
[Link]=acctno;
[Link]=balance;
count++;
}

17
void deposit()
{
double dat;
[Link]("Enter the amount to deposit: ");
dat=[Link]();
if(dat>0)
{
balance+=dat;
}
else
[Link]("Enter the valid Amount");
}
void withdraw()
{
[Link]("Enter the amount to withdraw : ");
wbalance=[Link]();
if(wbalance>0)
{
balance-=wbalance;
}
else
[Link]("Enter the valid Amount");
}
void display()
{
[Link]("Account Holder Name: "+name);
[Link]("Account Number: "+acctno);
[Link]("Account Number: "+type);
[Link]("Account Balance: "+balance);
[Link]();
}
static void totalAccounts()
{
[Link]("Total [Link] Accounts :"+count);
}
}
class ExecuteAccountD
{
public static void main(String args[])
{
BankAccount ba1=new BankAccount();
BankAccount ba2=new BankAccount("Sreenivas","Saving",1234567891,20000);
[Link]();
[Link]();
}
}
Output:

18
E) Modify the constructor to read data from keyboard.
import [Link].*;
class BankAccount
{
String name,type;
int acctno;
double balance;
double wbalance;
static int count=0;
Scanner s = new Scanner([Link]);
public BankAccount()
{
[Link]("Enter the Name: ");
name=[Link]();
[Link]("Enter the type of Account: ");
type=[Link]();
[Link]("Enter the Account Number: ");
acctno=[Link]();
[Link]("Enter the Balance: ");
balance=[Link]();
count++;
}
void deposit()
{
double dat;
[Link]("Enter the amount to deposit: ");
dat=[Link]();
if(dat>0)
{
balance+=dat;
}
else
[Link]("Enter the valid Amount");
}
void withdraw()
{
[Link]("Enter the amount to withdraw : ");
19
wbalance=[Link]();
if(wbalance>0)
{
balance-=wbalance;
}
else
[Link]("Enter the valid Amount");
}
void display()
{
[Link]("Account Holder Name: "+name);
[Link]("Account Number: "+acctno);
[Link]("Account Number: "+type);
[Link]("Account Balance: "+balance);
[Link]();
}
static void totalAccounts()
{
[Link]("Total [Link] Accounts :"+count);
}
}
class ExecuteAccountE
{
public static void main(String args[])
{
BankAccount ba1=new BankAccount();
[Link]();
}
}
Output:

20
F) Overload the method deposit () method (one with argument and another without argument)

import [Link].*;
class BankAccount
{
String name,type;
int acctno;
double balance;
double wbalance;
static int count=0;
Scanner s = new Scanner([Link]);
public BankAccount()
{
[Link]("Enter the Name: ");
name=[Link]();
[Link]("Enter the type of Account: ");
type=[Link]();
[Link]("Enter the Account Number: ");
acctno=[Link]();
[Link]("Enter the Balance: ");
balance=[Link]();
count++;
}
void deposit()
{
double dat;
[Link]("Enter the amount to deposit: ");
dat=[Link]();
if(dat>0)
{
balance+=dat;
}
else
[Link]("Enter the valid Amount");
}
void deposit(double d)
{
if(d>0)
{
balance+=d;
}
else
[Link]("Enter the valid Amount");
}
void withdraw()
{
[Link]("Enter the amount to withdraw : ");
wbalance=[Link]();
if(wbalance>0)
{
21
balance-=wbalance;
}
else
[Link]("Enter the valid Amount");
}
void display()
{
[Link]("Account Holder Name: "+name);
[Link]("Account Number: "+acctno);
[Link]("Account Number: "+type);
[Link]("Account Balance: "+balance);
[Link]();
}
static void totalAccounts()
{
[Link]("Total [Link] Accounts :"+count);
}
}
class ExecuteAccountF
{
public static void main(String args[])
{
BankAccount ba1=new BankAccount();
[Link]("Account Details :");
[Link]();
[Link]();
[Link]("Account Details after deposit :");
[Link]();
[Link](3500);
[Link]("Account Details after deposit :");
[Link]();
}
}
Output:

22
G) In Account class, define set and get methods for each instance variables.
Example:
For account number variable, define the methods.
getAccountNo() and setAccountNo(int accno)
In each and every method of Account class, reading data from and writing data to instance variables should
be done through these variables.

import [Link];
class BankAccount{

String AcctName,Type;
long AcctNo;
double balance;
Scanner s=new Scanner([Link]);

void getAcctNo(){
[Link]("Acct Number is :"+AcctNo);
}

void setAcctNo(int acctno){


AcctNo=acctno;
}

void getAcctBalance(){
[Link]("Acct balance is :"+balance);
23
}

void setAcctBalance(double bal){


balance=bal;
}
void setName(String s){
AcctName=s;
}
void getName(){
[Link]("AcctName is:"+AcctName);

}
void setType(String type){
Type=type;
}
void getType(){
[Link]("Account type is: "+Type);
}
public BankAccount(String Name,String T,long AccNo,double bal){

AcctName=Name;
Type=T;
balance=bal;
AcctNo=AccNo;

void deposit(){
getAcctBalance();
}

void withdraw(){
double wbal;
[Link]("Enter with draw amount:");
wbal=[Link]();
[Link]("with draw amount is:"+wbal);
balance=balance-wbal;
[Link]("balance after with drawing: "+balance);
}

void display(){
getAcctNo();
getType();
getName();

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

24
BankAccount ba=new BankAccount("abc","saving",1234,20000.00);

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

}
}

25
3. A) Define Resister class in which we define the following members:
Instance variables:
resistance
Instance Methods:
giveData():To assign data to the resistance variable
displayData(): To display data in the resistance variable
constructors
Define subclasses for the Resistor class called SeriesCircuit and ParallelCircuit in w h i c h d e f i n e m e t h o d s :
c a l c u l a t e S e r i e s R e s i s t a n c e ( ) a n d calculateParallelResistance() [Link] the methods should take
two Resistor objects as arguments and return Resistor object as [Link] main method , define another class called
ResistorExecute to test the above class.

import [Link];
class Resistor
{
float resistance;
void giveData()
{
Scanner sc=new Scanner([Link]);
[Link]("enter value of resistance");
resistance=[Link]();
}
void displayData()
{
[Link]("resultant value of series is :"+resistance);
}
}
class SeriesCircuit extends Resistor
{
Resistor calculateSeriesResistance(Resistor r1,Resistor r2)
{
Resistor r3=new Resistor();
[Link]=[Link]+[Link];
return r3;
}
}
class ParallelCircuit extends Resistor
{
Resistor calculateParallelResistance(Resistor r1,Resistor r2)
{
Resistor r4=new Resistor();
[Link]=([Link]*[Link])/([Link]+[Link]);
return r4;
}
}
class ResistorExecute
{
public static void main(String args[])
{
Resistor r3,r4;
26
Resistor r1=new Resistor();
[Link]();
Resistor r2=new Resistor();
[Link]();
SeriesCircuit sc=new SeriesCircuit();
r3=[Link](r1,r2);
[Link]();
ParallelCircuit PA=new ParallelCircuit();
r4=[Link](r1,r2);
[Link]();
}
}
Output:

B) Modify the above two methods which should accept array of Resistor objects as argument and return Resistor object as
27
result.

import [Link];
class Resistor
{
float resistance;
void giveData()
{
Scanner sc=new Scanner([Link]);
[Link]("enter value of resistance");
resistance=[Link]();
}
void displayData()
{
[Link]("resultant value of series is :"+resistance);
}
}
class SeriesCircuit extends Resistor
{
Resistor calculateSeriesResistance(Resistor[] r)
{
Resistor r3=new Resistor();
[Link]=r[0].resistance+r[1].resistance;
return r3;
}
}
class ParallelCircuit extends Resistor
{
Resistor calculateParallelResistance(Resistor[] r)
{
Resistor r4=new Resistor();
[Link]=(r[0].resistance*r[1].resistance)/(r[0].resistance+r[1].resistance);
return r4;
}
}
class ResistorExecuteA
{
public static void main(String args[])
{
Resistor r3,r4;
Resistor[] r=new Resistor[2];
r[0]=new Resistor();
r[1]=new Resistor();
for(int i=0;i<2;i++)
r[i].giveData();
SeriesCircuit sc=new SeriesCircuit();
r3=[Link](r);
[Link]();
ParallelCircuit PA=new ParallelCircuit();
r4=[Link](r);
28
[Link]();
}
}
Output:

29
4. A) Write a program to demonstrate method overriding.

class Simple
{
void method()
{
[Link]("method in Simple");
}
}
class SimpleA extends Simple
{
void method()
{
[Link]("method in SimpleA");
}
}
class TestOverRiding
{
public static void main(String[] args)
{
Simple s1=new Simple();
[Link]();
SimpleA s2=new SimpleA();
[Link]();
Simple s3=new SimpleA();
[Link]();
}
}

Output:

30
B) Write a program to demonstrate the uses of "super" keyword (three uses)

//Call Base Class Constructor using super


class SuperClass
{
public SuperClass(String str)
{
[Link]("Base Class Constructor " + str);
}
}
class SubClass extends SuperClass
{
public SubClass(String str)
{
super(str);
[Link]("Sub Class Constructor " + str);
}
}
class MainClass1
{
public static void main(String args[])
{
SubClass obj = new SubClass("called");
}
}

Output:

//Call Base Class Method using super


class SuperClass
{
void display()
{
[Link]("Base Class method called");
}
}
31
class SubClass extends SuperClass
{

void display()

{
[Link]();
[Link]("Sub Class method called");
}
}
class MainClass2
{
public static void main(String args[])
{
SubClass obj = new SubClass();
[Link]();
}
}

Output:

//Access Base Class Variables using super


class SuperClass
{
int a = 10;
}

class SubClass extends SuperClass


{
int a = 20;
void display()
{
[Link]("The value is : " + super.a);
}
}

32
class MainClass3
{
public static void main(String args[])
{
SubClass obj = new SubClass();
[Link]();
}
}

Output:

C) Write a program to demonstrate dynamic method dispatch (i.e. Dynamic polymorphism).

//Dynamic Method Dispatch


class A
{
void callme()
{
[Link]("Inside A's callme method");
}
}
class B extends A
{
void callme()
{
[Link]("Inside B's callme method");
}
}
class C extends B
{
void callme()
{
[Link]("Inside C's callme method");
33
}
}
class Dispatch
{
public static void main(String args[])
{
A a=new A();
B b=new B();
C c=new C();

A r;

r=a;
[Link]();

r=b;
[Link]();

r=c;
[Link]();
}
}

Output:

5) A) Write a program to check whether the given string is palindrome or not.

import [Link];
34
class Palindrome
{
public static void main(String[] args)
{
String str;
Scanner in = new Scanner([Link]);
[Link]("Enter the String : ");
str=[Link]();
StringBuffer sb=new StringBuffer(str);
String rstr=[Link]().toString();
if([Link](rstr))
[Link]("The given String is Palindrome");
else
[Link]("The given String is not Palindrome");
}
}

Output:

B) Write a program for sorting a given list of names in ascending order.

35
import [Link];
class StringSort
{
public static void main(String args[])
{
String names[]=new String[5];
Scanner in = new Scanner([Link]);
[Link]("Enter the Names: ");
for (int i = 0; i < 5; i++)
{
names[i]=[Link]();
}
int size=[Link];
[Link](size);
[Link]("Before Sorting : ");
for(int i=0;i<size;i++)
{
[Link](names[i]);
}
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(names[i].compareTo(names[j])>0)
{
String temp=names[i];
names[i]=names[j];
names[j]=temp;
}
}
}
[Link]("After Sorting : ");
for(int i=0;i<size;i++)
{
[Link](names[i]);
}
}
}

Output:

36
37
C) Write a program to count the no. of words in a given text.

import [Link].*;
import [Link].*;
class Count
{
public static void main(String args[ ])throws IOException
{
long nl=0,nw=0,nc=0;
String line;
BufferedReader br=new BufferedReader(new FileReader(args[0]));
while ((line=[Link]())!=null)
{
nl++;
nc=nc+[Link]();
StringTokenizer st = new StringTokenizer(line);
nw += [Link]();
}
[Link]("Number of Characters: "+nc);
[Link]("Number of Words: "+nw);
[Link]("Number of Lines: "+nl);
}
}

Output:

38
6. A) Define an interface "GeomtricShape" with methods area( ) and perimeter()(Both method's return
type and parameter list should be void and empty respectively). D e f i n e c l a s s e s l i k e T r i a n g l e ,
R e c t a n g l e a n d C i r c l e i m p l e m e n t i n g t h e "GeometricShape" interface and also define
"ExecuteMain" class in which include main method to test the above classes.

import [Link];
interface GeometricShape
{
void area();
void perimeter();
}
class Triangle implements GeometricShape
{
double a=1,b=2,c=1,h=4;
public void area()
{
[Link]("");
double area1=0.5*b*h;
[Link]("Area of a Triangle: "+area1);
}
public void perimeter()
{
double per=a+b+c;
[Link]("Perimeter of a Triangle: "+per);
[Link]("");
}
}
class Rectangle implements GeometricShape
{
int length=15,width=10,per,area1;
public void area()
{
area1=length*width;
[Link]("Area of Rectangle: "+area1);
}
public void perimeter()
{
per=2*length+2*width;
[Link]("Perimeter of Rectangle: "+per);
[Link]("");
}
}
class Circle implements GeometricShape
{
int r=10;
double p=3.141,area1=0.0,per=0.0;
public void area()
{
area1=p*r*r;
39
[Link]("Area of Circle: "+area1);
}
public void perimeter()
{
per=2*p*r;
[Link]("Perimeter of Circle: "+per);
[Link]("");
}
}
class ExecuteMain
{
public static void main(String args[])
{
Triangle t=new Triangle();
[Link]();
[Link]();
Circle c=new Circle();
[Link]();
[Link]();
Rectangle r=new Rectangle();
[Link]();
[Link]();
}
}

Output:

40
B) Define a package with name “sortapp” in which declare an interface “SortInterface” with method sort ()
whose return type and parameter type should be void and empty. Define “subsortapp” as sub package of
“sortapp” package in which define class “SortImpl” implementing “SortInterface” in which sort() method
should print a message Linear sort is used.
Define a package “searchingapp” in which declare an interface “SearchInterface” with search () method
whose return type and parameter list should be void and empty respectively.
Define “serachingimpl” package in which define a “SearchImpl” class implementing “SearchInterface”
defined in “searchingapp” package in which define a search() method which should print a message linear
search is used.
Define a class ExecutePackage with main method using the above packages (classes and it’s methods).

//program1
package sortapp;
public interface SortInterface
{
void sort();
}

//program2
package [Link];
import sortapp.*;

public class SortImpl implements SortInterface


{
public void sort()
{
[Link]("Sort Interface.......");
}
}

//program3
package searchingapp;
public interface SearchInterface
{
void search();
}

//program4

package searchingimpl;
import searchingapp.*;
public class SearchImpl implements SearchInterface
{
public void search()
{
[Link]("Search Interface.......");
41
}
}

//program5

import [Link];
import [Link];
import [Link];
import [Link];
class ExecutePackageB
{
public static void main(String args[])
{
SortImpl sort1=new SortImpl();
SearchImpl search1=new SearchImpl();
[Link]();
[Link]();
}
}

Output:

7). Modify the withdraw() method of Account class such that this method should throw

42
“InsufficientFundException” if the account holder tries to withdraw an amount that leads to condition where
current balance becomes less than minimum balance otherwise allow the account holder to withdraw and
update balance accordingly.

import [Link];
class InsufficientException extends Exception{
double balance;
double wbalance;
public InsufficientException(String msg){
super(msg);
}
void withdraw(){
double balance=25000.00;
[Link]("Current Balance: "+balance);
try{
[Link]("Enter withdraw amount: ");
Scanner in=new Scanner([Link]);
double wamount=[Link]();
if(wamount>balance){
throw new InsufficientException("Insufficient balance in account.....");
}
else
[Link]("Transaction Successfully Completed...............");
double rembal=balance-wamount;
[Link]("Withdrawal Amount :"+wamount);
[Link]("After transaction current balance :"+rembal); }
catch(InsufficientException e){
[Link]("Caught:"+[Link]());
}
}
}
class ExecuteAccount6{
public static void main(String args[]) {
InsufficientException ie=new InsufficientException("Insufficient balance in account");
[Link]();
}
}

43
44
8. A) Define two threads such that one thread should print even numbers and another thread should print
odd numbers.
public class EvenOddNumber
{
int i = 1;

public synchronized void printNumber(String threadNm) throws InterruptedException


{

if([Link]("t1"))
{
if(i%2 == 1)
{
[Link]([Link]().getName()+"--"+ i++);
notify();
}
else
{
wait();
}
} else if([Link]("t2"))
{
if(i%2 == 0)
{
[Link]([Link]().getName()+"--"+ i++);
notify();
}
else
{
wait();
}
}

public static void main(String[] args)


{
final EvenOddNumber obj = new EvenOddNumber();
Thread t1 = new Thread(new Runnable()
{

public void run() {


try {
while(obj.i <= 10){

[Link]([Link]().getName());
}
} catch (InterruptedException e) {
45
// TODO Auto-generated catch block
[Link]();
}
[Link]("done t1");
}
});
Thread t2 = new Thread(new Runnable() {

public void run() {


try {
while(obj.i <=10){
[Link]([Link]().getName());
}
} catch (InterruptedException e) {
[Link]();
}
[Link]("done t2");
}
});

[Link]("t1");
[Link]("t2");
[Link]();
[Link]();
}
}
Output:

46
B) Write a program to implement thread synchronization concept.
//example of java synchronized method
class Table{
synchronized void printTable(int n)
{//synchronized method
for(int i=1;i<=5;i++)
{
[Link](n*i);
try
{
[Link](400);
}
catch(Exception e)
{
[Link](e);
}
}

}
}

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
[Link](5);
}

}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
[Link](100);
}
}
public class TestSynchronization2
{
47
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
[Link]();
[Link]();
}
}
Output:

48
C) Define two threads such that one thread should read a line of text from text file and another thread
should write that line of text to another file. (Thread communication example).
import [Link].*;
import [Link].*;
public class ThreadReadDemo
{
public static void main(String[] args)
{
Thread t1=new Thread(new MultiThread(),"A");
Thread t2=new Thread(new MultiThread(),"B");
[Link]();
[Link]();
}
}
class MultiThread implements Runnable
{
private static BufferedReader br = null;
private List<String> list;
static
{
try
{
br = new BufferedReader(new FileReader("D:/[Link]"),10);
}
catch (FileNotFoundException e)
{
[Link]();
}
}

public void run()


{
String line = null;
int count = 0;
while(true)
{
[Link] = new ArrayList<String>();
synchronized(br)
{
try
{
while((line = [Link]()) != null)
{
if(count<15)
{
[Link](line);
count++;
}
else
{
49
[Link](line);
count = 0;
break;
}
}
}
catch (IOException e)
{
[Link]();
}
}
try
{
[Link](1);
display([Link]);
}
catch (InterruptedException e)
{
[Link]();
}
if(line == null)
break;
}
}

public void display(List<String> list)


{
for(String str:list)
{
[Link](str);
}
}

}
Output:

50
D) Write a program to implement thread priority.

public class TestPriority extends Thread


{
public static void main(String args[])
{
TestPriority tp1 = new TestPriority();
TestPriority tp2 = new TestPriority();

[Link](Thread.MAX_PRIORITY-1);
[Link](Thread.MIN_PRIORITY+1);
[Link]("High");
[Link]("Less");
[Link]("High Priority is " + [Link]());
[Link]("Less Priority is " + [Link]());
[Link]();
[Link]();
}
public void run()
{
for(int i=0; i<10; i++)
{
[Link]([Link]() + ": " + i);
}
}
}

51
52
9) Design the user screen as follows and handle the events appropriately.
Add Window
First Number
Second Number
Result
ADD SUBTRACT

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

class AddSub extends Frame implements ActionListener


{
Label l1,l2,l3;
TextField t1,t2,t3;
JButton b1,b2;
AddSub()
{
super("Addition of two numbers");
setLayout(null);
setSize(500,400);
setVisible(true);
l1=new Label("Enter the first no:");
l2=new Label("Enter the second no:");
l3=new Label("Result:");
t1=new TextField();
t2=new TextField();
t3=new TextField();
b1=new JButton("ADD");
b2=new JButton("SUB");
[Link](100,50,120,20);
add(l1);
[Link](240,50,50,20);
add(t1);
[Link](100,80,130,20);
add(l2);
[Link](240,80,50,20);
add(t2);
[Link](240,110,50,20);
add(t3);
[Link](100,110,100,20);
add(l3);
[Link](200,150,70,50);
add(b1);
[Link](300,150,70,50);
add(b2);
[Link](this);
[Link](this);

53
addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
public void actionPerformed(ActionEvent ae)
{
float a,b,c;
if([Link]()==b1)
{
a=[Link]([Link]().trim());
b=[Link]([Link]().trim());
c=a+b;
[Link]([Link](c));
}
if([Link]()==b2)
{
a=[Link]([Link]().trim());
b=[Link]([Link]().trim());
c=a-b;
[Link]([Link](c));
}
}
public static void main(String s[])
{
AddSub ob=new AddSub();
}
}
Output:

54
10) Write a program to simulate a calculator.
import [Link].*;
import [Link].*;
class Calc implements ActionListener
{
JFrame f;
JTextField t;
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,b0,bdiv,bmul,bsub,badd,bdec,beq,bdel,bclr;

static double a=0,b=0,result=0;


static int operator=0;

Calc()
{
f=new JFrame("Calculator");
t=new JTextField();
b1=new JButton("1");
b2=new JButton("2");
b3=new JButton("3");
b4=new JButton("4");
b5=new JButton("5");
b6=new JButton("6");
b7=new JButton("7");
b8=new JButton("8");
b9=new JButton("9");
b0=new JButton("0");
bdiv=new JButton("/");
bmul=new JButton("*");
bsub=new JButton("-");
badd=new JButton("+");
bdec=new JButton(".");
beq=new JButton("=");
bdel=new JButton("Delete");
bclr=new JButton("Clear");

[Link](30,40,280,30);
[Link](40,100,50,40);
[Link](110,100,50,40);
[Link](180,100,50,40);
[Link](250,100,50,40);

[Link](40,170,50,40);
[Link](110,170,50,40);
[Link](180,170,50,40);
[Link](250,170,50,40);

[Link](40,240,50,40);
[Link](110,240,50,40);
[Link](180,240,50,40);
55
[Link](250,240,50,40);

[Link](40,310,50,40);
[Link](110,310,50,40);
[Link](180,310,50,40);
[Link](250,310,50,40);

[Link](60,380,100,40);
[Link](180,380,100,40);

[Link](t);
[Link](b7);
[Link](b8);
[Link](b9);
[Link](bdiv);
[Link](b4);
[Link](b5);
[Link](b6);
[Link](bmul);
[Link](b1);
[Link](b2);
[Link](b3);
[Link](bsub);
[Link](bdec);
[Link](b0);
[Link](beq);
[Link](badd);
[Link](bdel);
[Link](bclr);

[Link](null);
[Link](true);
[Link](350,500);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](false);

[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
56
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}

public void actionPerformed(ActionEvent e)


{
if([Link]()==b1)
[Link]([Link]().concat("1"));

if([Link]()==b2)
[Link]([Link]().concat("2"));

if([Link]()==b3)
[Link]([Link]().concat("3"));

if([Link]()==b4)
[Link]([Link]().concat("4"));

if([Link]()==b5)
[Link]([Link]().concat("5"));

if([Link]()==b6)
[Link]([Link]().concat("6"));

if([Link]()==b7)
[Link]([Link]().concat("7"));

if([Link]()==b8)
[Link]([Link]().concat("8"));

if([Link]()==b9)
[Link]([Link]().concat("9"));

if([Link]()==b0)
[Link]([Link]().concat("0"));

if([Link]()==bdec)
[Link]([Link]().concat("."));

if([Link]()==badd)
{
a=[Link]([Link]());
operator=1;
[Link]("");
}

if([Link]()==bsub)
{
57
a=[Link]([Link]());
operator=2;
[Link]("");
}

if([Link]()==bmul)
{
a=[Link]([Link]());
operator=3;
[Link]("");
}

if([Link]()==bdiv)
{
a=[Link]([Link]());
operator=4;
[Link]("");
}

if([Link]()==beq)
{
b=[Link]([Link]());

switch(operator)
{
case 1: result=a+b;
break;

case 2: result=a-b;
break;

case 3: result=a*b;
break;

case 4: result=a/b;
break;

default: result=0;
}

[Link](""+result);
}

if([Link]()==bclr)
[Link]("");

if([Link]()==bdel)
{
String s=[Link]();
[Link]("");
58
for(int i=0;i<[Link]()-1;i++)
[Link]([Link]()+[Link](i));
}
}

public static void main(String...s)


{
new Calc();
}
}

59
11) Write a Java program for handling mouse events and key events.

// demonstrate the mouse event handlers.


import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code="MouseEvents" width=300 height=100></applet>*/

public class MouseEvents extends Applet implements MouseListener, MouseMotionListener,MouseWheelListener {


String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse

public void init() {


addMouseListener(this);
addMouseMotionListener(this);
addMouseWheelListener(this);
}

// Handle mouse clicked.


public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}

// Handle mouse entered.


public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}

// Handle mouse exited.


public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}

// Handle button pressed.


public void mousePressed(MouseEvent me) {
60
// save coordinates
mouseX = [Link]();
mouseY = [Link]();
msg = "Down";
repaint();
}

// Handle button released.


public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = [Link]();
mouseY = [Link]();
msg = "Up";
repaint();
}

// Handle mouse dragged.


public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = [Link]();
mouseY = [Link]();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}

// Handle mouse moved.


public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + [Link]() + ", " + [Link]());
}

// Handle mouse wheel moved.


public void mouseWheelMoved(MouseWheelEvent me) {
// show status
showStatus("Mouse Wheel Moving at " + [Link]() + ", " + [Link]());
}

// Display msg in applet window at current X,Y location.


public void paint(Graphics g) {
[Link](msg, mouseX, mouseY);
}
}
Output:

61
// demonstrate some virtual key codes.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="KeyEvents" width=300 height=100></applet>*/
public class KeyEvents extends Applet implements KeyListener
{
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init()
{
addKeyListener(this);

public void keyPressed(KeyEvent ke)


{
showStatus("Key Down");
int key = [Link]();
switch(key) {
case KeyEvent.VK_PAGE_DOWN:
msg += "<PgDn>";
break;
case KeyEvent.VK_PAGE_UP:
msg += "<PgUp>";
break;
case KeyEvent.VK_LEFT:
msg += "<Left Arrow>";
break;
case KeyEvent.VK_UP:
msg += "<Up Arrow>";
62
break;
case KeyEvent.VK_DOWN:
msg += "<Down Arrow>";
break;
case KeyEvent.VK_9:
msg += "<Digit 9>";
break;
case KeyEvent.VK_RIGHT:
msg += "<Right Arrow>";
break;
}
repaint();
}

public void keyReleased(KeyEvent ke)


{
showStatus("Key Up");
}

public void keyTyped(KeyEvent ke)


{
msg += [Link]();
repaint();
}

// Display keystrokes.
public void paint(Graphics g)
{
[Link](msg, X, Y);
}
}

Output:

63
64
12) a) Write a program for handling window events.
import [Link].*;
import [Link].*;
class Myclass implements WindowListener
{
public void windowActivated(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowClosing(WindowEvent e)
{
[Link](0);
}
public void windowDeactivated(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowOpened(WindowEvent e){}
}
class MyFrame extends Frame
{
public static void main(String[] args)
{
MyFrame f = new MyFrame();
[Link]("My AWT Frame");
[Link](400,400);
[Link](true);
[Link](new Myclass());
}
}
Output:

65
b) Develop an applet that displays a simple message.
import [Link].*;
import [Link];
/* <applet code="SimpleApplet" width=300 height=50> </applet> */
public class SimpleApplet extends Applet
{
public void paint(Graphics g)
{
[Link] ("A Simple Applet",100, 100);
}
}
Output:

66
67
13) Develop a client that sends data to the server and also develop a server that sends data to the client (two
way communication)

import [Link].*;
import [Link].*;
class Client2
{
public static void main(String args[])throws Exception
{
Socket s=new Socket("localhost",777);
DataOutputStream dos=new DataOutputStream([Link]());

InputStream obj=[Link]();
BufferedReader br=new BufferedReader(new InputStreamReader(obj));
BufferedReader kb=new BufferedReader(new InputStreamReader([Link]));
String str,str1;
while(!(str=[Link]()).equals("exit"))
{
[Link](str+"\n");
str1=[Link]();
[Link](str1);
}
[Link]();
[Link]();
[Link]();
[Link]();
}
}

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

class Server2
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(777);
Socket s=[Link]();
[Link]("Connection Established\n");
OutputStream obj=[Link]();
PrintStream ps=new PrintStream(obj);
BufferedReader br=new BufferedReader(new InputStreamReader([Link]()));
BufferedReader kb=new BufferedReader(new InputStreamReader([Link]));
while(true)
{
String str,str1;
while((str=[Link]())!=null)
{
[Link](str);
str1=[Link]();
68
[Link](str1);
}

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

}
}

69
70
14) Develop a client server application in which client read a file name from the key board and send the file
name to the server, and server will read the file name from client and send the file contents to the client.

import [Link].*;
import [Link].*;
public class ContentsClient
{
public static void main( String args[ ] ) throws Exception
{
Socket sock = new Socket( "[Link]", 4000);

// reading the file name from keyboard. Uses input stream


[Link]("Enter the file name");
BufferedReader keyRead = new BufferedReader(new InputStreamReader([Link]));
String fname = [Link]();

// sending the file name to server. Uses PrintWriter


OutputStream ostream = [Link]( );
PrintWriter pwrite = new PrintWriter(ostream, true);
[Link](fname);
// receiving the contents from server. Uses input stream
InputStream istream = [Link]();
BufferedReader socketRead = new BufferedReader(new InputStreamReader(istream));

String str;
while((str = [Link]()) != null) // reading line-by-line
{
[Link](str);
}
[Link](); [Link](); [Link]();
}
}

import [Link].*;
import [Link].*;
public class ContentsServer
{
public static void main(String args[]) throws Exception
{ // establishing the connection with the server
ServerSocket sersock = new ServerSocket(4000);
[Link]("Server ready for connection");
Socket sock = [Link](); // binding with port: 4000
[Link]("Connection is successful and wating for chatting");

// reading the file name from client


InputStream istream = [Link]( );
BufferedReader fileRead =new BufferedReader(new InputStreamReader(istream));
String fname = [Link]( );
// reading file contents
71
BufferedReader contentRead = new BufferedReader(new FileReader(fname) );

// keeping output stream ready to send the contents


OutputStream ostream = [Link]( );
PrintWriter pwrite = new PrintWriter(ostream, true);

String str;
while((str = [Link]()) != null) // reading line-by-line from file
{
[Link](str); // sending each line to client
}

[Link](); [Link](); // closing network sockets


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

Programs Beyond the Syllabus

72
[Link] java programs to illustrate the scope of default ,private,protected and public access modifiers for
variables and methods in java..

Java program to illustrate private modifier


class A{
private int data=40;
private void msg(){[Link]("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
}}
Java program to illustrate default modifier

package pack;
class A{
void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
[Link]();//Compile Time Error
}
}

Java program to illustrate protected modifier

//save by [Link]
package pack;
public class A{
protected void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;

73
class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
}
Output:Hello

Java program to illustrate public modifier

//save by [Link]

package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Output:Hello

74
16) Write a java program to illustrate the usage of multiple catch blocks in java.
class MultipleCatchBlock {
public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Test it Now

Output:

Arithmetic Exception occurs


rest of the code

75
17) Develop a program for passing parameters to an Applet.

import [Link];
import [Link].*;
/* <APPLET CODE="HelloAppletMsg" width=500 height=400>
<PARAM NAME="Greetings" VALUE="Hello , How are you?">
</APPLET> */
public class HelloAppletMsg extends Applet {
String msg;
public void init()
{
msg = getParameter("Greetings");
if( msg == null)
msg = "Hello";
}
public void paint(Graphics g) {
[Link] (msg,10, 100);
}
}

76

Common questions

Powered by AI

Using an interface like "SortInterface" provides a contract for performing a sorting action without committing to a specific implementation method . Implementing this in classes like "SortImpl" allows for different sorting algorithms to be used interchangeably and tested without altering the interface. Such design promotes flexibility and code reuse. In the context of linear sorting, defining sort() in "SortImpl" provides a real-time application of a sorting algorithm suitable for small datasets, where simplicity and readability are prioritized over performance .

A Java program handling mouse and key events uses event-driven programming to determine the behavior of a component when certain actions occur. This involves implementing interfaces such as MouseListener, MouseMotionListener, and KeyListener . Each interface contains methods like mouseClicked(), mouseMoved(), keyPressed(), etc., which are overridden to define specific responses to those interactions. For instance, mouse event methods can be used to change component states or visualize changes when a mouse is clicked or moved. Similarly, key event methods can capture key presses for shortcuts or inputs. The program uses addKeyListener() and addMouseListener() methods to register events with components .

Implementing thread synchronization in the Account class entails using synchronized methods or blocks to control access to shared resources, such as balance amount, ensuring that only one thread can modify account balance at a time . This prevents race conditions during concurrent withdrawals, where multiple threads try to withdraw more money than available, and ensures thread safety by maintaining data consistency. The synchronized keyword ensures that the critical section of code managing withdrawals is executed by only one thread at a time .

Designing a client/server application for file exchange involves creating a client that reads the filename input by the user from the keyboard, sends that filename to the server, and a server that receives the filename, locates the file, and sends its contents back to the client . Sockets are used for the communication between client and server, with the server listening on a port and the client connecting to it. Once connected, the client uses output streams to send the filename, the server reads the filename using input streams, reads the file contents, and forwards the data back to the client, implementing a two-way communication system .

In defining a "Resister" class, the key elements include instance variables such as "resistance" and methods like "giveData()" for assigning data and "displayData()" for displaying data held by the resistance variable . The class has to be constructed with appropriate constructors. Then, subclasses like "SeriesCircuit" and "ParallelCircuit" are defined, extending the functionality with methods such as "calculateSeriesResistance()" and "calculateParallelResistance()", these methods should take two Resistor objects as arguments and return a Resistor object as a result .

To ensure the withdraw() method throws an "InsufficientFundException", incorporate a condition to check if the withdrawal would cause the balance to fall below the minimum required balance . If this condition is met, throw the custom exception "InsufficientFundException" signaling that the balance is insufficient. The code should look like 'if(balance - withdrawAmount < minimumBalance) throw new InsufficientFundException();' This requires defining the "InsufficientFundException" class, either extending Exception or RuntimeException depending on whether it should be checked or unchecked .

Method overriding in Java is demonstrated by creating a subclass that provides a specific implementation for a method already defined in its superclass. This allows polymorphism to be utilized, where a superclass reference is used to refer to a subclass object. The "super" keyword plays a crucial role in method overriding as it is used to refer to the immediate parent class object. It can be used to access parent class methods, constructors, and in some cases, fields .

Thread communication in Java can be implemented by having threads share data through a common object, often using synchronized methods or blocks. In this context, one thread reads a line of text from a file and notifies another thread to write that line to a different file . The concept involves producer-consumer problems where one thread acts as a producer (reading the file), and the other acts as a consumer (writing to a file). Java uses methods such as wait(), notify(), and notifyAll() to manage the communication between the threads and ensure smooth data transfer and synchronization .

An interface like "GeometricShape" is implemented in Java by defining it with abstract methods, such as "area()" and "perimeter()", which do not contain any method body . Classes like "Triangle", "Rectangle", and "Circle" can implement this interface, providing concrete implementations for these methods. The advantages include the capability to define a contract for what a class can do, without specifying how it does it, allowing for polymorphism. This design promotes loose coupling and enables a form of multiple inheritance, where one class can implement multiple interfaces .

A Java applet to display a simple message can be developed by creating a subclass of the Applet class and overriding the paint() method to draw text on the screen using Graphics.drawString() method . To display the applet, it must be embedded in an HTML page using the <applet> or <embed> tags. The benefits of applets include ease of use in embedding Java programs in web pages and providing interactive features on websites. However, applets have largely fallen out of favor due to security concerns and support being deprecated in modern browsers .

You might also like