You are on page 1of 89

GURU TEGH BAHADUR INSTITUTE OF TECHNOLOGY

(Affiliated To Guru Gobind Indraprastha University)

JAVA FILE

Submitted by:
Aryan Choudhary
01813203120
5th Semester (IT)

Page 1|
Aryan Choudhary
01813203120
Experiment 1
Aim: Design a java program to find the biggest of three given integers.
Source code:
import java.util.*;

class largest{
int num1,num2,num3,res;
void inputData(){
Scanner sc =new Scanner(System.in);
System.out.println("Enter three digit");
num1=sc.nextInt();
num2=sc.nextInt();
num3=sc.nextInt();
}
int findLargest(){
if(num1>num2 && num1>num3)
res = num1;
else if(num2>num1 && num2>num3)
res = num2;
else
res = num3;
return res;
}
void displayLargest(){
System.out.println("\nLargest= "+res);
}
}
Page 2|
Aryan Choudhary
01813203120
class Main{
public static void main(String args[])
{
largest l =new largest();
l.inputData();
l.findLargest();
l.displayLargest();
}
}

Page 3|
Aryan Choudhary
01813203120
Output:

Page 4|
Aryan Choudhary
01813203120
Experiment 2
Aim: Design a java program to define a class, describe its constructor,
over-load the constructor and instantiate the object.
Source code:
class Shapes
{
double len;
double bre;
double result;
Shapes()
{
len=0.0;
bre=0.0;
}
Shapes(double l)
{
len=l;
bre=0.0;
}
Shapes(double l, double b)
{
len=l;
bre=b;
}
void area()
{
if(len!=0.0 && bre==0.0)
{

Page 5|
Aryan Choudhary
01813203120
result=len*len;
System.out.println("AREA SQUARE " + result);
}
if(len!=0.0 && bre!=0.0)
{
result=len*bre;
System.out.println("AREA RECTANGLE " + result);
}
else if(len==0.0 && bre==0.0)
{
System.out.println("NO OUTPUT");
}
}
}
class MyELClass
{
public static void main(String a[])
{
double para1, para2;
para1=10.0;
para2=20.0;
Shapes s1=new Shapes();
Shapes s2=new Shapes(para1);
Shapes s3=new Shapes(para1,para2);
s2.area();
s3.area();
s1.area();
}

Page 6|
Aryan Choudhary
01813203120
Output:

Page 7|
Aryan Choudhary
01813203120
Experiment 3
Aim: Design a java program to demonstrate the use of nested class.

Source code:
class Outer
{
private int outer_x = 100;
void test()
{
Inner inner = new Inner();
inner.display();
inner.hello();
}
class Inner
{
private void hello()
{
System.out.println("Private Method Hello() of Inner Class");
}
void display()
{
System.out.println("Display: outer_x = " + outer_x);
Outer o=new Outer();
System.out.println("Display: outer_x = " + o.outer_x);
}
}
}
Page 8|
Aryan Choudhary
01813203120
class MyELClass
{
public static void main(String args[])
{
Outer outer = new Outer();
outer.test();
}
}

Page 9|
Aryan Choudhary
01813203120
Output:

P a g e 10 |
Aryan Choudhary
01813203120
Experiment 4
Aim: Design a java program to print all the real solutions of the quadratic
equation ax2+bx+c=0, read in the values of a,b,c and use the quadratic
equation formula. If the discriminant b2-4ac is negative, display a message
stating that there are no real solutions

Source code:

import java.util.*;

class Quadratic{
double a,b,c;
double r1,r2;
void inputEquation(){

Scanner sc = new Scanner(System.in);


System.out.println("Enter the values of a,b,c :");
a=sc.nextDouble();
b=sc.nextDouble();
c=sc.nextDouble();

void findRoot() {
double determinant = b*b-4*a*c;
if(determinant > 0) {
r1 = (-b + Math.sqrt(determinant)) / (2*a);
r2 = (-b - Math.sqrt(determinant)) / (2*a);
P a g e 11 |
Aryan Choudhary
01813203120
System.out.format("root1 = %.2f and root2 = %.2f",r1,r2); }
else if(determinant == 0) {
r1 =r2=-b/(2*a);
System.out.format("root1 = root2 = %.2f;", r1);}
else {
double realPart =-b/(2*a);
double imaginaryPart = Math.sqrt(-determinant) / (2*a);
System.out.format("root1 = %.2f+%.2fi and root2 = %.2f-%.2fi", realPart,
imaginaryPart,
realPart, imaginaryPart);
}
}
}
class Main{
public static void main(String args[]){
Quadratic q1=new Quadratic();
q1.inputEquation();
q1.findRoot();
}
}

P a g e 12 |
Aryan Choudhary
01813203120
Output:

P a g e 13 |
Aryan Choudhary
01813203120
Experiment 5
Aim: Design a java program that uses recursive method to print the nth
value of the Fibonacci series sequence
Source code:
import java.util.Scanner;

class Main
{
public static void main(String args[])
{
System.out.println("Enter the number n to print the faboniccs series ");
Scanner ob=new Scanner(System.in);
short a=ob.nextShort();
Series ob1=new Series();
long b=ob1.input(a);
System.out.println("The "+a+"th number of the faboniccs series is "+b);
}
}

class Series
{

int a=1;
int b=1;
int c=0;
int count;
int input(int a)
P a g e 14 |
Aryan Choudhary
01813203120
{
count=a;
count=fabo(count);
return count;
}

int fabo(int count)


{
if(count!=2)
{
c=a+b;
a=b;
b=c;
fabo(--count);
}
return c;
}
}

P a g e 15 |
Aryan Choudhary
01813203120
Output:

P a g e 16 |
Aryan Choudhary
01813203120
Experiment 6
Aim: Design a java program to prompt user for an integer and print all the
prime numbers up to that integer.
Source code:
import java.util.*;
class Prime
{
int value,num;
int i,flag;
void inputNumber()
{
Scanner sc = new Scanner(System.in);
System.out.println("ENTER A NUMBER ");
value = sc.nextInt();
}
void displayPrime()
{
for(num=2;num<=value;num++)
{
flag=0;
for(i=2;i<=num-1;i++)
{
if(num%i==0)
{
flag=1;
break;
}
}

P a g e 17 |
Aryan Choudhary
01813203120
if(flag==0)
{
System.out.println(num);
}
}
}
}
class MyELClass
{
public static void main(String a[])
{
Prime o=new Prime();
o.inputNumber();
o.displayPrime();
}
}

Output:

P a g e 18 |
Aryan Choudhary
01813203120
Experiment 7
Aim: Design a java program to check whether a string is palindrome or
not.
Source code:
import java.util.*;
class P_Check
{
void check(String data)
{
String rdata = "";
int i,len;
len = data.length();
for (i=len-1;i>=0;i--)
rdata = rdata + data.charAt(i);
if (data.equals(rdata))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}}
class MyELClass
{
public static void main(String a[])
{
String name;
P_Check pc=new P_Check();
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
name = in.nextLine();

P a g e 19 |
Aryan Choudhary
01813203120
pc.check(name);
}
}

Output:

P a g e 20 |
Aryan Choudhary
01813203120
Experiment 8
Aim: Design a java program that reads a line of integers, then display each
integer and the sum of all integers.
Source code:
import java.util.*;
class IntData
{
int arr[];
int i,sum;
IntData(int size)
{
arr = new int[size];
sum=0;
}
void input()
{
Scanner sc = new Scanner(System.in);
for(i=0;i<arr.length;i++)
{
arr[i] = sc.nextInt();
}
}
void display()
{
for(i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}

P a g e 21 |
Aryan Choudhary
01813203120
}
void sumCal()
{
for(i=0;i<arr.length;i++)
{
sum=sum+arr[i];
}
System.out.println("SUM IS "+sum);
}
}
class MyELClass
{
public static void main(String a[])
{
IntData obj=new IntData(5);
obj.input();
obj.display();
obj.sumCal();
}
}

P a g e 22 |
Aryan Choudhary
01813203120
Output:

P a g e 23 |
Aryan Choudhary
01813203120
Experiment 9
Aim: Design a java program to implement stack
Source Code:
class Stack
{
int stck[];
int tos;
Stack(int size)
{ stck =
new int[size];
tos = -1; }
void push(int item)
{ if(tos==stck.length-1)
System.out.println("Stack is full.");
else
stck[++tos] = item; }
int pop()
{ if(tos < 0)
{ System.out.println("Stack underflow.");
return 0; }
else
return stck[tos--];
}}
class MyELClass
{

P a g e 24 |
Aryan Choudhary
01813203120
public static void main(String args[])
{
Stack mystack1 = new Stack(5);
Stack mystack2 = new Stack(8);

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


mystack1.push(i);
for(int i=0; i<8; i++)
mystack2.push(i);

System.out.println("Stack in mystack1:");
for(int i=0; i<5; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<8; i++)
System.out.println(mystack2.pop());
}
}

P a g e 25 |
Aryan Choudhary
01813203120
Output:

P a g e 26 |
Aryan Choudhary
01813203120
Experiment 10
Aim: Design a java program to create an abstract class named Shape, that
contains an empty method called numberOfSides(). Provide four classes
named Trapezoid, Triangle, Rectangle and Hexagon such that each one of
the classes contains only the method numberOfSides(), that contains
number of sides in each geometrical figure.

Source code:
abstract class MyArea {
abstract void area();
}
class HEXArea extends MyArea {
double s;
void area() {
double areasq;
s=10.0;
areasq= (3*Math.sqrt(3)*s*s)/2;
System.out.println("Area of Square " + (float)areasq);
}
}
class RECTArea extends MyArea {
double l,b;
void area() {
double arearect;
l=10.0;
b=2.0;

P a g e 27 |
Aryan Choudhary
01813203120
arearect=l*b;
System.out.println("Area of Rectangle " + arearect);
}
}
class TRIArea extends MyArea {
double h,b;
void area() {
double areatri;
h=6.0;
b=4.0;
areatri = (h*b)/2;
System.out.println("Area of Triangle " + areatri);
}
}
class TRAPArea extends MyArea {
double h,a,b;
void area() {
double areatrap;
h=8.0;
a= 9.0;
b=10.0;
areatrap = ((a+b)/2)*h;
System.out.println("Area of Trapezoid " + areatrap);
}
}
class MyELClass {
public static void main(String a[]) {
MyArea sa=new HEXArea();

P a g e 28 |
Aryan Choudhary
01813203120
sa.area();
MyArea ra=new RECTArea();
ra.area();
MyArea tri=new TRIArea();
tri.area();
MyArea trap=new TRAPArea();
trap.area();
}
}

Output:

P a g e 29 |
Aryan Choudhary
01813203120
Experiment 11
Aim: Design a java program to show dynamic polymorphism.
Source code:
class MyArea
{
void area()
{
System.out.println("A concrete function called Area()");
}
}
class SQArea extends MyArea
{
double s;
void area() //Same name function in base class
{
double areasq;
s=10.0;
areasq=s*s;
System.out.println("Area of Square " + areasq);
}
}
class RECTArea extends MyArea
{
double l,b;
void area() //Same name function in base class

P a g e 30 |
Aryan Choudhary
01813203120
{
double arearect;
l=10.0;
b=2.0;
arearect=l*b;
System.out.println("Area of Rectangle " + arearect);
}
}
class MyELClass
{
public static void main(String a[])
{
MyArea ma; //Base class object
ma=new SQArea(); //Refering to SQArea
ma.area(); //Calling SQArea method (Dynamic Ploymorphism)
ma=new RECTArea(); //Refering to RECTArea
ma.area(); //Calling RECTArea method (Dynamic Ploymorphism)
}
}

P a g e 31 |
Aryan Choudhary
01813203120
Output:

P a g e 32 |
Aryan Choudhary
01813203120
Experiment 12
Aim: Design a java program to implement interfaces
Source code:
interface IntStack
{
void push(int item); //Store an item.
int pop(); //Retrieve an item.
}
class DynStack implements IntStack
{ private int stck[];
private int tos;
//Allocate and initialize stack.
DynStack(int size)
{
stck = new int[size];
tos = -1;
}
//Push an item onto the stack.
public void push(int item)
{ //If stack is full, allocate a larger stack.
if(tos==stck.length-1)
{
int temp[] = new int[stck.length * 2];
//Making a double size array.
for(int i=0; i<stck.length; i++)

P a g e 33 |
Aryan Choudhary
01813203120
temp[i] = stck[i];
stck = temp;
stck[++tos] = item;
}
else
stck[++tos] = item;
}

//Pop an item from the stack.


public int pop()
{
if(tos < 0)
{
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
}
class ELClass1
{
public static void main(String args[])
{
DynStack mystack1 = new DynStack(5);
DynStack mystack2 = new DynStack(8);
//These loops cause each stack to grow.
for(int i=0; i<12; i++)

P a g e 34 |
Aryan Choudhary
01813203120
mystack1.push(i);
for(int i=0; i<20; i++)
mystack2.push(i);
System.out.println("Stack in mystack1:");
for(int i=0; i<12; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<20; i++)
System.out.println(mystack2.pop());
}
}

P a g e 35 |
Aryan Choudhary
01813203120
0utput:

P a g e 36 |
Aryan Choudhary
01813203120
Experiment 13
Aim: Design a java program to create a customized exception and also
make use of all 5 exception keywords.
Source Code:
class NSalException extends Exception
{
public NSalException(String s)
{
super(s); //CALLING CONSTRUCTOR Exception()
}
}
class PSalException extends RuntimeException
{
public PSalException(String s)
{
super(s); //CALLING CONSTRUCTOR RuntimeException()
}
}
class Employee
{
public void decideSal(String s1) throws NSalException, PSalException,
NumberFormatException
{
int sal=Integer.parseInt(s1);
if(sal<=0)
{
NSalException no=new NSalException("Invalid Salary");
throw(no);

P a g e 37 |
Aryan Choudhary
01813203120
}
else
{
PSalException po=new PSalException("Valid Salary");
throw(po);
}
}}
class MyELClass
{
public static void main(String args[])
{
try
{
Employee e=new Employee();
e.decideSal(args[0]);
}
catch (NumberFormatException nfe)
{
System.err.println("Please enter integer values.");
}
catch (NSalException no)
{
System.err.println("Negative Salary.");
}
catch (PSalException po)
{
System.err.println("Valid Positive Salary.");
}

P a g e 38 |
Aryan Choudhary
01813203120
finally
{
System.out.println("Finally Block executing");
}
}
}
Output:

P a g e 39 |
Aryan Choudhary
01813203120
Experiment 14
Aim: Design a java program to sort list of names in ascending order.
Source code:
import java.util.*;
class SortNames
{
String name[]=new String[5];
int i,n=5;
SortNames()
{
for(i=0;i<n;i++)
{
name[i]=null;
}
}
void inputNames()
{
name[0]="Yogesh";
name[1]="Deepak";
name[2]="Aman";
name[3]="Srishti";
name[4]="Baljinder";
}
P a g e 40 |
Aryan Choudhary
01813203120
void bubbleSort()
{
int j;
String temp;
for(i=0;i<n;i++)
{ for(j=0;j<n-1-i;j++)
{ if(name[j].compareTo(name[j+1])>0)
{ temp=name[j];
name[j]=name[j+1];
name[j+1]=temp;
}
}
}}
void displayNames()
{
for(i=0;i<n;i++)
{
System.out.println(name[i]);
}
}
}
class MyELClass
{
public static void main(String a[])
{
SortNames sn=new SortNames();
sn.inputNames();
sn.bubbleSort();

P a g e 41 |
Aryan Choudhary
01813203120
sn.displayNames();
}
}

Output:

P a g e 42 |
Aryan Choudhary
01813203120
Experiment 15
Aim: Design a java program to create two threads: one for odd numbers
and other for even numbers.
Source code:
class EvenThread extends Thread
{
int num;
void set()
{
this.num=0;
}
public void run()
{
for(int i=1;i<=10;i++)
{
try
{
even();
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println("INTERRUPTED EXCEPTION ");
}
}
}
void even()
{

P a g e 43 |
Aryan Choudhary
01813203120
num=num+2;
System.out.println("Even : "+num);
}
}
class OddThread implements Runnable
{
int num;
void set()
{
this.num=1;
}
public void run()
{
for(int i=1;i<=10;i++)
{
try
{
odd();
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println("INTERRUPTED EXCEPTION ");
}
}
}
void odd()
{

P a g e 44 |
Aryan Choudhary
01813203120
num=num+2;
System.out.println("Odd : "+num);
}
}
class JavaLab
{
public static void main(String a[])
{
int i;
EvenThread et=new EvenThread();
OddThread ot=new OddThread();
Thread t=new Thread(ot);
et.set();
ot.set();
et.start();
t.start();
}
}

P a g e 45 |
Aryan Choudhary
01813203120
Output:

P a g e 46 |
Aryan Choudhary
01813203120
Experiment 16
Aim: Design a java program to implement producer consumer problem
using concept of inter thread communication.
Source code:
class Q
{
int n;
boolean valueSet = false;
synchronized int get()
{
while(valueSet==false)
try
{ wait(); }
catch(InterruptedException e)
{ System.out.println("InterruptedException caught"); }
System.out.println("Got by Consumer: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n)
{
while(valueSet==true)
try
{ wait(); }
catch(InterruptedException e)
{ System.out.println("InterruptedException caught"); }
this.n = n;

P a g e 47 |
Aryan Choudhary
01813203120
valueSet = true;
System.out.println("Put by Producer: " + n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{ this.q = q;
new Thread(this, "Producer").start();
}
public void run()
{ int i = 0;
while(true)
{ q.put(i++); }
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{ this.q = q;
new Thread(this, "Consumer").start();
}
public void run()
{ while(true)
{

P a g e 48 |
Aryan Choudhary
01813203120
q.get();
}
}
}
class MyELClass
{
public static void main(String args[])
{
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}

Output:

P a g e 49 |
Aryan Choudhary
01813203120
Experiment 17
Aim: Design a java program to create three threads runnable interface.
First thread display “GOOD MORNING” at every 1 second. Second
thread displays “HELLO” at every 2 seconds and third thread displays
“WELCOME” at every 3 seconds.
Source code:
class Callme
{ void call(String msg, int t)
{ System.out.println(msg);
try
{ Thread.sleep(t*1000); }
catch (InterruptedException e)
{ System.out.println("Interrupted"); }
}
}
class Caller implements Runnable
{
String msg;
int time;
Callme target;
Thread t;
public Caller(Callme targ, String s, int et)
{
target = targ;
msg = s;
time=et;
t = new Thread(this);
t.start();
P a g e 50 |
Aryan Choudhary
01813203120
}
public void run()
{
int i;
for(i=1;i<=5;i++)
{
synchronized(target)
{
target.call(msg,time);
}
}}
}

class MyELClass
{
public static void main(String args[])
{
Callme target = new Callme();
Caller ob1 = new Caller(target, "GOOD MORNING",1);
Caller ob2 = new Caller(target, "HELLO",2);
Caller ob3 = new Caller(target, "WELCOME",3);
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)

P a g e 51 |
Aryan Choudhary
01813203120
{
System.out.println("Interrupted");
}
}
}

Output:

P a g e 52 |
Aryan Choudhary
01813203120
Experiment 18
Aim: Design a java program to create three threads. First thread display
“GOOD MORNING” at every 1 second. Second thread displays “HELLO”
at every 2 seconds and third thread displays “WELCOME” at every 3
seconds
Source code:
import java.util.*;
public class Hal extends Thread
{
public void run()
{
for(int i=1;i<6;i++)
{
try
{
Thread.sleep(1000);
System.out.println("Good Morning");
Thread.sleep(2000);
System.out.println("Hello");
Thread.sleep(3000);
System.out.println("Welcome");
}catch(Exception e)
{
System.out.println(e);
}
}
}
public static void main(String[] args)
{
P a g e 53 |
Aryan Choudhary
01813203120
Hal h = new Hal();
h.start();

}
}
Output:

P a g e 54 |
Aryan Choudhary
01813203120
Experiment 19
Aim: Design an applet to do the following tasks:
a) To output the question “WHO IS THE PRIME MINISTER OF
INDIA?”
b) To accept the answer and print “CORRECT” and then stop if the
answer is correct.
c) To print “TRY AGAIN” and if the answer is not correct.
d) To display the correct answer, if the answer is wrong even after third
attempt.
Source code:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/* <applet code=MyELClass width=600 height=600></applet> */
public class MyELClass extends Applet implements ActionListener
{
String ans="";
Button sub;
TextField tf1;
int count=0;
public void init()
{
Label f=new Label("ENTER PRIME MINISTER NAME", Label.RIGHT);
tf1=new TextField(10);
add(f);
add(tf1);
sub=new Button("SUBMIT");
add(sub);

P a g e 55 |
Aryan Choudhary
01813203120
sub.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String name=tf1.getText();
if(ae.getSource()==sub)
{
if(name.equals("Narendra Modi"))
{
ans="CORRECT";
sub.setEnabled(false);
}
else
{
ans="INCORRECT";
count++;
if(count==3)
{
ans="NAME OF PRIME MINISTER IS Sh. NARENDRA MODI";
}
}
}
repaint();
}
public void paint(Graphics g)
{
g.drawString(ans,10,100);
}}

P a g e 56 |
Aryan Choudhary
01813203120
Output:

P a g e 57 |
Aryan Choudhary
01813203120
Experiment 20
Aim: Design a java program to write an applet that computes the payment
of loan which is based on the amount of loan, interest rate and number of
months. It takes one parameter from browser which is called Monthly
Rate. If it is True then interest rate is per month else it is annual. (Use
label, textfield, button, check box, checkbox group)
Source code:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/* <applet code=prog20 width=150 height=150></applet>
<param name=N1 value=5>
*/
public class prog20 extends Applet implements ItemListener, ActionListener
{
String s1;
Int n1;
TextField tf1,tf2;
Button result;
Checkbox cb1,cb2;
CheckboxGroup cbg;
public void init()
{
Label f=new Label("ENTER AMOUNT OF LOAN", Label.RIGHT);
Label s=new Label("ENTER INTEREST RATE", Label.RIGHT);
tf1=new TextField(4);
tf2=new TextField(4);
add(f);
add(tf1);

P a g e 58 |
Aryan Choudhary
01813203120
add(s);
add(tf2);
cbg=new CheckboxGroup();
cb1=new Checkbox("MONTHLY RATE",cbg,true);
cb2=new Checkbox("YEARLY RATE",cbg,false);
result=new Button("LOAN PAYMENT AMOUNT");
add(cb1);
add(cb2);
add(result);
cb1.addItemListener(this);
cb2.addItemListener(this);
result.addActionListener(this);
s1=getParameter("N1");
if(s1!=null)
{
n1=Integer.parseInt(s1);
}
}

P a g e 59 |
Aryan Choudhary
01813203120
Output:

P a g e 60 |
Aryan Choudhary
01813203120
Experiment 21
Aim: Design a java program to write an applet with following AWT
components : textarea and button.
Source code:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code=MyELClass width=300 height=300> </applet>*/
public class MyELClass extends Applet implements ActionListener
{
String msg="";
String data="";
Button select;
TextArea ta;
public void init()
{
data="COUNTRY NAME: INDIA\n" + "CAPITAL NAME: DELHI\n" +
"STATE NAME: DELHI";
ta=new TextArea(data,5,30);
add(ta);
select=new Button("SELECT");
add(select);
select.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==select)
{

P a g e 61 |
Aryan Choudhary
01813203120
msg=ta.getSelectedText();
}
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,10,150);
}
}
Output:

P a g e 62 |
Aryan Choudhary
01813203120
Experiment 22
Aim: Design a java program to write an calculator applet. Use grid layout to
arrange the buttons for digits and for the +,-,*,/,% operations. Add textfield
to display the result.
Source code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/* <applet code=prog22 width=300 height=300></applet>*/
public Class22 extends Applet implements ActionListener
{
String s,s1,s2,s3,s4;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;
Button add,sub,eq,cl,mul,div,rem;
TextField t1;
int a,b,c;
public void init()
{
t1=new TextField(10);
b1=new Button("1");
b2=new Button("2");
b3=new Button("3");
b4=new Button("4");
b5=new Button("5");
b6=new Button("6");
b7=new Button("7");
b8=new Button("8");
b9=new Button("9");

P a g e 63 |
Aryan Choudhary
01813203120
b0=new Button("0");
add=new Button("+");
sub=new Button("-");
mul=new Button("*");
div=new Button("/");
eq=new Button("=");
cl=new Button("Clear");
rem=new Button("%");
GridLayout gb=new GridLayout(4,5);
setLayout(gb);
add(t1);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
add(b7);
add(b8);
add(b9);
add(b0);
add(add);
add(sub);
add(mul);
add(div);
add(rem);
add(eq);
add(cl);

P a g e 64 |
Aryan Choudhary
01813203120
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b0.addActionListener(this);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
eq.addActionListener(this);
cl.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
s=ae.getActionCommand();
if(s.equals("0") || s.equals("1") || s.equals("2") || s.equals("3") ||
s.equals("4") || s.equals("5") || s.equals("6") || s.equals("7") || s.equals("8") ||
s.equals("9") )
{s1=t1.getText() +s;
t1.setText(s1);
}
if(s.equals("+"))
{
P a g e 65 |
Aryan Choudhary
01813203120
s2=t1.getText();
t1.setText("");
s3="+";
}
if(s.equals("-"))
{
s2=t1.getText();
t1.setText("");
s3="-";
}
if(s.equals("*"))
{s2=t1.getText();
t1.setText("");
s3="*";
}
if(s.equals("/"))
{s2=t1.getText();
t1.setText("");
s3="/";
}
if(s.equals("%"))
{
s2=t1.getText();
t1.setText("");
s3="%";
}
if(s.equals("="))
{

P a g e 66 |
Aryan Choudhary
01813203120
s4=t1.getText();
a=Integer.parseInt(s2);
b=Integer.parseInt(s4);
if(s3.equals("+"))
{
c=a+b;
}
if(s3.equals("-"))
{c=a-b;
}
if(s3.equals("*"))
{c=a*b;
}
if(s3.equals("/"))
{
c=a/b;
}
if(s3.equals("%"))
{c=a%b;
}
t1.setText(String.valueOf(c));
}
if(s.equals("Clear"))
{
t1.setText("");
}
}
public void textValueChanged(TextEvent e){}

P a g e 67 |
Aryan Choudhary
01813203120
}

Output:

P a g e 68 |
Aryan Choudhary
01813203120
Experiment 23
Aim: Design a java program to handle keyboard events
Source code:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code="ELClass1" width=400 height=200> </applet>*/
public class ELClass1 extends Applet implements KeyListener
{
String data="";
int x,y,px,py;
public void init()
{
addKeyListener(this);
px=0;
py=0;
x=px;
y=py;
}
public void keyPressed(KeyEvent k)
{
int code=k.getKeyCode();
if(code==KeyEvent.VK_LEFT)
{ x--; }
if(code==KeyEvent.VK_RIGHT)
{ x++; }

P a g e 69 |
Aryan Choudhary
01813203120
if(code==KeyEvent.VK_UP)
{ y--; }
if(code==KeyEvent.VK_DOWN)
{ y++; }
Graphics g=getGraphics();
g.drawLine(px,py,x,y);
px=x;
py=y;
}
public void keyTyped(KeyEvent k){}
public void keyReleased(KeyEvent k){}
}
Output:

P a g e 70 |
Aryan Choudhary
01813203120
Experiment 24
Aim: Design a program to Implement card layout in applets.
Source code:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code=MyELClass width=650 height=100></applet>*/
public class MyELClass extends Applet implements ItemListener,ActionListener
{
Panel main,P1,P2; CardLayout cl;
String ans="";
Button plus,sub,mul,div; Checkbox cb1,cb2;
CheckboxGroup cbg; TextField tf1,tf2;
public void init()
{
cl=new CardLayout();
main=new Panel();
main.setLayout(cl);
Label f=new Label("ENTER FIRST NUMBER");
Label s=new Label("ENTER SECOND NUMBER");
tf1=new TextField(4);
tf2=new TextField(4);
cbg=new CheckboxGroup();
cb1=new Checkbox("ADDITION/SUBTRACTION",cbg,false);
cb2=new Checkbox("MULTIPLICATION/DIVISION",cbg,false);
add(f);
add(tf1);
add(s);

P a g e 71 |
Aryan Choudhary
01813203120
add(tf2);
add(cb1);
add(cb2);
plus=new Button("ADDITION");
sub=new Button("SUBTRACTION");
mul=new Button("MULTIPLICATION");
div=new Button("DIVISION");
P1=new Panel();
P1.add(plus);
P1.add(sub);
P2=new Panel();
P2.add(mul);
P2.add(div);
add(main);
main.add(P1,"as");
main.add(P2,"md");
plus.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
cb1.addItemListener(this);
cb2.addItemListener(this);
}
public void actionPerformed(ActionEvent ae)
{
//THIS METHOD IS LEFT BLANK, SINCE WE ARE DISCUSSING LAYOUT.
//STUDENT MUST DEFINE THIS FUNCTION.
}

P a g e 72 |
Aryan Choudhary
01813203120
public void itemStateChanged(ItemEvent ie)
{
if(cb1.getState()==true)
{ cl.show(main,"as"); }
if(cb2.getState()==true)
{ cl.show(main,"md"); }
repaint();
}
public void paint(Graphics g)
{ g.drawString(ans,10,100); }
}
Output:

P a g e 73 |
Aryan Choudhary
01813203120
Experiment 25
Aim: Program In Java To Demonstrate FileWriter, FileReader,
BufferedReader classes to Enter Multiple Strings And Numbers Into A
File, Read File Using Loop And Display.
Source code:
import java.io.*;
class MyELClass
{
public static void main(String s[])throws IOException
{
String name; int roll;
FileWriter fw=new FileWriter("Demo1.txt");
name="AMIT\n"; roll=11;
fw.write(name); fw.write(roll);
name="BANEET\n"; roll=12;
fw.write(name); fw.write(roll);
name="CHARAN\n"; roll=13;
fw.write(name); fw.write(roll);
name="DEEP\n"; roll=14;
fw.write(name); fw.write(roll);
fw.close();
FileReader fr=new FileReader("Demo1.txt");
BufferedReader br=new BufferedReader(fr);
while((name=br.readLine()) != null)
{
roll=br.read();
System.out.println(name + " " + roll);
}
br.close();
P a g e 74 |
Aryan Choudhary
01813203120
fr.close();
}
}
Output:

P a g e 75 |
Aryan Choudhary
01813203120
Experiment 26
Aim: Program to implement various functions giving details about a file
Source code:
import java.io.File;
import java.text.SimpleDateFormat;
class MyELClass
{
static void p(String s)
{
System.out.println(s);
}
public static void main(String args[])
{
File f1 = new File("D:/JAVA_TESTING.txt");
p("File Name: " + f1.getName());
p("Path: " + f1.getPath());
p("Abs Path: " + f1.getAbsolutePath());
p("Parent: " + f1.getParent());
p(f1.exists() ? "exists" : "does not exist");
p(f1.canWrite() ? "is writeable" : "is not writeable");
p(f1.canRead() ? "is readable" : "is not readable");
p("is " + (f1.isDirectory() ? "" : "not" + " a directory"));
p(f1.isFile() ? "is normal file" : "path");

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");


p("File last modified: " + sdf.format(f1.lastModified()));
p("File size: " + f1.length() + " Bytes");

P a g e 76 |
Aryan Choudhary
01813203120
}
}
Output:

P a g e 77 |
Aryan Choudhary
01813203120
Experiment 27
Aim:
Aim: Design a program in java to implement client-server TCP\IP socket
application which exchange strings among them
Source code:

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

class Client {
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
public Client(String address, int port)
{ // establish a connection
try {
socket = new Socket(address, port);
System.out.println("Connected");
input = new DataInputStream(System.in);
out = new DataOutputStream(socket.getOutputStream());
} catch (UnknownHostException u)
{
System.out.println(u);
}
catch (IOException i)
{
System.out.println(i);
}
String line = "";

P a g e 78 |
Aryan Choudhary
01813203120
while (!line.equals("Over")) {
try {
line = input.readLine();
out.writeUTF(line);
} catch (IOException i) {
System.out.println(i);}}
try {
input.close();
out.close();
socket.close();
} catch (IOException i) {
System.out.println(i);
}
}
public static void main(String args[]) {
Client client = new Client("127.0.0.1", 5000);
}
}
Output:

P a g e 79 |
Aryan Choudhary
01813203120
P a g e 80 |
Aryan Choudhary
01813203120
Experiment 28
Aim: Program In Java To Make Database Connectivity Using JDBC,
create statement object, create resultset object And Display (All Or Specific
Records using first(), last(), previous(), next() and absolute() functions).
(Pre requirements: install MySql software, create database: Shiksha, create
table house with attributes as H_No, H_Locality, H_Rooms, H_Owner,
insert rows of data into table house)
Source code:
import java.sql.*;
public class MyJDBC {
public static void main(String[] args) throws SQLException
{ Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/prog28","root","password");
Statement statement =
connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet resultSet = statement.executeQuery("select * from shiksha");
while(resultSet.next()) {
System.out.println(resultSet.getString("H_No") + "\t" +
resultSet.getString("H_Locality") + "\t" + resultSet.getString("H_Rooms") + "\t" +
resultSet.getString("H_Owner"));
}
System.out.println();
resultSet.first();
while(resultSet.next()) {
System.out.println(resultSet.getString("H_No") + "\t" +
resultSet.getString("H_Locality") + "\t" + resultSet.getString("H_Rooms") + "\t" +
resultSet.getString("H_Owner"));
}
System.out.println();
while(resultSet.previous())
{

P a g e 81 |
Aryan Choudhary
01813203120
System.out.println(resultSet.getString("H_No") + "\t" +
resultSet.getString("H_Locality") + "\t" + resultSet.getString("H_Rooms") + "\t" +
resultSet.getString("H_Owner"));
}
resultSet.absolute(1);
System.out.println();
System.out.println(resultSet.getString("H_No") + "\t" + resultSet.getString("H_Locality") + "\t" +
resultSet.getString("H_Rooms") + "\t" + resultSet.getString("H_Owner"));
resultSet.last();
System.out.println();
System.out.println(resultSet.getString("H_No") + "\t" + resultSet.getString("H_Locality")
+ "\t" + resultSet.getString("H_Rooms") + "\t" + resultSet.getString("H_Owner"));
}
}

Output:

P a g e 82 |
Aryan Choudhary
01813203120
Experiment 29
Aim: Program In Java To Make Database Connectivity Using JDBC,
create statement object,
create resultset object, insert a record using prepared statement and
Display all records.
(Pre requirements: install MySql software, create database: Shiksha, create
table house with
attributes as H_No, H_Locality, H_Rooms, H_Owner, insert rows of data
into table house)
Source code:
import java.sql.*;
public class MyJDBC {
public static void main(String[] args) throws SQLException {
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/prog29","root","password");
Statement statement =
connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR
_UPDA
TABLE);
ResultSet resultSet = statement.executeQuery("select * from shiksha");
while(resultSet.next()) {
System.out.println(resultSet.getString("H_No") + "\t" +
resultSet.getString("H_Locality") + "\t" + resultSet.getString("H_Rooms") + "\t" +
resultSet.getString("H_Owner"));
}
//Prog 29
String q = "insert into shiksha(H_No,H_Locality,H_Rooms,H_Owner) values (?,?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(q);
preparedStatement.setInt(1,4);

P a g e 83 |
Aryan Choudhary
01813203120
preparedStatement.setString(2,"Dwarka");
preparedStatement.setInt(3,1);
preparedStatement.setString(4,"Sarthak");
preparedStatement.executeUpdate();
resultSet = statement.executeQuery("select * from shiksha");
resultSet.absolute(0);
System.out.println();
while(resultSet.next()) {
System.out.println(resultSet.getString("H_No") + "\t" +
resultSet.getString("H_Locality") + "\t" + resultSet.getString("H_Rooms") + "\t" +
resultSet.getString("H_Owner"));
}
}
}
Output:

P a g e 84 |
Aryan Choudhary
01813203120
Experiment-30
Aim: Program In Java To Make Database Connectivity Using
JDBC, create statement object, create resultset object, update
a record based on H_No and Display all records.
(Prerequirements: install MySql software, create database:
Shiksha, create table house with attributes as H_No, H_Locality,
H_Rooms, H_Owner, insert rows of data into table house)
Source code:
import java.sql.*;
public class MyJDBC {
public static void main(String[] args) throws SQLException {
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/prog29","root","password");
Statement statement =
connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR
_UPDA
TABLE);
ResultSet resultSet = statement.executeQuery("select * from shiksha");
while(resultSet.next()) {
System.out.println(resultSet.getString("H_No") + "\t" +
resultSet.getString("H_Locality") + "\t" + resultSet.getString("H_Rooms") + "\t" +
resultSet.getString("H_Owner"));
}
String q = "update shiksha set H_Owner=? where H_Locality=?";
PreparedStatement preparedStatement = connection.prepareStatement(q);
preparedStatement.setString(1,"Yogesh");
preparedStatement.setString(2,"Dwarka");
preparedStatement.executeUpdate();

P a g e 85 |
Aryan Choudhary
01813203120
resultSet = statement.executeQuery("select * from shiksha");
resultSet.absolute(0);
System.out.println();
while(resultSet.next()) {
System.out.println(resultSet.getString("H_No") + "\t" +
resultSet.getString("H_Locality") + "\t" + resultSet.getString("H_Rooms") + "\t" +
resultSet.getString("H_Owner"));
}
}
}

Output:

P a g e 86 |
Aryan Choudhary
01813203120
Experiment 31
Aim: Program In Java To Make Database Connectivity Using JDBC,
create statement object,
create resultset object, delete a record based on H_No and Display all
records. (Pre
requirements: install MySql software, create database: Shiksha, create
table house with
attributes as H_No, H_Locality, H_Rooms, H_Owner, insert rows of data
into table house)
source Code:
import java.sql.*;
public class MyJDBC {
public static void main(String[] args) throws SQLException {
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/prog29","root","password");
Statement statement =
connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR
_UPDA
TABLE);
ResultSet resultSet = statement.executeQuery("select * from shiksha");
while(resultSet.next()) {
System.out.println(resultSet.getString("H_No") + "\t" +
resultSet.getString("H_Locality") + "\t" + resultSet.getString("H_Rooms") + "\t" +
resultSet.getString("H_Owner"));
}
//Prog31
String q = "delete from shiksha where H_No = ?";
PreparedStatement preparedStatement = connection.prepareStatement(q);
preparedStatement.setInt(1,4);

P a g e 87 |
Aryan Choudhary
01813203120
preparedStatement.executeUpdate();
resultSet = statement.executeQuery("select * from shiksha");
resultSet.absolute(0);
System.out.println();
while(resultSet.next()) {
System.out.println(resultSet.getString("H_No") + "\t" +
resultSet.getString("H_Locality") + "\t" + resultSet.getString("H_Rooms") + "\t" +
resultSet.getString("H_Owner"));
}
}
}
Output:

P a g e 88 |
Aryan Choudhary
01813203120
P a g e 89 |
Aryan Choudhary
01813203120

You might also like