Vivekananda Institute of Professional Studies

You might also like

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

VIVEKANANDA INSTITUTE OF PROFESSIONAL STUDIES

VIVEKANANDA SCHOOL OF INFORMATION TECHNOLOGY

BACHELOR OF COMPUTER APPLICATION


JAVA PROGRAMING FILE

Guru Gobind Singh Indraprastha University 


Sector - 16C, Dwarka, Delhi - 110078

SUBMITTED TO: SUBMITTED BY:


Dr. Neha Verma Malhotra Himanshu Tandon
Assistant Professor 08429802019
VSIT BCA-IV (EB)

Page | 1
Himanshu Tandon
08429802019
BCA 4EB
INDEX
S.NO Date Teacher’s
. PROGRAM Signature
Write a program to print all odd numbers 12-03-21
1. between 1 to 10.
Write a program to find out factorial of a number 12-03-21
2. through recursion.

Write a program to accept Command line 13-03-21


3. arguments & print them.

4. Write a program to print Fibonacci series. 13-03-21


Write a program to obtain a number by a user & 16-03-21
5 check if it’s prime or not.
Write a program that creates a class Accounts with 16-03-21
following details:
Instance variables: ac_no., name, ac_name, balance
6 Methods: withdrawal (), deposit (), display ().Use
constructors to
initialize members.
Write a program to implement constructor 18-03-21
7
overloading.
Write a program to count the no. of objects created 18-03-21
8 in a program.
Write a program to show call by value & call by 22-03-21
9
reference.
Write a program to implement method over 22-03-21
10 ridding & method
overloading.
Create a class box having height, width, depth as 26-03-21
the instance
variables & calculate its volume. Implement
constructor
11 overloading in it. Create a subclass named box_new
that has
weight as an instance variable. Use super in the
box_new class
to initialize members of the base class.

Page | 2
Himanshu Tandon
08429802019
BCA 4EB
Write a program to implement Run time 26-03-21
12 polymorphism.
Write a program to implement interface. Create an 3-04-21
interface named
Shape having area () & perimeter () as its methods.
13 Create three
classes circle, rectangle & square that implement
this interface.

14 Write a program to show multiple inheritance. 9-04-21


Write a program to implement exception handling. 10-04-21
15 Use try, catch & finally.
Create a user defined exception named 10-04-21
“NoMatchException”
16
that is fired when the string entered by the user is
not “india”.
Write a program to show even & odd numbers by 13-04-21
17 thread.
Write a program that draws different color shapes 1-05-21
18 on an applet .Set the
foreground & background color as red & blue.

19 Write a program to show moving banner by applet. 5-05-21


Write a program to implement Matrix 10-05-21
20 multiplication by 2D array.
Write a program to implement Vector. 17-05-21
21 [Use:
addElement(),elementAt().removeElement(),size().]
Write a program to demonstrate the use of equals(), 22-05-21
22 trim() ,length() ,
substring(), compareTo() of String class.
Write a program to implement file handling(both 29-05-21
23 reading & writing to a
file)
Write a program to implement all mouse events 31-05-21
24 and mouse motion
events.

25 Write a program to implement keyboard events. 1-06-21


26 Write a program using AWT to create a simple 5-06-21
Page | 3
Himanshu Tandon
08429802019
BCA 4EB
calculator.
Create a login form using AWT controls like 9-06-21
labels,buttons,
27 textboxes, checkboxes, list, checkboxgroup. The
selected
checkbox item names should be displayed.

28 Write a program to show all Layout managers. 12-06-21


29 Write a program to show all Layout managers. 12-06-21
30 Write a program to show all Layout managers. 12-06-21
31 Write a program to show all Layout managers. 13-06-21
32 Create a simple JDBC program that creates a table. 18-06-21
Create a simple JDBC program that stores data 18-06-21
33 into a table.
Create a simple JDBC program that retrieves & 18-06-21
34 prints the data from that table.
Create a Java applet with three buttons 20-06-21
‘Red’,’Green’,’Blue’.
35 Whenever user press any button the corresponding
color should be
seen as background color in an applet window.

Page | 4
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #1
1. Write a program to print all odd numbers between 1 to 10.
Ans.
Source Code
class oddnumber {
public static void main(String args[])
{
int n = 10;
System.out.print("Odd Numbers from 1 to "+n+" are: ");
for (int i = 1; i <= n; i++) {
if (i % 2 != 0) {
System.out.print(i + " ");
}
}
}
}

Page | 5
Himanshu Tandon
08429802019
BCA 4EB
Output

Page | 6
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #2
2. Write a program to find out factorial of a number through recursion.
Ans.
Source Code
class factorial
{
static int factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[])
{
int i,fact=1;
int number=6;
fact = factorial(number);
System.out.println("Factorial of "+number+" is: "+fact);
}
}

Page | 7
Himanshu Tandon
08429802019
BCA 4EB
Output

Page | 8
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #3
3. Write a program to accept Command line arguments & print them.
Ans.
Source Code
class commandline
{
public static void main(String args[]){

for(int i=0;i<args.length;i++)
System.out.println(args[i]);

}
}

Page | 9
Himanshu Tandon
08429802019
BCA 4EB
Output

PRACTICAL #4
Page | 10
Himanshu Tandon
08429802019
BCA 4EB
4. Write a program to print Fibonacci series.
Ans.
Source Code
class fibonacci
{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=20;
System.out.print(n1+" "+n2);

for(i=2;i<count;++i)
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}

}}

Output

Page | 11
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #5
Page | 12
Himanshu Tandon
08429802019
BCA 4EB
5. Write a program to obtain a number by a user & check if it’s prime or
not.

