JAVA Practical File

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 97

JAVA PROGRAMMING

PRACTICAL FILE

Department Of Computer Science And Applications


Kurukshetra University , Kurukshetra

Submitted By- Shweta Goel Submitted To-


Course- MCA(1st Semester) DR. CHANDER KANT VERMA
Roll no.- 03
MCA(20-16) Lab Based On MCA(20-11)

Page 1
4

7-8

9-10

11-14

15-16

17-18
19-
21
22

23-24

25-29

3039

40-41

42-44

45-46

47-51

52-55

Page 2
Page

56-59
56-59

60-62

63-64

65-67

68-69

70-73

74-83

84-85

86-87

88-90

91-93

94-98

Page 3
PROGRAM 1.

WAP to find the sum of 10 numbers, entered as command


line arguments.

public class ShwetaProgram1 {


public static void main(String args[]) {
int i;
int sum=0;
for(i=0;i<10;i++) {
sum=sum+ Integer.parseInt(args[i]);
}
System.out.println("sum is :" +sum) ;
}
}

Page 4
PROGRAM 2.

WAP that take two numbers as input from command line in-
terface and display their sum.

public class ShwetaProgram2 {


public static void main(String args[]) {
int a,b,sum;
a= Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
sum=a+b;
System.out.println("Sum of two integers are: "+ sum);
}
}

Page 5
PROGRAM 3.

WAP to find the area of rectangle using objects.

class Rectangle
{
int l,b;
}
class ShwetaProgram3
{
public static void main (String args[])
{
int area;
Rectangle rect = new Rectangle(); // rect is object of class
rect.l=20; // Rectangle
rect.b=60;
area=rect.l*rect.b;
System.out.println("Area of Rectangle is : "+area);
}
}

Page 6
PROGRAM 4.

WAP to find the area of rectangle using constructor.

class ShwetaRectangleCons
{
int area,length,breadth;
ShwetaRectangleCons(int l, int b) //parameterized CONSTRUCTOR
{
length=l;
breadth=b;
}
void areaa() //For Area Calculation
{
area=length*breadth;
System.out.println(area);
}
public static void main(String args[ ])
{
ShwetaRectangleCons r1=new ShwetaRectangleCons(15,15); //PA-
RAMETERIZED CONSTRUCTOR

System.out.println("Area of rectangle with parameterized constructor


is: ");
r1.areaa( );
}
}

Page 7
Page 8
PROGRAM 5.

WAP to find the area of rectangle and area of square using


function overloading .

/* Java program to find the area of the rectangle and Area of square
using Method Overloading
Method overloading allows different methods to have the same
name, but different signatures where the signature can differ by the
number of input parameters or type of input parameters or both. */

import java.io.*;
class Rectangle {
// Overloaded Area() function to
// calculate the area of the rectangle
// It takes two double parameters
void Area(double L, double B)
{
System.out.println("Area of the rectangle: "
+ L * B);
}
// Overloaded Area() function to
// calculate the area of the Square.
// It takes one double parameter
void Area(double S)
{
System.out.println("Area of the Square: "
+ S * S);

Page 9
}
}
public class ShwetaOverloading {
// Driver code
public static void main(String[] args)
{
// Creating object of Rectangle class
Rectangle obj = new Rectangle();
// Calling function
obj.Area(20.5, 10);
obj.Area(5.5);
}
}

PROGRAM 6A.

Page 10
WAP to find the area of rectangle using single inheritance .

//Single Inheritance To Find Area Of Rectangle

class Dimensions
{
int length;
int breadth;
}

class Rectanglee extends Dimensions


{
int a;
void area()
{
a = length * breadth;
}

}
public class ShwetaSingleInheritence
{
public static void main(String args[])
{
Rectanglee Rect = new Rectanglee();
Rect.length = 7;
Rect.breadth = 16;
Rect.area();
System.out.println("The Area of rectangle of length "
+Rect.length+" and breadth "+Rect.breadth+" is "+Rect.a);
}
}

Page 11
Page 12
PROGRAM 6B.

WAP to find the area of rectangle using Multilevel


Inheritance .

class Data
{
int length,breadth,height,area,volume;
public void input(int l, int b)

{
length = l;
breadth = b;
}
}

class Area extends Data


{
public void calculateArea()
{
area = length*breadth;
}
}

class Print extends Area


{
public int printArea() {
return area;
}
}
public class ShwetaMultilevel{

Page 13
public static void main(String args[])
{
Print p = new Print();

//Take input

p.input(5,15);
p.calculateArea();
int ans = p.printArea();
System.out.println("Area of rectangle = "+ans);
}
}

Page 14
PROGRAM 7.

WAP to find the area of rectangle and circle using interface.

// An interface is a completely "abstract class" that is used to group re-


lated methods with empty bodies
// Abstract class is that class which have atleast 1 Function undefined,
And interface has all function undefined so interface is a complete Ab-
stract class.
// Interface specify what a class must do. It does not specifies "How" to
do it.

interface area
{
double pi = 3.14;
double calc(double x,double y); //interface method (does not
have a body)
}
class rectangleee implements area // Here child class implements the
parent class rather then extending. It promise to provide the method
definition that provide by interface
{
public double calc(double x,double y)
{
return(x*y);
}
}
class circle implements area
{
public double calc(double x,double y)

Page 15
{
return(pi*x*x);
}
}
public class ShwetaInterface
{
public static void main(String arg[])
{
rectangleee r = new rectangleee();
circle c = new circle();
System.out.println("\nArea of Rectangle is : " +r.calc(10,20));

System.out.println("\nArea of Circle is : " +c.calc(15,15));


}
}

PROGRAM 8.

Page 16
WAP to handle the Exception using try and multiple catch
blocks and a finally block.

import java.io.*;
import java.util.*;

public class ShwetaExceptionTcf {


public static void main (String[] args) {
try{
Scanner sc= new Scanner(new File("test.in"));

/*Read file test.in which is not present It will throw an exception File
not found exception. */

System.out.println("Exit main()");
//This will not execute as after throwing excep-
tion we came of try block
}
catch(FileNotFoundException ex) //Exception matches
{
System.out.println("File not Found caught"); //line executed
}
catch(ArrayIndexOutOfBoundsException e) // will not execute
{

System.out.println("Insufficient nos.");
}
finally // Finally block will execute in every condition

Page 17
{

System.out.println("finally-block runs regardless of the state of


exception");
}
// After finally life goes on
System.out.println("After try-catch-finally, life goes on");
}
}

PROGRAM 9.

WAP to handle the user defined Exception.

Page 18
import java.io.*;
import java.util.*;
class InvalidBalanceException extends Exception
{
public InvalidBalanceException(String message)
{
super(message);
}
}
class UserDefinedException{
public static void main (String[] args) {
int balance;
try
{
balance = Integer.parseInt(args[0]);
updateBalance(balance);
}
catch(InvalidBalanceException ex)
{
System.out.println("Caught in catch of InvalidBalanceException");
ex.printStackTrace();
}
catch(NumberFormatException ex)
{
System.out.println("Caught in catch of NumberFormatExcep-
tion");
}
catch(ArrayIndexOutOfBoundsException ex)
{
System.out.println("Caught in catch of ArrayIndexOutOfBound-
sException");

Page 19
}
catch(Exception ex)
{
System.out.println("Caught in catch of Parent Exception");
}
System.out.println("Main method executed successfully");
}

public static void updateBalance(int number)throws InvalidBalanceEx-


ception
{
if(number < 0)
{
throw (new InvalidBalanceException("Account balance cannot
be less than Zero."));
}

System.out.println("No exception occured in updateBalance()


method");
}
}

Page 20
Page 21
PROGRAM 10.

WAP to create threads using thread class and demonstrate


using their priority.

public class ShwetaThreadPriority extends Thread


{
public void run ()
{
System.out.println ("running thread name is:" +
Thread.currentThread ().getName ());
System.out.println ("running thread priority is:" +
Thread.currentThread ().getPriority ());
}
public static void main (String args[])
{
ShwetaThreadPriority m1 = new ShwetaThreadPriority ();
ShwetaThreadPriority m2 = new ShwetaThreadPriority ();
ShwetaThreadPriority m3 = new ShwetaThreadPriority ();
m1.setPriority (Thread.MIN_PRIORITY);
m2.setPriority (Thread.NORM_PRIORITY);
m3.setPriority (Thread.MAX_PRIORITY);
m1.start ();
m2.start();
m3.start();
}
}

Page 22
PROGRAM 11.

WAP to read the contents of a file using Character Stream.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
class ReadFileUsingCharacterStream {
public static void main(String[] args) throws Exception {
FileReader inFile = new FileReader(args[0]);
BufferedReader br = new BufferedReader(inFile);
String s;
System.out.println("The contents of " + args[0] + "file are....");
/* Read lines from the file and display them on the screen. */
while((s = br.readLine()) != null) {
System.out.println(s);
}
inFile.close();
}
}

Page 23
Page 24
PROGRAM 12.

WAP for Implementing Calculator in an Applet, use appropri-


ate Layout Manager.

import java.applet.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;;
public class calculator extends Applet implements ActionListener,
TextListener

{
String s,s1,s2,s3,s4;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;
Button add,sub,eq,cl,mul,div;
TextField t1;
float 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");

Page 25
b8=new Button("8");
b9=new Button("9");
b0=new Button("0");
add=new Button("+");
sub=new Button("-");
mul=new Button("*");
div=new Button("/");
eq=new Button("=");
cl=new Button("Clear");

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(eq);
add(cl);
b1.addActionListener(this);

Page 26
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);
paint();
t1.addTextListener(this);
}
public void paint()
{
setBackground(Color.green);
}
public void actionPerformed(ActionEvent e)
{
s=e.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);

Page 27
}
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("="))
{
s4=t1.getText();
a=Integer.parseInt(s2);
b=Integer.parseInt(s4);
if(s3.equals("+"))
c=a+b;
if(s3.equals("-"))

Page 28
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)
{
}}

PROGRAM 13 A.

WAP to implement Grid Layout .

Page 29
import java.applet.Applet;
import java.awt.*;

public class Gridlayout extends Applet {


TextField t1=new TextField();
TextField t2=new TextField();
TextField t3=new TextField();

public Gridlayout(){
Label l1=new Label("First Number: ");
Label l2=new Label("Second Number: ");
Label l3=new Label("Third Number ");
setLayout(new GridLayout(4,2));//row,columns
setBackground(Color.red);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
}

Page 30
PROGRAM 13 B.

WAP to implement Card Layout .

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class Cardlayout extends Applet implements ActionListener


{
Button b1,b2,b3,b4,b5;

CardLayout card=new CardLayout(20,30);


public void init()
{
b1=new Button("north");
b2=new Button("south");
b3=new Button("east");

Page 31
b4=new Button("west");
b5=new Button("center");

setLayout(card);
add(b1,"card1");
add(b2,"card2");
add(b3,"card3");
add(b4,"card4");
add(b5,"card5");

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
}

public void actionPerformed(ActionEvent e)


{
//card.last(this);
card.next(this);
//card.first(this);
}

/*
<applet code="Cardlayout.class" width="500" height="500">
</applet>
*/

Page 32
Page 33
PROGRAM 13 C.

WAP to implement Border Layout .

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class Borderlayout extends Applet implements ActionListener


{
Button b1,b2,b3,b4,b5;

public void init()


{
b1=new Button("north");
b2=new Button("south");
b3=new Button("east");
b4=new Button("west");
b5=new Button("center");
setLayout(new BorderLayout(25,5));
add(b1,BorderLayout.NORTH);
add(b2,BorderLayout.SOUTH);
add(b3,BorderLayout.EAST);
add(b4,BorderLayout.WEST);
add(b5,BorderLayout.CENTER);

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);

Page 34
}
public void actionPerformed(ActionEvent e)
{

if (e.getSource()==b1)
{
Color color = new Color(255,100,0);
this.setBackground(color);
}
if (e.getSource()==b2)
{
Color color = new Color(255,10,0);
this.setBackground(color);
}
if (e.getSource()==b3)
{
Color color = new Color(100,58,0);
this.setBackground(color);
}
if (e.getSource()==b4)
{
Color color = new Color(0,100,0);
this.setBackground(color);
}
if (e.getSource()==b5)
{
Color color = new Color(50,200,0);
this.setBackground(color);
}
}
}

Page 35
/*
<applet code="Borderlayout.class" width="500" height="500">
</applet>
*/

PROGRAM 13 D.

WAP to implement Flow Layout .

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class Flowlayout extends Applet implements ActionListener


{

Page 36
Button b1,b2,b3,b4,b5;
FlowLayout f=new FlowLayout(FlowLayout.CENTER);
public void init()
{
b1=new Button("north");
b2=new Button("south");
b3=new Button("east");
b4=new Button("west");
b5=new Button("center");
setLayout(f);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==b1)
{
Color color = new Color(255,100,0);
this.setBackground(color);
}
if (e.getSource()==b2)

Page 37
{
Color color = new Color(255,10,0);
this.setBackground(color);
}
if (e.getSource()==b3)
{
Color color = new Color(100,58,0);
this.setBackground(color);
}
if (e.getSource()==b4)
{
Color color = new Color(0,100,0);
this.setBackground(color);
}
if (e.getSource()==b5)
{
Color color = new Color(50,200,0);
this.setBackground(color);
}
}

/*
<applet code="Flowlayout.class" width="500" height="500">
</applet>
*/

Page 38
PROGRAM 14.

Page 39
WAP to implement MouseMotion and MouseMotionListener
Interface.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

//<Applet code=DemoMouseLis height=600 width=600></Applet>

public class ShwetaMouselisteners extends Applet implements


MouseListener,MouseMotionListener{

int x1,y1,x2,y2;
public void init(){

addMouseListener(this);
addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent e){}


public void mousePressed(MouseEvent e){
x1=e.getX();
y1=e.getY();
}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e) {}
public void mouseMoved(MouseEvent e){}
public void mouseDragged(MouseEvent e){
x2=e.getX();
y2=e.getY();

Page 40
repaint();

public void paint(Graphics g){


g.drawLine(x1,y1,x2,y2);
g.drawOval(300,300,100,150);
}
}

PROGRAM 15.

Page 41
Write a program to handle your own Exception.

import java.io.*;
import java.util.*;
class InvalidBalanceException extends Exception
{
public InvalidBalanceException(String message)
{
super(message);
}
}
class UserDefinedException{
public static void main (String[] args) {
int balance;
try
{
balance = Integer.parseInt(args[0]);
updateBalance(balance);
}
catch(InvalidBalanceException ex)
{
System.out.println("Caught in catch of InvalidBalanceException");
ex.printStackTrace();
}
catch(NumberFormatException ex)
{
System.out.println("Caught in catch of NumberFormatExcep-
tion");
}
catch(ArrayIndexOutOfBoundsException ex)

Page 42
{
System.out.println("Caught in catch of ArrayIndexOutOfBound-
sException");
}
catch(Exception ex)
{
System.out.println("Caught in catch of Parent Exception");
}
System.out.println("Main method executed successfully");
}

public static void updateBalance(int number)throws InvalidBalanceEx-


ception
{
if(number < 0)
{
throw (new InvalidBalanceException("Account balance cannot
be less than Zero."));
}

System.out.println("No exception occured in updateBalance()


method");
}
}

Page 43
Page 44
PROGRAM 16.

Write Applet code to add two integers in textbox and their


sum should appear in third textbox.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ShwetaAppletnew extends Applet implements ActionLis-


tener {
TextField t1=new TextField();
TextField t2=new TextField();
TextField t3=new TextField();

public ShwetaAppletnew(){
Label l1=new Label("First Number: ");
Label l2=new Label("Second Number: ");
Label l3=new Label("Sum: ");
setLayout(new GridLayout(5,3));
setBackground(Color.red);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
t2.addActionListener(this);
}

Page 45
@Override
public void actionPerformed(ActionEvent e) {
String s1=t1.getText();
int num1=Integer.parseInt(s1);
int num2=Integer.parseInt(t2.getText());
int Res=num1+num2;
t3.setText("Sum is : "+Res);
}
}

Page 46
PROGRAM 17.

Write AWT program in Java to find the sum, Multiplication


and average of three numbers entered in three Text fields by
clicking the corresponding Labeled Button. The result should
be appearing in fourth text field.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*
<applet code="Program17.class" width="500" height="500">
</applet>

*/

public class Program17 extends Applet implements ActionListener


{
Label label1, label2, label3,label4;
TextField tf1, tf2, tf3,tf4;
Button b1, b2, b3;
String whichButtonClk; //This String object will tells us which
// button is pressed
public void init()
{
System.out.println("Initializing an applet");

label1 = new Label("Number1");


tf1= new TextField(10);

label2 = new Label("Number2");

Page 47
tf2= new TextField(10);
label3 = new Label("Number3");
tf3= new TextField(10);

label4 = new Label("Result");


tf4= new TextField(20);

b1 = new Button("Add");
b2= new Button("Multiply");
b3 = new Button("Average");

add(label1);
add(tf1);

add(label2);
add(tf2);

add(label3);
add(tf3);

add(label4);
add(tf4);

add(b1);
add(b2);
add(b3);

tf1.addActionListener(this);//Actionlistener to first textfield event


tf2.addActionListener(this);//Actionlistener to second textfield event
tf3.addActionListener(this);//Actionlistener to third textfield event
tf4.addActionListener(this);//Actionlistener to fourth textfield event

Page 48
setLayout(new GridLayout(6,1));
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);

public void actionPerformed(ActionEvent ae)


{
if(ae.getActionCommand().equals("Add") ||
ae.getActionCommand().equals("Multiply") ||
ae.getActionCommand().equals("Average") )// checking if an event of
clicking the add/multiply/average button is generated
{
whichButtonClk=ae.getActionCommand(); //initializing whichButtonClk
to a String value of Button which is clicked
repaint();
}
}

public void paint(Graphics g)


{

if(tf1.getText().equals("") && tf2.getText().equals("")&&


tf3.getText().equals("")) //if the add button is clicked when textfields are
empty
{
}
else
{
Integer i1= new Integer(tf1.getText());
Integer i2= new Integer(tf2.getText());

Page 49
Integer i3= new Integer(tf3.getText());
int sum = i1+i2+i3;
int multiply=i1*i2*i3;
float average=(i1+i2+i3)/3;

if(whichButtonClk.equals("Add"))
tf4.setText("Your sum is "+ sum);
if(whichButtonClk.equals("Multiply"))
tf4.setText("Your multiply is "+ multiply);
if(whichButtonClk.equals("Average"))
tf4.setText("Your average is "+ average);
}
}
}

Page 50
Page 51
PROGRAM18.

Write Applet code to show all the activities of Mouse using


Mouselistener and MouseMotionlistener.

// Activities of MouseListener

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class ShwetaMouse extends Applet implements MouseListener


{
Label l;
public void init()
{
l=new Label();
add(l);
addMouseListener(this);
}
public void mouseClicked(MouseEvent e)
{
l.setText("Mouse Clicked");
}
public void mousePressed(MouseEvent e)
{
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{
l.setText("Mouse Released");
}

Page 52
public void mouseEntered(MouseEvent e)
{
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{
l.setText("Mouse Exited");
}}

Page 53
// Activities of MouseMotionListener

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ShwetaMouseMotionListeners extends Applet implements
MouseMotionListener
{
public void init()
{
addMouseMotionListener(this);
}
public void mouseDragged(MouseEvent e)
{
Graphics g= getGraphics();
g.fillOval(e.getX(),e.getY(),20,20);
g.setColor(Color.RED);
}

Page 54
public void mouseMoved(MouseEvent e) {
Graphics g= getGraphics();
g.drawOval(e.getX(),e.getY(),20,20);
g.setColor(Color.GREEN);
}
}

//Here Empty oval represents mouseMoved Activity


//Filled Oval represents mouseDragged Activity

PROGRAM 19.

Page 55
Write Java code to demonstrate (i) Layout Managers (ii)
Package (iii) Stream Tokenizers (iv) ActionListener

//(i) Layout Managers Already Done in Program 13.


//(ii) Package

package mypack;
public class ShwetaPackage{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

// (iii) Stream Tokenizers

Page 56
import java.util.StringTokenizer;
public class ShwetaStringTokenizer{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is shweta"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());

StringTokenizer sh = new StringTokenizer("my,name,is,shweta");


// printing next token
System.out.println("Next token is : " + sh.nextToken(","));
}
}

//(iv) ActionListener

Page 57
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ShwetaActionListeners extends Applet implements Action-


Listener {
TextField t1=new TextField();
TextField t2=new TextField();
TextField t3=new TextField();

public ShwetaActionListeners(){
Label l1=new Label("First Number: ");
Label l2=new Label("Second Number: ");
Label l3=new Label("Sum: ");
setLayout(new GridLayout(5,3));
setBackground(Color.white);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
t2.addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent e) {
String s1=t1.getText();
int num1=Integer.parseInt(s1);

Page 58
int num2=Integer.parseInt(t2.getText());
int Res=num1+num2;
t3.setText("Sum is : "+Res);
}
}

PROGRAM 20.

Write Java code to read character from a file and write into
another file.

Page 59
// Java program to read content from
// one file and write into another file
import java.io.*;
import java.util.*;
public class ShwetaCopyFromFile1ToFile2 {
public static void copyContent(File a, File b)
throws Exception
{
FileInputStream in = new FileInputStream(a);
FileOutputStream out = new FileOutputStream(b);
try {
int n;
// read() function to read the
// byte of data
while ((n = in.read()) != -1) {
// write() function to write
// the byte of data
out.write(n);
}
}
finally {
if (in != null) {
// close() function to close the
// stream
in.close();
}

Page 60
// close() function to close
// the stream
if (out != null) {
out.close();
}
}
System.out.println("File Copied");
}
public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(System.in);
// get the source file name
System.out.println(
"Enter the source filename from where you have to read/copy :");
String a = sc.nextLine();
// source file
File x = new File(a);
// get the destination file name
System.out.println(
"Enter the destination filename where you have to write/paste :");
String b = sc.nextLine();
// destination file
File y = new File(b);
// method called to copy the
// contents from x to y
copyContent(x, y);
}
}

Page 61
PROGRAM 21.

Write Java Program to generate Even numbers and Odd


Numbers in TextField “T1 and T2 respectively” while
pressing Button “Even” and “Odd”.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

Page 62
//<applet code="shwetaevenodd.class" width="300" height="300"></
applet>
public class ShwetaEvenOddProgram21 extends Applet implements Ac-
tionListener {
TextField t1, t2;
int x = 0, y = 1;
Label l1, l2;
Button b1, b2;
public void init() {
t1 = new TextField(8);
t2 = new TextField(8);
l1 = new Label("Odd Number");
l2 = new Label("Even Number");
b1 = new Button("Even");
b2 = new Button("Odd");
add(l1);
add(t1);
add(l2);
add(t2);
b1.addActionListener(this);
add(b1);
b2.addActionListener(this);
add(b2);
setLayout(new GridLayout(3, 2));
}
public void actionPerformed(ActionEvent ae)
{
Button source = (Button) ae.getSource();
if (source.getLabel() == "Even") {
x = x + 2;
String s = String.valueOf(x);
t1.setText(s);
}

Page 63
if (source.getLabel() == "Odd") {
y = y + 2;
String s = String.valueOf(y);
t2.setText(s);
}
}
}

PROGRAM 22.

What is Applet Life Cycle? Explain with suitable Java Pro-


gram so that every Applet function works?

import java.applet.Applet;
import java.awt.Graphics;

public class ShwetaAppletLifeCycle extends Applet

Page 64
{
public void init()
{
System.out.println("1.I am init()");
}
public void start()
{
System.out.println("2.I am start()");
}
public void paint(Graphics g)
{
System.out.println("3.I am paint()");
}
public void stop()
{
System.out.println("4.I am stop()");
}
public void destroy()
{
System.out.println("5.I am destroy()");
}
}
/*
<html>
<body>
<applet code="AppletLifeCycle.class" width="300" height="300"></ap-
plet>
</body>
</html>*/

Page 65
After minimizing the applet-Output:

After MAXIMIZING and CLOSING the applet-Output:

Page 66
PROGRAM 23.

Page 67
Write applet code to draw shapes using Applet graphics.

//Smiley Face
import java.applet.Applet;
import java.awt.*;
public class ShwetaSmily extends Applet {
public void paint(Graphics g) {
g.setColor(Color.black);
g.drawOval(20,20,150,150); // For face
g.fillOval(50,60,15,25); // Left Eye
g.fillOval(120,60,15,25); // Right Eye
g.drawLine(93,105,93,75); // Nose
g.drawArc(55,95,78,50,0,-180); // Smile
}
}
/* <applet code="ShwetaSmily.class" width="500" height="500">
</applet>*/

// Boat With 2 Man

import java.applet.Applet;

Page 68
import java.awt.*;
public class ShwetaBoat extends Applet {
public void paint(Graphics g) {
g.setColor(Color.black);
g.drawOval(100,45,35,35);
g.drawOval(200,45,35,35);
g.drawArc(80,70,45,100,90,90);
g.drawArc(180,70,45,100,90,90);
g.drawArc(109,70,45,100,0,90);
g.drawArc(210,70,45,100,0,90);
g.drawLine(55,120,125,175);
g.drawLine(55,120,285,120);
g.drawLine(215,175,285,120);
g.drawLine(125,175,215,175);
}
}
/* <applet code="ShwetaBoat.class" width="500" height="500">
</applet>
*/

PROGRAM 24.

Write Applet code to show all the activities of Mouse using

Page 69
Mouselistener and MouseMotionlistener classes.

// Activities of MouseListener

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class ShwetaMouse extends Applet implements MouseListener


{
Label l;
public void init()
{
l=new Label();
add(l);
addMouseListener(this);
}
public void mouseClicked(MouseEvent e)
{
l.setText("Mouse Clicked");
}
public void mousePressed(MouseEvent e)
{
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{
l.setText("Mouse Released");
}
public void mouseEntered(MouseEvent e)
{

Page 70
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{
l.setText("Mouse Exited");
}}

Page 71
// Activities of MouseMotionListener

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ShwetaMouseMotionListeners extends Applet implements
MouseMotionListener
{
public void init()
{
addMouseMotionListener(this);
}
public void mouseDragged(MouseEvent e)
{
Graphics g= getGraphics();
g.fillOval(e.getX(),e.getY(),20,20);
g.setColor(Color.RED);
}

Page 72
public void mouseMoved(MouseEvent e) {
Graphics g= getGraphics();
g.drawOval(e.getX(),e.getY(),20,20);
g.setColor(Color.GREEN);
}
}

//Here Empty oval represents mouseMoved Activity


//Filled Oval represents mouseDragged Activity

PROGRAM 25.

Page 73
Write Java code to demonstrate different Layouts in Java.

WAP to implement Grid Layout .

import java.applet.Applet;
import java.awt.*;

public class Gridlayout extends Applet {


TextField t1=new TextField();
TextField t2=new TextField();
TextField t3=new TextField();

public Gridlayout(){
Label l1=new Label("First Number: ");
Label l2=new Label("Second Number: ");
Label l3=new Label("Third Number ");
setLayout(new GridLayout(4,2));//row,columns
setBackground(Color.red);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
}

Page 74
WAP to implement Card Layout .

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class Cardlayout extends Applet implements ActionListener


{
Button b1,b2,b3,b4,b5;

CardLayout card=new CardLayout(20,30);


public void init()
{
b1=new Button("north");
b2=new Button("south");
b3=new Button("east");

Page 75
b4=new Button("west");
b5=new Button("center");

setLayout(card);
add(b1,"card1");
add(b2,"card2");
add(b3,"card3");
add(b4,"card4");
add(b5,"card5");

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
}

public void actionPerformed(ActionEvent e)


{
//card.last(this);
card.next(this);
//card.first(this);
}

/*
<applet code="Cardlayout.class" width="500" height="500">
</applet>
*/

Page 76
Page 77
WAP to implement Border Layout .

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class Borderlayout extends Applet implements ActionListener


{
Button b1,b2,b3,b4,b5;

public void init()


{
b1=new Button("north");
b2=new Button("south");
b3=new Button("east");
b4=new Button("west");
b5=new Button("center");
setLayout(new BorderLayout(25,5));
add(b1,BorderLayout.NORTH);
add(b2,BorderLayout.SOUTH);
add(b3,BorderLayout.EAST);
add(b4,BorderLayout.WEST);
add(b5,BorderLayout.CENTER);

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);

Page 78
}
public void actionPerformed(ActionEvent e)
{

if (e.getSource()==b1)
{
Color color = new Color(255,100,0);
this.setBackground(color);
}
if (e.getSource()==b2)
{
Color color = new Color(255,10,0);
this.setBackground(color);
}
if (e.getSource()==b3)
{
Color color = new Color(100,58,0);
this.setBackground(color);
}
if (e.getSource()==b4)
{
Color color = new Color(0,100,0);
this.setBackground(color);
}
if (e.getSource()==b5)
{
Color color = new Color(50,200,0);
this.setBackground(color);
}
}
}

Page 79
/*
<applet code="Borderlayout.class" width="500" height="500">
</applet>
*/

WAP to implement Flow Layout .

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class Flowlayout extends Applet implements ActionListener


{

Page 80
Button b1,b2,b3,b4,b5;
FlowLayout f=new FlowLayout(FlowLayout.CENTER);
public void init()
{
b1=new Button("north");
b2=new Button("south");
b3=new Button("east");
b4=new Button("west");
b5=new Button("center");
setLayout(f);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==b1)
{
Color color = new Color(255,100,0);
this.setBackground(color);
}
if (e.getSource()==b2)

Page 81
{
Color color = new Color(255,10,0);
this.setBackground(color);
}
if (e.getSource()==b3)
{
Color color = new Color(100,58,0);
this.setBackground(color);
}
if (e.getSource()==b4)
{
Color color = new Color(0,100,0);
this.setBackground(color);
}
if (e.getSource()==b5)
{
Color color = new Color(50,200,0);
this.setBackground(color);
}
}

/*
<applet code="Flowlayout.class" width="500" height="500">
</applet>
*/

Page 82
Page 83
PROGRAM 26.

Discuss MouseListener and MouseMotionListener interfaces


in detail. Write code to drag a line and rectangle using these
interfaces.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

//<Applet code=DemoMouseLis height=600 width=600></Applet>

public class Program26 extends Applet implements


MouseListener,MouseMotionListener{

int x1,y1,x2,y2;
public void init(){

addMouseListener(this);
addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent e){}


public void mousePressed(MouseEvent e){
x1=e.getX();
y1=e.getY();
}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e) {}
public void mouseMoved(MouseEvent e){}
public void mouseDragged(MouseEvent e){
x2=e.getX();

Page 84
y2=e.getY();
repaint();

public void paint(Graphics g){


g.drawLine(x1,y1,x2,y2);
g.drawRect(300,300,100,150);
}
}

Page 85
PROGRAM 27.

Write java code to demonstrate the concept of checkbox and


radio button using appropriate interface.

/*
Create AWT Radio Buttons Using CheckboxGroup AND AWT Checkbox
using Checkbox:
*/
import java.applet.Applet;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.GridLayout;

/*
<applet code=RadioButtonCheckBox.class" width=200 height=200>
</applet>
*/
public class RadioButtonCheckBox extends Applet{
public void init(){
// Create CheckBox
Checkbox cb1 = new Checkbox("Checkbox 1");
this.add(cb1);
Checkbox cb2 = new Checkbox("Checkbox 2");
this.add(cb2);
Checkbox cb3 = new Checkbox("Checkbox 3");
this.add(cb3);
Checkbox cb4 = new Checkbox("Checkbox 4");
this.add(cb4);
// Add RAdio buttons

Page 86
CheckboxGroup cbg = new CheckboxGroup();
this.add(new Checkbox("Shweta", cbg, true));
this.add(new Checkbox("Shakti", cbg, false));
this.add(new Checkbox("Nikita", cbg, false));
this.add(new Checkbox("Deepali", cbg, false));
setLayout(new GridLayout(4,2));
}
}

PROGRAM 28.

Write a program to Copy the text from one file to another

Page 87
using byte stream.

// Java program to copy content from


// one file to another
import java.io.*;
import java.util.*;
public class ShwetaCopyFromFile1ToFile2 {
public static void copyContent(File a, File b)
throws Exception
{
FileInputStream in = new FileInputStream(a);
FileOutputStream out = new FileOutputStream(b);
try {
int n;
// read() function to read the
// byte of data
while ((n = in.read()) != -1) {
// write() function to write
// the byte of data
out.write(n);
}
}
finally {
if (in != null) {
// close() function to close the
// stream
in.close();
}

Page 88
// close() function to close
// the stream
if (out != null) {
out.close();
}
}
System.out.println("File Copied");
}
public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(System.in);
// get the source file name
System.out.println(
"Enter the source filename from where you have to read/copy :");
String a = sc.nextLine();
// source file
File x = new File(a);
// get the destination file name
System.out.println(
"Enter the destination filename where you have to write/paste :");
String b = sc.nextLine();
// destination file
File y = new File(b);
// method called to copy the
// contents from x to y
copyContent(x, y);
}
}

Page 89
PROGRAM 29.

What are various types of Applets? Explain in detail Applet


life cycle. Write Java code that shows the working of every
applet function?

import java.applet.Applet;

Page 90
import java.awt.Graphics;

public class ShwetaAppletLifeCycle extends Applet


{
public void init()
{
System.out.println("1.I am init()");
}
public void start()
{
System.out.println("2.I am start()");
}
public void paint(Graphics g)
{
System.out.println("3.I am paint()");
}
public void stop()
{
System.out.println("4.I am stop()");
}
public void destroy()
{
System.out.println("5.I am destroy()");
}
}
/*
<html>
<body>
<applet code="AppletLifeCycle.class" width="300" height="300"></ap-
plet>
</body>
</html>*/

Page 91
After minimizing the applet-Output:

After MAXIMIZING and CLOSING the applet-Output:

Page 92
PROGRAM 30.

Discuss ActionListener and ItemListener interfaces in detail.


Write your own code to demonstrate the respective functions
these interfaces.

//ActionListener

import java.applet.Applet;

Page 93
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ShwetaActionListeners extends Applet implements Action-


Listener {
TextField t1=new TextField();
TextField t2=new TextField();
TextField t3=new TextField();

public ShwetaActionListeners(){
Label l1=new Label("First Number: ");
Label l2=new Label("Second Number: ");
Label l3=new Label("Sum: ");
setLayout(new GridLayout(5,3));
setBackground(Color.white);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
t2.addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent e) {
String s1=t1.getText();
int num1=Integer.parseInt(s1);
int num2=Integer.parseInt(t2.getText());
int Res=num1+num2;

Page 94
t3.setText("Sum is : "+Res);
}
}

//ItemListeners

/*The itemStateChanged() method is invoked automatically


* whenever you click or unclick on the registered
* checkbox component.
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

Page 95
public class ShwetaItemListener extends Applet implements ItemLis-
tener
{
Checkbox check1;
Checkbox check2;
Checkbox check3;
Checkbox check4;
String msg = "";
public void init()
{
check1 = new Checkbox("Shweta");
check2 = new Checkbox("Shakti");
check3 = new Checkbox("Nikita");
check4 = new Checkbox("Deepali");
add(check1);
check1.addItemListener(this);
add(check2);
check2.addItemListener(this);
add(check3);
check3.addItemListener(this);
add(check4);
check4.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
msg = "Current State: ";

Page 96
g.drawString(msg,6,100);
msg = "shweta's State: " + check1.getState();
g.drawString(msg,6,120);
msg = "Shakti's State: " + check2.getState();
g.drawString(msg,6,140);
msg = "Nikita's State: " + check3.getState();
g.drawString(msg,6,160);
msg = "Deepali's State: " + check4.getState();
g.drawString(msg,6,180);
}
}

/*
<applet code=ShwetaItemListener.class" width=200 height=200>
</applet>

*/

Page 97

You might also like