Ans.
Source Code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class prime
{
public static void main(String args[]) throws IOException
{
int i,m=0,flag=0;
BufferedReader reader =new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter a Number: ");
int n = Integer.parseInt(reader.readLine());

m=n/2;
if(n==0||n==1)
{
System.out.println(n+" is not prime number");
}
else
{
for(i=2;i<=m;i++)
{
if(n%i==0)

Page | 13
Himanshu Tandon
08429802019
BCA 4EB
{
System.out.println(n+" is not prime number");
flag=1;
break;
}
}
if(flag==0)
{
System.out.println(n+" is prime number"); }
}

}
}

Output

Page | 14
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #6
6. Write a program that creates a class Accounts with following details:
Instance variables: ac_no., name, ac_name, balance
Methods: withdrawal (), deposit (), display ().Use constructors to
Page | 15
Himanshu Tandon
08429802019
BCA 4EB
initialize members.
Ans.
Source Code
class accounts
{
public int ac_no;
public String name;
public String ac_name;
public float balance;

accounts()
{
ac_no=6969;
name="abc";
ac_name="bank";
balance=5000;
}

void deposit(float amt)


{
balance=balance+amt;
System.out.println(" amount deposited");
}
void withdraw(float amt)
{
if(balance<amt)
{
Page | 16
Himanshu Tandon
08429802019
BCA 4EB
System.out.println("no Balance");
}
else
{
balance=balance-amt;
System.out.println("amount withdrawn");
}
}

void display()
{
System.out.println("Account number=" + ac_no);
System.out.println("Name = " +name);
System.out.println("Account name =" +ac_name);
System.out.println("balance = " +balance);
}
}

class account
{
public static void main(String args[])
{
accounts a=new accounts();
a.display();
a.deposit(50000);
a.display();
a.withdraw(11000);
Page | 17
Himanshu Tandon
08429802019
BCA 4EB
a.display();
}
}

Output

Page | 18
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #7
7. Write a program to implement constructor overloading.
Ans.

Page | 19
Himanshu Tandon
08429802019
BCA 4EB
Source Code

public class student


{
int id;
String name;
student()
{
System.out.println("this a default constructor");
}
student(int i, String n)
{
id = i;
name = n;
}
public static void main(String[] args)
{
student s = new student();
System.out.println("\nDefault Constructor values: \n");
System.out.println("Student Id : "+s.id + "\nstudent Name :
"+s.name);
System.out.println("\nParameterized Constructor values: \n");
student student = new student(84, "Himanshu Tandon");
System.out.println("Student Id : "+student.id + "\nstudent Name :
"+student.name);
}
Page | 20
Himanshu Tandon
08429802019
BCA 4EB
}

Output

Page | 21
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #8
8. Write a program to count the no. of objects created in a program.
Page | 22
Himanshu Tandon
08429802019
BCA 4EB
Ans.
Source Code
public class number
{
static int count=0;
number()
{
count++;
}
public static void main(String[] args)
{
number obj1 = new number();
number obj2 = new number();
number obj3 = new number();
number obj4 = new number();
System.out.println("Number of objects created:"+count);
}
}

Output

Page | 23
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #9
9. Write a program to show call by value & call by reference.

Page | 24
Himanshu Tandon
08429802019
BCA 4EB
Ans.

Call By Value

Source Code
public class tester
{
public static void main(String[] args)
{
int a = 90;
int b = 58;
System.out.println("Before swapping, a = " + a + " and b = " + b);
swapFunction(a, b);
System.out.println("\n*Now, Before and After swapping values will be
same here*:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b)
{
System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}

Output
Page | 25
Himanshu Tandon
08429802019
BCA 4EB
Call By Reference
Source Code
public class tester
Page | 26
Himanshu Tandon
08429802019
BCA 4EB
{
public static void main(String[] args)
{
int a = 90;
int b = 58;
System.out.println("Before swapping, a = " + a + " and b = " + b);
swapFunction(a, b);
System.out.println("\n*Now, Before and After swapping values will be
same here*:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b)
{
System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}

Output

Page | 27
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #10
10. Write a program to implement method over ridding &
method
overloading..

Page | 28
Himanshu Tandon
08429802019
BCA 4EB
Ans.
Method Overriding

Source Code

class vehicle
{
void run(){System.out.println("Vehicle is running");}
}
class bike extends vehicle
{
public static void main(String args[])
{
bike obj = new bike();
obj.run();
}
}

Output
Page | 29
Himanshu Tandon
08429802019
BCA 4EB
Method Overloading: Changing no. of arguments
Source Code

Page | 30
Himanshu Tandon
08429802019
BCA 4EB
class adder
{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class testoverloading
{
public static void main(String[] args)
{
System.out.println(adder.add(20,22));
System.out.println(adder.add(91,34,32));
}
}

Output

Page | 31
Himanshu Tandon
08429802019
BCA 4EB
Method Overloading: Changing data type of arguments
Source Code

class adder
Page | 32
Himanshu Tandon
08429802019
BCA 4EB
{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class testoverloading2
{
public static void main(String[] args)
{
System.out.println(adder.add(45,71));
System.out.println(adder.add(13.3,62.6));
}
}

Output

Page | 33
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #11
11. Create a class box having height, width, depth as the instance
variables & calculate its volume. Implement constructor

Page | 34
Himanshu Tandon
08429802019
BCA 4EB
overloading in it. Create a subclass named box_new that has
weight as an instance variable. Use super in the box_new class
to initialize members of the base class.

Ans.
Source Code

class box
{
private float depth,vol,height,width;
public box(float x,float y,float z)
{
height=x;
width=y;
depth=z;
System.out.println("height is "+height+"m");
System.out.println("width is "+width+"m");
System.out.println("depth is "+depth+"m");
}
public box()
{
height=0;
width=0;
depth=0;
}
public void volume()
{
vol=height*width*depth;
System.out.println("volume is "+vol+"m^3");
}
}
class boxnew extends box
{
private float weight;
public boxnew(float x,float y,float z,float w)
{
super(x,y,z);
weight=w;
System.out.println("weight is "+weight+"kg");

}
}
class prog11
{
Page | 35
Himanshu Tandon
08429802019
BCA 4EB
public static void main(String[]args)
{
boxnew b1=new boxnew(3,5,7,50);
b1.volume();
}
}

Output

Page | 36
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #12
12. Write a program to implement Run time polymorphism.

Page | 37
Himanshu Tandon
08429802019
BCA 4EB
Ans.
Source Code

class car
{
public void move()
{
System.out.println("Cars can move fast");
}
}
class bike extends car
{
public void move()
{
System.out.println("Bikes can move faster");
}
}
public class testbike
{
public static void main(String args[])
{
car a = new car();
car b = new bike();
a.move();
b.move();
}
}

Output

Page | 38
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #13
13. Write a program to implement interface. Create an interface
named
Page | 39
Himanshu Tandon
08429802019
BCA 4EB
Shape having area () & perimeter () as its methods. Create three
classes circle, rectangle & square that implement this interface.

Ans.
Source Code

interface Shape
{
void area();
void perimeter();
}
class circle implements Shape
{
int r = 0;
double pi = 3.14, ar = 0,p=0;
public void input(int a)
{
r = a;
}

public void area()


{
ar = pi * r * r;
System.out.println("Area of circle: "+ar);
}

public void perimeter()


{
p=2*r*pi;

Page | 40
Himanshu Tandon
08429802019
BCA 4EB
System.out.println("Perimeter of circle: "+p);

}
}
class rectangle implements Shape
{
int l = 0, b = 0;
double ar,pe;

public void input(int a,int x)


{

l = a;
b = x;
}
public void area()
{

ar = l * b;
System.out.println("Area of rectangle: "+ar);
}
public void perimeter()
{
pe=2*(l+b);
System.out.println("Perimeter of rectangle: "+pe);

}
}
Page | 41
Himanshu Tandon
08429802019
BCA 4EB
class square implements Shape
{
int s = 0;
double ar,pe;

public void input(int a)


{

s = a;

}
public void area()
{

ar = s * s;
System.out.println("Area of square: "+ar);
}
public void perimeter()
{
pe=4*s;
System.out.println("Perimeter of square: "+pe);

}
}
public class prog
Page | 42
Himanshu Tandon
08429802019
BCA 4EB
{
public static void main(String[] args)
{ circle c=new circle();
square sq=new square();
rectangle rect = new rectangle();
c.input(8);
c.area();
c.perimeter();

sq.input(6);
sq.area();
sq.perimeter();

rect.input(5,3);
rect.area();
rect.perimeter();
}
}

Output

Page | 43
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #14
14. Write a program to show multiple inheritance.

Page | 44
Himanshu Tandon
08429802019
BCA 4EB
Ans.
Source Code

interface cardrive
{
void drive();
}
interface carstop
{
void stop();
}
class car implements cardrive, carstop
{
public void drive()
{
System.out.println("Car is moving");
}
public void stop()
{
System.out.println("Car is stoping");
}
}
public class multipleinheritance
{
public static void main(String args[])
{
car a = new car();
a.drive();
a.stop();
}
}

Output

Page | 45
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #15
15. Write a program to implement exception handling. Use try, catch &
finally.
Page | 46
Himanshu Tandon
08429802019
BCA 4EB
Ans.
Source Code
class main
{
public static void main (String[] args)
{
int[] myArr = new int[20];
try
{
int i = myArr[20];

System.out.println("Program is inside the try block");


}
catch(ArrayIndexOutOfBoundsException ex)
{

System.out.println("Exception has been caught in the catch block");


}
finally
{

System.out.println("Now the finally block is executed");

System.out.println("Program is outside the try-catch-finally clause");


}
}

Output

Page | 47
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #16
16. Create a user defined exception named “NoMatchException”
that is fired when the string entered by the user is not “india”.
Ans.
Source Code
Page | 48
Himanshu Tandon
08429802019
BCA 4EB
import java.io.DataInputStream;
import java.io.IOException;

class NoMatchException extends Exception


{
public NoMatchException(String message)
{
super(message);
}
}
class IndiaAssertComparer
{
private String s;
IndiaAssertComparer(String s) throws NoMatchException
{
this.s = s;
if (s.equals("India"))
{
System.out.print("Matched!\n");
}
else
{
throw new NoMatchException("Not Matched!\n");
}
}
}

class NoMatcher
{
public static void main(String[] a) throws NoMatchException
{
IndiaAssertComparer v = new IndiaAssertComparer("ThaiLand");
}
}

Output

Page | 49
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #17
17. Write a program to show even & odd numbers by
thread.

Ans.
Source Code
Page | 50
Himanshu Tandon
08429802019
BCA 4EB
class OddEven implements Runnable
{
public int PRINT_NUMBERS_UPTO=20;
static int n=1;
int r;
static Object lock=new Object();
OddEven(int r)
{
this.r=r;
}

public void run()


{
while (n < PRINT_NUMBERS_UPTO)
{
synchronized (lock)
{
while (n % 2 != r)
{
try
{
lock.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " "
+ n);
n++;
lock.notifyAll();
}
}
}
}

public class PrintOddEven


{
public static void main(String[] args)
Page | 51
Himanshu Tandon
08429802019
BCA 4EB
{
OddEven oddRunnable=new OddEven(1);
OddEven evenRunnable=new OddEven(0);

Thread t1=new Thread(oddRunnable,"Odd");


Thread t2=new Thread(evenRunnable,"Even");

t1.start();
t2.start();
}
}

Output

Page | 52
Himanshu Tandon
08429802019
BCA 4EB
Page | 53
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #18
18. Write a program that draws different color shapes on an applet .Set the
foreground & background color as red & blue.
Ans.
Source Code
import java.applet.*;
import java.awt.*;

/*
* <applet code="eighteen" width=400 height=400>
* </applet>
*/

public class eighteen extends Applet {


String msg = " ";
public void init() {
setBackground(Color.blue);
setForeground(Color.red);
}
public void paint(Graphics g) {
g.drawArc(5, 5, 50, 60, 0, -80);
g.fillArc(5, 5, 50, 60, 0, -80);
g.drawArc(50, 50, 60, 50, 0, -80);
g.fillArc(50, 50, 50, 60, 0, -80);
g.drawArc(150, 150, 60, 50, 90, 80);
g.fillArc(150, 150, 50, 60, 90, 80);
g.drawArc(200, 200, 60, 50, 90, 80);
g.fillArc(200, 200, 50, 60, 90, 80);

Page | 54
Himanshu Tandon
08429802019
BCA 4EB
g.drawRect(20, 150, 60, 50);
g.fillRect(20, 150, 60, 50);
g.drawRoundRect(20, 240, 80, 60, 8, 8);
g.fillRoundRect(20, 240, 80, 60, 8, 8);
g.drawPolygon(new int[] {300,350,240,350,400}, new int[]
{300,300,350,350,325}, 5);
g.fillPolygon(new int[] {300,350,240,350,400}, new int[]
{300,300,350,350,325}, 5);
g.drawOval(350, 350, 200, 120);
g.fillOval(350, 350, 200, 120);
}
}

Page | 55
Himanshu Tandon
08429802019
BCA 4EB
Output

Page | 56
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #19
19. Write a program to show moving banner by applet.
Ans.
Source Code
import java.applet.*;
import java.awt.*;
import java.lang.Thread;

/**
* <applet code="ninteen" width=850 height=180>
* </applet>
*/

public class ninteen extends Applet implements Runnable {


Thread thread;
String message = "WELCOME TO MY HOME ";
boolean stopFlag;
Font MyFont;
public void start() {
stopFlag = false;
thread = new Thread(this,"MOVING BANNER THREAD");
MyFont = new Font("Arial",Font.BOLD,40);
thread.start();
}
public void run() {
char ch;
while(true) {
ch = message.charAt(0);
Page | 57
Himanshu Tandon
08429802019
BCA 4EB
message = message.substring(1, message.length());
message += ch;
try {
Thread.sleep(500);
} catch (InterruptedException iex) {
System.out.println(iex.getMessage());
}
repaint();
if(stopFlag)
thread = null;
}
}
public void paint(Graphics g) {
g.setFont(MyFont);
g.drawString(message, 100, 100);

}
public void stop() {
stopFlag = true;
thread = null;
}
}

Output
Page | 58
Himanshu Tandon
08429802019
BCA 4EB
Page | 59
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #20
20. Write a program to implement Matrix multiplication by 2D
array.
Ans.
Source Code
public class MatrixMulti {

public static void main(String args[]){


int a[][]={{1,5,6},{3,5,6},{3,2,1}};
int b[][]={{2,5,3},{8,6,7},{6,8,1}};

int c[][]=new int[3][3];


for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}
}
Page | 60
Himanshu Tandon
08429802019
BCA 4EB
Output

Page | 61
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #21
21. Write a program to implement Vector.
[Use: addElement(),elementAt().removeElement(),size().]
Ans.
Source Code
import java.util.Vector;

public class twentyone

{
public static void main(String args[])
{
Vector vect1 = new Vector ();
vect1.add("A");
vect1.add("B");
vect1.add("072");
vect1.add(0,"C");
System.out.println("Vector A: " +vect1);

System.out.println("Copying Elements of Vector A in Vector B" );


Vector vect2 = new Vector ();
vect2.addAll(vect1);
System.out.println("Vector B: " +vect1);
System.out.println("Element Value at First Index : " +vect1.get(1));
vect1.remove(1);
System.out.println("After Removal vector A: " +vect1);

vect2.clear();
System.out.println("After Clear vectB : " +vect2);
System.out.println("Vector A Size: " +vect1.size());

}
}

Page | 62
Himanshu Tandon
08429802019
BCA 4EB
Output

Page | 63
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #22
22. Write a program to demonstrate the use of equals() ,trim()
,length(),substring(), compareTo() of String class.
Ans.
Source Code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class twentytwo {
public static void main(String[] args) throws IOException {
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(inp);
System.out.println("Enter String 1 : ");
String str1 = in.readLine();
System.out.println("Enter String 2 : ");
String str2 = in.readLine();

if(str1.equals(str2)) {
System.out.println("Both the strings are same. ");
}
else {
System.out.println("The strings aren't same. ");
}

str1 = str1.trim();
System.out.println("Trimmed string is : " + str1);

Page | 64
Himanshu Tandon
08429802019
BCA 4EB
System.out.println("Length of string 1 is : " + str1.length());
System.out.println("Length of string 2 is : " + str2.length());

System.out.println(" - - - Sub String Function - - - ");


System.out.println("Enter 1 for choosing String 1 else 2 ");
int choice = Integer.parseInt(in.readLine());
System.out.println("Enter starting point : ");
int start = Integer.parseInt(in.readLine());
System.out.println("Enter ending point : ");
int end =Integer.parseInt(in.readLine());
switch(choice) {
case 1:
System.out.println("Sub string " + start + " to " + end + " in '" + str1 + "' is:
" + str1.substring(start, end));
break;
case 2:
System.out.println("Sub string " + start + " to " + end + " in '" + str2 + "' is:
" + str2.substring(start, end));
break;
default:
System.out.println("ERROR: Invalid choice number");
}

System.out.println("Dictionary difference between the two strings : " +


str1.compareTo(str2));
inp.close();
}
}

Page | 65
Himanshu Tandon
08429802019
BCA 4EB
Output

Page | 66
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #23
23. Write a program to implement file handling(both reading &
writing to a file)
Ans.
Source Code
import java.io.*;
import java.util.*;

public class program23


{
public static void main(String[] args) {
// create a new file
File myFile = new File("txtfile.txt");
try {
myFile.createNewFile();
} catch (IOException e) {
System.out.println("Unable to create this file");
e.printStackTrace();
}
System.out.println("File created.");

// write to a file
try {
FileWriter fileWriter = new FileWriter("txtfile.txt");
fileWriter.write("Hello I am Himanshu Tandon and we are handling files.
\nOkay bye");
fileWriter.close();
} catch (IOException e) {

Page | 67
Himanshu Tandon
08429802019
BCA 4EB
e.printStackTrace();
}

// Reading a file
System.out.println("Displaying the contents of the file: ");
File f = new File("txtfile.txt");
try {
FileReader reader = new FileReader(f);
int character;

while ((character = reader.read()) != -1) {


System.out.print((char) character);
}

reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Page | 68
Himanshu Tandon
08429802019
BCA 4EB
Output

Page | 69
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #24
24. Write a program to implement all mouse events and mouse
motion
events.
Ans.
Source Code
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/**
* <applet code="twentyfour" height=400 width=400>
* </applet>
*/

public class twentyfour extends Applet implements


MouseListener,MouseMotionListener {
String msg;
Font font = new Font("Consolas",Font.ITALIC,14);
Label l;
int X,Y;
boolean dragMode = false;
public void init() {
l = new Label();
l.setBackground(Color.darkGray);
l.setForeground(Color.orange);
add(l);
addMouseListener(this);
addMouseMotionListener(this);
Page | 70
Himanshu Tandon
08429802019
BCA 4EB
setLayout(null);
l.setBounds(20, 20, 300, 100);
setBackground(Color.orange);
setForeground(Color.darkGray);
}
public void paint(Graphics g) {
showStatus("Cursor coordinates : (" + X + "," + Y + ")");
if(dragMode) {
g.drawString(msg, X, Y);
} else {
l.setText(msg);
}
}
public void mouseEntered(MouseEvent mEvent) {
msg = "MOUSE ENTERED";
dragMode = false;
repaint();
}
public void mouseExited(MouseEvent mEvent) {
msg = "MOUSE EXITED";
dragMode = false;
repaint();
}
public void mouseClicked(MouseEvent mEvent) {
msg = "MOUSE CLICKED";
dragMode = false;
repaint();
}

Page | 71
Himanshu Tandon
08429802019
BCA 4EB
public void mousePressed(MouseEvent mEvent) {
msg = "MOUSE PRESSED";
dragMode = false;
repaint();
}
public void mouseReleased(MouseEvent mEvent) {
msg = "MOUSE RELEASED";
dragMode = false;
for(int i = 0; i < 9999999 ; i++) {
l.setText("MOUSE RELEASED");
}
repaint();
}
public void mouseMoved(MouseEvent mEvent) {
msg = "MOUSE MOVED";
X = mEvent.getX();
Y = mEvent.getY();
dragMode = false;
repaint();
}
public void mouseDragged(MouseEvent mEvent) {
msg = "$$";
dragMode = true;
X = mEvent.getX();
Y = mEvent.getY();
repaint();
}
}

Page | 72
Himanshu Tandon
08429802019
BCA 4EB
Output

Page | 73
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #25
25. Write a program to implement keyboard events.
Ans.
Source Code
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/**
* <applet code="twentyfive" height=500 width=500>
* </applet>
*/

public class twentyfive extends Applet implements KeyListener {


int X,Y;
String status;
public void init() {
X=10;
Y=10;
addKeyListener(this);
}
public void paint(Graphics g) {
g.drawOval(X, Y, 80, 80);
g.drawString(status, 100, 100);
}
public void keyPressed(KeyEvent ke) {

Page | 74
Himanshu Tandon
08429802019
BCA 4EB
status = "keyPressed";
int key = ke.getKeyCode();
switch(key) {
case KeyEvent.VK_UP:
Y--;
break;
case KeyEvent.VK_DOWN:
Y++;
break;
case KeyEvent.VK_LEFT:
X--;
break;
case KeyEvent.VK_RIGHT:
X++;
break;
}
repaint();
}
public void keyTyped(KeyEvent ke) {
status = "keyTyped";
repaint();
}
public void keyReleased(KeyEvent ke) {
status = "keyReleased";
repaint();
}
}
Page | 75
Himanshu Tandon
08429802019
BCA 4EB
Output

Page | 76
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #26
26. Write a program using AWT to create a simple calculator.

Ans.
Source Code
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/**
* <applet code="twentysix" height=400 width=200>
* </applet>
*/

public class twentysix extends Applet implements ActionListener,KeyListener


{
int op1,op2;
float opf1,opf2;
int res;
float resf;
String opMode;
Button addButton,subButton,mulButton,divButton;
Button calcButton,allClrButton;
TextField box1;
Label result,message;

Font MyFont = new Font("Arial",Font.BOLD,14);

Page | 77
Himanshu Tandon
08429802019
BCA 4EB
public void init() {

addButton = new Button("+");


subButton = new Button("-");
mulButton = new Button("*");
divButton = new Button("/");

calcButton = new Button("=");


allClrButton = new Button("AC");

addButton.setFont(MyFont);
subButton.setFont(MyFont);
mulButton.setFont(MyFont);
divButton.setFont(MyFont);
calcButton.setFont(MyFont);
allClrButton.setFont(MyFont);

add(addButton);
add(subButton);
add(mulButton);
add(divButton);
add(calcButton);
add(allClrButton);

addButton.addActionListener(this);
subButton.addActionListener(this);
mulButton.addActionListener(this);

Page | 78
Himanshu Tandon
08429802019
BCA 4EB
divButton.addActionListener(this);
calcButton.addActionListener(this);
allClrButton.addActionListener(this);

box1 = new TextField();


add(box1);

result = new Label("Result: ");


message = new Label();

box1.setFont(MyFont);
result.setFont(MyFont);
message.setFont(MyFont);

add(result);
add(message);
setLayout(null);

box1.setBounds(5, 5, 190, 50);


addButton.setBounds(5,55,47,25);
subButton.setBounds(5,80,47,25);
mulButton.setBounds(52,55,47,25);
divButton.setBounds(52,80,47,25);

calcButton.setBounds(99, 55, 47, 50);


allClrButton.setBounds(146, 55, 47, 50);
result.setBounds(5, 105, 140, 50);

Page | 79
Himanshu Tandon
08429802019
BCA 4EB
}

public void executeOperation(String operation) {


if(operation == "+") {
op1 = Integer.parseInt(box1.getText()); //received operand 1
box1.setText("");
opMode = "add";
} else if(operation == "-") {
op1 = Integer.parseInt(box1.getText()); //received operand 1
box1.setText("");
opMode = "sub";
} else if(operation == "*") {
op1 = Integer.parseInt(box1.getText()); //received operand 1
box1.setText("");
opMode = "mul";
} else if(operation == "/") {
op1 = Integer.parseInt(box1.getText()); //received operand 1
box1.setText("");
opMode = "div";
} else if(operation == "=") {
op2 = Integer.parseInt(box1.getText());
box1.setText("");
if(opMode == "add") {
res = op1 + op2;
} else if(opMode == "sub") {
res = op1 - op2;
} else if(opMode == "mul") {
Page | 80
Himanshu Tandon
08429802019
BCA 4EB
res = op1 * op2;
} else if(opMode == "div") {
res = op1 / op2;
}
result.setText("Result of " + opMode + "= " + res);
}
}

public void reset() {


result.setText("Result: ");
opMode = null;
message.setText("");
box1.setText("");

}
public void actionPerformed(ActionEvent ae) {
if(box1.getText().length() != 0) {
String operation = ae.getActionCommand();
executeOperation(operation);
}
if(ae.getActionCommand() == "AC")
reset();
}
public void keyPressed(KeyEvent keyEvent) {

}
public void keyReleased(KeyEvent keyEvent) {

Page | 81
Himanshu Tandon
08429802019
BCA 4EB
}
public void keyTyped(KeyEvent keyEvent) {

Page | 82
Himanshu Tandon
08429802019
BCA 4EB
Output

Page | 83
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #27
27. Create a login form using AWT controls like labels,buttons,
textboxes, checkboxes, list, checkboxgroup. The selected
checkbox item names should be displayed.

Ans.
Source Code
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

/**
* <applet code="twentyseven" height=500 width=430>
* </applet>
*/

class User {
private String name;
private String password;
private String posting;
private String[] luggage;
public User() {
name = password = posting = "-/NA/-";
luggage = null;
}
public User(String name, String password, String posting, String[] luggage) {
this.name = name;
this.password = password;
Page | 84
Himanshu Tandon
08429802019
BCA 4EB
this.posting = posting;
this.luggage = luggage;
}
public String name() {
return this.name;
}
public String password() {
return this.password;
}
public String posting() {
return posting;
}
public String[] luggage() {
return luggage;
}
}

class MyString {
public static String myJoin(char separator, String[] sArray) {
String joinedString = new String();
for (int i = 0 ; i < sArray.length-1 ; i++) {
joinedString += sArray[i] + separator;
}
joinedString = joinedString.substring(0, joinedString.length() - 1);
return joinedString;
}
}
Page | 85
Himanshu Tandon
08429802019
BCA 4EB
class Vector {
User[] array_vect;
int Length;
public Vector() {
array_vect = null;
Length = -1;
}
public Vector(User[] arr) {
array_vect = arr;
Length = arr.length;
}

public boolean validateUser(User item) {


int i = 0;
while(i < Length) {
if((array_vect[i].name().equals(item.name())) &&
(array_vect[i].password().equals(item.password()))) {
return true;
}
i++;
}
return false;
}
public boolean Contains(User item) {
int i = 0;
while(i < Length) {

Page | 86
Himanshu Tandon
08429802019
BCA 4EB
if(array_vect[i].name().equals(item.name())) {
return true;
}
i++;
}
return false;
}
public String addElement(User element) {
if(this.Contains(element)) {
return "MESSAGE:User already exists";
} else {
User[] temp_arr = new User[++Length];
for(int i = 0 ; i < Length ; i++) {
try {
temp_arr[i] = array_vect[i];
} catch (Exception e) {
temp_arr[i] = element;
}
}
array_vect = temp_arr;
return "MESSAGE:User added.";
}
}

public User elementAt(int index) {


return array_vect[index - 1];
}
Page | 87
Himanshu Tandon
08429802019
BCA 4EB
public void removeElement(User item) {
int index = -1;
for(int i = 0 ; i < Length ; i++) {
if(array_vect[i] == item) {
index = i;
break;
}
}
if(index != -1) {
User[] temp_arr = new User[Length - 1];
for(int i = 0 ; i<index ; i++) {
temp_arr[i] = array_vect[i];
}
for(int i = index ; i < Length-1 ; i++) {
temp_arr[i] = array_vect[i+1];
}
array_vect = temp_arr;
--Length;
}
else {
System.out.println("Element " + item.name() + " does not exist in the
list");
}
}
public void display() {
for(int i = 0 ; i < Length ; i++) {

Page | 88
Himanshu Tandon
08429802019
BCA 4EB
System.out.print(array_vect[i].name() + " ");
}
System.out.println();
}
}

public class twentyseven extends Applet implements


ActionListener,ItemListener,MouseMotionListener {

Vector userList;
Label headLabel,uNameLabel, pswdLabel;
TextField uNameTField, pswdTField;
Button signInButton,signUpButton;
CheckboxGroup dutyLocations;
Checkbox loc1,loc2,loc3,loc4;
List luggageItemList;
TextArea details;
Font font = new Font("Consolas",Font.BOLD,28);
Font font2 = new Font("Arial",Font.PLAIN,18);
boolean signup=false,signin=false,loginSuccess=false;

public void init() {

userList = new Vector();


addMouseMotionListener(this);
setLayout(null);
headLabel = new Label("Indian Navy \n Login");

Page | 89
Himanshu Tandon
08429802019
BCA 4EB
headLabel.setBounds(80, 5, 320, 80);
headLabel.setFont(font);
add(headLabel);

uNameLabel = new Label("Username: ");


uNameLabel.setBounds(80, 80, 100, 40);
uNameLabel.setFont(font2);
add(uNameLabel);

uNameTField = new TextField();


uNameTField.setBounds(185 ,90 ,160 ,20 );
uNameTField.setFont(font2);
add(uNameTField);

pswdLabel = new Label("Password: ");


pswdLabel.setBounds(80, 135, 100, 20);
pswdLabel.setFont(font2);
add(pswdLabel);

pswdTField = new TextField();


pswdTField.setBounds(185 ,135 ,160 ,20 );
pswdTField.setFont(font2);
add(pswdTField);

signUpButton = new Button("Sign-Up");


signUpButton.setBounds(80, 180, 130, 30);
signUpButton.setFont(font2);
Page | 90
Himanshu Tandon
08429802019
BCA 4EB
signUpButton.addActionListener(this);
add(signUpButton);

signInButton = new Button("Sign-In");


signInButton.setBounds(212, 180, 130, 30);
signInButton.setFont(font2);
signInButton.addActionListener(this);
add(signInButton);

Label head = new Label("Select Posting & Luggage item");


head.setFont(font2);
//head.setBounds(x, y, width, height);

dutyLocations = new CheckboxGroup();


loc1 = new Checkbox("Middle East",dutyLocations,false);
loc2 = new Checkbox("Korea",dutyLocations,false);
loc3 = new Checkbox("Indo-China",dutyLocations,false);
loc4 = new Checkbox("LOC",dutyLocations,false);
loc1.setBounds(100, 220, 100, 30);
loc2.setBounds(100, 260, 100, 30);
loc3.setBounds(100, 300, 100, 30);
loc4.setBounds(100, 340, 100, 30);
add(loc1);
add(loc2);
add(loc3);
add(loc4);
loc1.addItemListener(this);
Page | 91
Himanshu Tandon
08429802019
BCA 4EB
loc2.addItemListener(this);
loc3.addItemListener(this);
loc4.addItemListener(this);

luggageItemList = new List();


luggageItemList.add("Mattress");
luggageItemList.add("Sanitation");
luggageItemList.add("Pocket Knife");
luggageItemList.add("notebooks");
luggageItemList.add("Calculator");
luggageItemList.add("Binoculors");
luggageItemList.setBounds(210, 220, 90, 140);
luggageItemList.setMultipleMode(true);
add(luggageItemList);

details = new TextArea("",5,40);


details.setBounds(80, 400, 300, 100);
add(details);
}

public void actionPerformed(ActionEvent ae) {

String buttonName = ae.getActionCommand();


String posting = dutyLocations.getSelectedCheckbox().getLabel();
String[] luggage = luggageItemList.getSelectedItems();
User tempUser = new User(uNameTField.getText(),
pswdTField.getText(), posting, luggage);

Page | 92
Himanshu Tandon
08429802019
BCA 4EB
if(buttonName == "Sign-Up") {
signup = true;
signin = false;
SignUp(tempUser);
} else if(buttonName == "Sign-In") {
signin = true;
signup = false;
SignIn(tempUser);
}

public void SignUp (User tempUser) {


showStatus(userList.addElement(tempUser));

}
public void SignIn(User tempUser) {
boolean state = userList.validateUser(tempUser);
if(state) {
showStatus("User signed in successfully");
String userData = "Name: " + tempUser.name() + "\n"
+ "Posting: " + tempUser.posting() + "\n"
+ "Luggage: " + MyString.myJoin(',', tempUser.luggage()) +
"\n";
details.setText(userData);
}
else {

Page | 93
Himanshu Tandon
08429802019
BCA 4EB
showStatus("Login info is incorrect or not available.");
}
}

public void itemStateChanged(ItemEvent iEvent) {

}
public void mouseDragged(MouseEvent mEvent) {

}
public void mouseMoved(MouseEvent mEvent) {
//showStatus("("+mEvent.getX()+","+mEvent.getY()+")");
}
public void destroy() {
userList = null;
this.removeAll();
}
}

Page | 94
Himanshu Tandon
08429802019
BCA 4EB
Output

Page | 95
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #28
28. Write a program to show all Layout managers.

Ans.
Source Code
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

/**
* <applet code="twentyeight" width=400 height=400>
* </applet>
*/

public class twentyeight extends JApplet {


JButton b1,b2,b3,b4;
FlowLayout fl;
JPanel p = new JPanel();
public void init() {

b1 = new JButton("JButton1");
b2 = new JButton("JButton2");
b3 = new JButton("JButton3");
b4 = new JButton("JButton4");

fl = new FlowLayout(FlowLayout.CENTER);

getContentPane().add(p);

Page | 96
Himanshu Tandon
08429802019
BCA 4EB
p.setLayout(fl);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(b4);

}
}

Output

Page | 97
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #29
29. Write a program to show all Layout managers.
Ans.
Source Code
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

/**
* <applet code="twentynine" width=400 height=400>
* </applet>
*/

public class twentynine extends JApplet {


JButton b1,b2,b3,b4;
GridLayout gl;
JPanel p = new JPanel();
public void init() {

b1 = new JButton("JButton1");
b2 = new JButton("JButton2");
b3 = new JButton("JButton3");
b4 = new JButton("JButton4");

gl = new GridLayout(2,2);
getContentPane().add(p);
p.setLayout(gl);

Page | 98
Himanshu Tandon
08429802019
BCA 4EB
p.add(" 1",b1);
p.add(" 2",b2);
p.add(" 3",b3);
p.add(" 4",b4);

}
}

Output

Page | 99
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #30
30. Write a program to show all Layout managers.
Ans.
Source Code
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

/**
* <applet code="thirty" width=400 height=400>
* </applet>
*/

public class thirty extends JApplet {


JButton b1,b2,b3,b4,b5,b6;
BorderLayout bl;
JPanel p = new JPanel();
public void init() {

b1 = new JButton("JButton1");
b2 = new JButton("JButton2");
b3 = new JButton("JButton3");
b4 = new JButton("JButton4");
b5 = new JButton("JButton5");

bl = new BorderLayout();

Page | 100
Himanshu Tandon
08429802019
BCA 4EB
getContentPane().add(p);
p.setLayout(bl);
p.add(b1,BorderLayout.NORTH);
p.add(b2,BorderLayout.SOUTH);
p.add(b3,BorderLayout.EAST);
p.add(b4,BorderLayout.WEST);
p.add(b5,BorderLayout.CENTER);

}
}

Output

Page | 101
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #31
31. Write a program to show all Layout managers.
Ans.
Source Code
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

/**
* <applet code="thirtyone" width=400 height=400>
* </applet>
*/

public class thirtyone extends JApplet implements ActionListener {


JButton b1,b2,b3,b4;
CardLayout cl;
JPanel p = new JPanel();
public void init() {

b1 = new JButton("JButton1");
b2 = new JButton("JButton2");
b3 = new JButton("JButton3");
b4 = new JButton("JButton4");

cl = new CardLayout(10,10);

Page | 102
Himanshu Tandon
08429802019
BCA 4EB
getContentPane().add(p);
p.setLayout(cl);
p.add(" 1",b1);
p.add(" 2",b2);
p.add(" 3",b3);
p.add(" 4",b4);

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

}
public void actionPerformed(ActionEvent ae) {
cl.next(p);
}
}

Page | 103
Himanshu Tandon
08429802019
BCA 4EB
Output

Page | 104
Himanshu Tandon
08429802019
BCA 4EB
PRACTICAL #35
35. Create a Java applet with three buttons ‘Red’,’Green’,’Blue’.
Whenever user press any button the corresponding color should
be seen as background color in an applet window.

Ans.
Source Code
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/**
* <applet code="thirtyfive" height=400 width=400>
* </applet>
*/

public class thirtyfive extends Applet implements ActionListener {


String message;
Button b1 = null;
Button b2 = null;
Button b3 = null;
Color backColor;
Font MyFont = new Font("Arial",Font.BOLD,14);
public void init() {
b1 = new Button("RED");
b2 = new Button("GREEN");
Page | 105
Himanshu Tandon
08429802019
BCA 4EB
b3 = new Button("BLUE");

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

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
}
public void paint(Graphics g) {
setBackground(backColor);
g.setFont(MyFont);
g.drawString(message, 60, 60);
}
public void actionPerformed(ActionEvent ae) {
String actionCommand = ae.getActionCommand();

if(actionCommand == "RED") {
message = "RED BUTTON PRESSED";
backColor = Color.red;
} else if(actionCommand == "GREEN") {
message = "GREEN BUTTON PRESSED";
backColor = Color.green;
} else if(actionCommand == "BLUE") {
message = "BLUE BUTTON PRESSED";
backColor = Color.blue;
}

Page | 106
Himanshu Tandon
08429802019
BCA 4EB
repaint();
}
}

Output

Page | 107
Himanshu Tandon
08429802019
BCA 4EB

You might also like