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

JAGANNATH INTERNATIONAL

MANAGEMENT SCHOOL
(DEPT. OF INFORMATION TECHNOLOGY)

(P-VII) Java Lab Session: Feb 2022-June


2022
BCA-252

Submitted To Submitted By:


Ms. Minal Maheshwari Name: Khush Bhatt

Assistant Professor - Enroll. No.: 02321402020


IT
JIMS, VASANT KUNJ BCA- 4E
INDEX
S. No. Name of the Practical Date Signature

1 Write down the steps to compile and run a


Java Program? Write a program to print
Hello World.
To study the basics of programming

a. Write a program to read name, age, phone


no, gender and CGPA from user and print
the value.
b. WAP to find the largest and smallest of 3
numbers using if else statement
2 c. Write a Java program that takes three
numbers as input to calculate and print the
average of the numbers.
d. WAP to calculate Factorial of a number
e. WAP to check whether a given number is
Armstrong or not
f. WAP to check leap year.
g. Write a Java program that checks whether
a given string is a palindrome or not.
3 WAP to display integer values of an array
using for each loop.
4 WAP to print String Elements in array using
for each loop
5 Write a Java Program to implement array of
objects.
6 WAP to read the array dynamically, sort the
array and display the sorted array.
7 Write a Java Program to demonstrate use of
nested class.
8 Program to find Area of circle, Rectangle
and Triangle using different methods
9 Java program to demonstrate example of
static variable and static method.
10 WAP to implement Single Inheritance
11 WAP to implement Multilevel and
Hierarchy Inheritance
12 WAP to create a package in java
13 WAP to illustrate the concept of Method
Overriding
14 WAP to demonstrate the concept of Abstract
Class
15 Write a program to demonstrate use of
implementing interfaces.
16 Write a program to demonstrate use of
extending interfaces
17 Write an program using try, catch, throw and
finally
18 Write a program to implement the concept of
Exception Handling using predefined exception
19 Write a program to implement the concept of
Exception Handling by creating user-defined
exceptions.
20 Write a program to demonstrate thread priority.
21 WAP to implement the concept of
Multithreading
22 WAP to demonstrate Method overloading
23 WAP to show constructor overloading
24 Write a program to implement all string
operations.
25 Write a program to implement all string
operations using String Buffer Methods.
26 WAP to read the contents from file and writing
contents into a file
27 Develop an applet that displays a simple
message.
28 Write a GUI Program to Add Two Numbers
Using AWT and event handling.
WAP to make a login GUI using TextField,
29
PasswordField and Login Button using Swings.
30 Write a java program that connects to a
database using JDBC and perform add, delete
and retrieve operations.

PRACTICAL-1
Write down the steps to compile and run a Java Program. Write a program to print Hello
World.

Steps to compile and run a Java Program-


Open command prompt and set the directory by typing “drive name:”, For example-
d: .
Then go to the folder where you saved the program,
type “cd foldername”.
Type “javac programname.java” to compile the code.
Now type “java programname” to run the program.
public class hlloworld
{
public static void main(String args[]){
System.out.println("Khush Bhatt , 02321402020\n");
System.out.println("Hello World");
}
}

PRACTICAL-2
A. Write a program to read name, age, phone no, gender and CGPA from user
and print the value.

import java.util.Scanner;
public class userinput
{
public static void main(String args[]){
System.out.println("Khush Bhatt 02321402020\n");
Scanner s= new Scanner(System.in);
String name,gender;
int phone,cgpa, age;
System.out.println("Enter name: \n");
name = s.nextLine();
System.out.println("Enter gender: \n");
gender=s.nextLine();
System.out.println("Enter age: \n");
age = s.nextInt();
System.out.println("Enter phone number: \n");
phone=s.nextInt();
System.out.println("Enter cgpa: \n");
cgpa = s.nextInt();
System.out.println("NAME: "+ name +" "+ "AGE: "+ age +" "+"gender:
"+gender+" "+"phone number: "+phone+" "+"CGPA: "+ cgpa);
}}

B. WAP to find the greatest and smallest of 3 numbers using if else statement

import java.util.Scanner;
public class greatest{
public static void main(String args[]){
System.out.println("Khush bhatt 02321402020\n");
int num1,num2,num3;
Scanner s=new Scanner(System.in);
System.out.println("Enter 1st number: \n");
num1=s.nextInt();
System.out.println("Enter the 2nd number: \n");
num2=s.nextInt();
System.out.println("Enter the 3rd Number: \n");
num3=s.nextInt();
if(num1>num2 && num1>num3){
System.out.println(num1+" "+"is the greatest");}
else if(num2>num1 && num2>num3){
System.out.println(num2+" "+"is the greatest");}
else{
System.out.println(num3+" "+"is the greatest");}
}
}

import java.util.Scanner;
public class small{
public static void main(String args[]){
System.out.println("Shubham Patel 05121402020\n");
Scanner s=new Scanner(System.in);
int num1,num2,num3;
System.out.println("Enter 1st number: ");
num1=s.nextInt();
System.out.println("Enter the 2nd number: ");
num2=s.nextInt();
System.out.println("Enter the 3rd Number: ");
num3=s.nextInt();
if(num1<num2 && num1<num3){
System.out.println(num1+" "+"is the smallest");}
else if(num2<num1 && num2<num3){
System.out.println(num2+" "+"is the smallest");}
else{
System.out.println(num3+" "+"is the smallest");}
}
}

C. Write a Java program that takes three numbers as input to calculate and print
the average of the numbers.

import java.util.Scanner;
public class average{
public static void main(String args[]){
System.out.println("Khush Bhatt 02321402020\n");
int num1,num2,num3;
double avg=0.0;
Scanner s=new Scanner(System.in);
System.out.println("Enter 1st number: \n");
num1=s.nextInt();
System.out.println("Enter the 2nd number: \n");
num2=s.nextInt();
System.out.println("Enter the 3rd Number: \n");
num3=s.nextInt();
avg=(num1+num2+num3)/3;
System.out.println("The average of 3 numbers is: "+avg);
}
}

D. WAP to calculate Factorial of a number

import java.util.Scanner;
public class factorial{
public static void main(String args[]){
Scanner s=new Scanner(System.in);
System.out.println("Khush Bhatt 02321402020\n");
int num,i,fact=1;
System.out.println("Enter the number: \n");
num=s.nextInt();
for(i=1;i<=num;i++){
fact=fact*i;}
System.out.println("Factorial of the number is: "+fact);
}
}
E. WAP to check whether a given number is Armstrong or not

import java.util.Scanner;
public class armstrong
{
public static void main(String[] args)
{
System.out.println("Khush Bhatt 02321402020\n");
int x=0,a,temp;
int n;
System.out.println("Enter number");
Scanner s=new Scanner(System.in);
n=s.nextInt();
temp=n;
while(n>0)
{
a=n%10;
n=n/10;
x=x+(a*a*a);
}
if(temp==x)
System.out.println(temp+" is an armstrong number");
else
System.out.println(temp+" is not an armstrong number");
}
}
F. WAP to check leap year.

import java.util.Scanner;
public class LeapYear {
public static void main(String[] args){
System.out.println("Khush bhatt 05121402020");
int year;
System.out.println("Enter an Year :: ");
Scanner sc = new Scanner(System.in);
year = sc.nextInt();

if (((year % 4 == 0) && (year % 100!= 0)) || (year%400 == 0))


System.out.println("Specified year is a leap year");
else
System.out.println("Specified year is not a leap year");
}
}

G. Write a Java program that checks whether a given string is a palindrome or not.

import java.util.Scanner;
class pl
{
public static void main(String args[])
{
System.out.println("Khush bhatt 02321402020\n");
int l,i;
String str,rev="";
System.out.println("Enter the string::");
Scanner s = new Scanner(System.in);
str=s.next();
l=str.length();
for(i=l-1;i>=0;i--)
{
rev=rev+str.charAt(i);
}
if(str.equals(rev))
{
System.out.println(str+" is a palindrome");
}
else
System.out.println(str+" is not a palindrome");
}
}

PRACTICAL-3
WAP to display integer and string values of an array using for each loop.

import java.util.Scanner;
public class loop
{
public static void main(String args[])
{
System.out.println("Khush Bhatt 02321402020");
int arr[]={2,3,4,5,6,7};
String arr1[]={"a","e","i","o","u"};
for(int i:arr)
{
System.out.println(i);
}
for(String j:arr1){
System.out.println(j);}
}
}

PRACTICAL-4
WAP to read the array dynamically, sort the array and display the sorted array.
import java.util.Scanner;
import java.util.Arrays;
public class arraydn
{
public static void main(String args[])
{
int size,i;
System.out.println("enter the size of an array:");
Scanner s= new Scanner(System.in);
size=s.nextInt();
int[] a=new int[size];
System.out.println("Enter elements in the array :");
for(i=0;i<size;i++)
{
a[i]=s.nextInt();
}
System.out.println(Arrays.toString(a));
}}
PRACTICAL-5
Write a Java Program to demonstrate use of nested class.

class outer1
{
void outmethod()
{
class inner
{
void inmethod()
{

System.out.println("Inner class");
}
}
inner i=new inner();
i.inmethod();
}
public static void main(String args[])
{
outer c=new outer();
c.outmethod();
}
}
PRACTICAL-6
Java program to demonstrate example of static variable and static method.

import java.util.Scanner;
class static1
{
static int a;
static int fact(int a)
{
int b=1;
for(int i=a;i>1;i--)
{
b=b*i;
}
System.out.println("Factorial of "+a+" is : "+b);
return b;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter number to find factorial");

a=sc.nextInt(); fact(a);
}
}

PRACTICAL-7
WAP to implement Single Inheritance

class employee
{
int salary=10000;
}
public class programmer extends employee
{
int bonus=5000;
public static void main(String args[]){
System.out.println("Shubham Patel 05121402020");
programmer p=new programmer();
System.out.println("Salary: "+p.salary);
System.out.println("Bonus: "+p.bonus);
}
}

PRACTICAL-8
WAP to implement Multilevel and Hierarchy Inheritance

class dog
{
String name="dog";
}
class cat extends dog
{
String name1="cat";
}
public class rat extends cat
{
String name2="rat";
public static void main(String args[]){
System.out.println("Shubham Patel 05121402020\n");
rat r=new rat();
System.out.println(r.name);
System.out.println(r.name1);
System.out.println(r.name2);
}
}

PRACTICAL-9
WAP to create a package in java

package pack2;
public class C{
public void msg(){
System.out.println("Enter a number: ");
}
}

package pack3;
import pack2.*;
import java.util.Scanner;
class D{
public static void main(String args[]){
C obj=new C();
obj.msg();
int num;
Scanner s=new Scanner(System.in);
num=s.nextInt();
System.out.println("The number entered by you is: "+num);
}
}
PRACTICAL-10
WAP to illustrate the concept of Method Overriding and constructor overriding

class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
public class Bike2 extends Vehicle{
void run()
{System.out.println("Bike is running safely");}

public static void main(String args[]){

System.out.println("Shubham Patel 05121402020\n");


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}

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) {


System.out.println("Shubham Patel 05121402020\n");
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(10, "David");
System.out.println("Student Id : "+student.id + "\nStudent Name :
"+student.name);
}
}
PRACTICAL-11
Write an program using try, catch, throw and finally

import java.util.*;
import java.lang.*;
public class program1
{

static void validate(int age)


{
if(age<18)
throw new ArithmeticException("NOT VALID");
else
System.out.println("YOU CAN VOTE");
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter age ");
try
{
int a=sc.nextInt();
validate(a);
}
catch(Exception e)
{
System.out.println("PLEASE USE NUMERIC");
}
finally
{
System.out.println("This is finally block");
}
}
}
PRACTICAL-12
WAP to illustrate the concept of abstract class and abstract method

abstract class base


{
public base()
{
System.out.println("Base constructor");
}
public void sayHello()
{
System.out.println("Hello");
}
abstract public void greet();
}

class child extends base


{
public void greet()
{
System.out.println("Good Morning");
}
}
public class Abstract
{
public static void main(String args[])
{
System.out.println("\nName:- khush bhatt Enroll. no.:- 02321402020 \
n");
//base obj=new base();
//this line give error because we cannot create object of Abstract class
child obj=new child();
obj.greet();
}

}
PRACTICAL-13
WAP to demonstrate the use of implementing interfaces

import java.util.Scanner;
interface area
{
public void dimensions();
public void area();
}
public class Inter implements area
{
int length,breadth,area;
public void dimensions()
{
Scanner s=new Scanner(System.in);
System.out.print("Enter length: ");
length=s.nextInt();
System.out.print("Enter breadth: ");
breadth=s.nextInt();
}
public void area()
{
area=length*breadth;
System.out.print("\nArea :"+area);
}
public static void main(String[] args)
{
System.out.println("\nName:- khush bhatt Enroll. no.:-
02321402020 \n");
Inter obj=new Inter();
obj.dimensions();
obj.area();
}
}
PRACTICAL-14
WAP to implement the concept of exception handling using predefined and user
define exceptions.

A. PREDINED EXCEPTION

import java.util.Scanner;
class MyException extends Exception
{

public String tostring()


{
return "I am tostring()";
}
}

public class test


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

try
{
Scanner emp=new Scanner(System.in);
String name,dep;
int salary;
System.out.print("\nEnter your Name:- ");
name=emp.nextLine();
System.out.print("\nEnter your Department Name:-");
dep=emp.nextLine();
System.out.print("\nEnter your Salary:-");
salary=emp.nextInt();
System.out.println("Your Name is: "+name);
System.out.println("Your Department Name is: "+dep);
System.out.println("Your Salary is: "+salary);
}
catch(Exception obj)
{
System.out.println("Exception Occured:- " + obj);
}
}
}
B . CUSTOM EXCEPTION

// class representing custom exception


class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}

// class that uses custom exception InvalidAgeException


public class Custom
{

// method to check the age


static void validate (int age) throws InvalidAgeException{
if(age < 18){

// throw an object of user defined exception


throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}

// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");

// printing the message from InvalidAgeException object


System.out.println("Exception occured: " + ex);
}

System.out.println("rest of the code...");


}
}
}
}
PRACTICAL-15
WAP to demonstrate thread priority.

import java.lang.*;

public class Test extends Thread


{

// Method 1
// Whenever the start() method is called by a thread
// the run() method is invoked
public void run()
{
// the print statement
System.out.println("Inside the run() method");
}

// the main method


public static void main(String argvs[])
{
System.out.println("\nName:- khush bhatt Enroll. no.:- 02321402020 \
n");

// Creating threads with the help of ThreadPriority class


ThreadPriority th1 = new ThreadPriority();
ThreadPriority th2 = new ThreadPriority();
ThreadPriority th3 = new ThreadPriority();

// We did not mention the priority of the thread.


// Therefore, the priorities of the thread is 5, the default value

// 1st Thread
// Displaying the priority of the thread
// using the getPriority() method
System.out.println("Priority of the thread th1 is : " + th1.getPriority());

// 2nd Thread
// Display the priority of the thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());

// 3rd Thread
// // Display the priority of the thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());

// Setting priorities of above threads by


// passing integer arguments
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);

// 6
System.out.println("Priority of the thread th1 is : " + th1.getPriority());

// 3
System.out.println("Priority of the thread th2 is : " + th2.getPriority());

// 9
System.out.println("Priority of the thread th3 is : " + th3.getPriority());

// Main thread

// Displaying name of the currently executing thread


System.out.println("Currently Executing The Thread : " +
Thread.currentThread().getName());
System.out.println("Priority of the main thread is : " +
Thread.currentThread().getPriority());

// Priority of the main thread is 10 now


Thread.currentThread().setPriority(10);

System.out.println("Priority of the main thread is : " +


Thread.currentThread().getPriority());
}
}
PRACTICAL-16
WAP to Check the Thread Status using multithreading.

import java.util.Set;

class MyThread implements Runnable


{
public void run()
{
try
{
Thread.sleep(1500);
}
catch (Exception e)
{
System.out.println(e);
}
}
}

public class Status


{
public static void main(String args[]) throws Exception
{
System.out.println("\nName:- khush bhatt Enroll. no.:-
02321402020 \n");
for (int tn = 0; tn < 5; tn++)
{
Thread t = new Thread(new MyThread());
t.setName("MyThread:" + tn);
t.start();
}
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for (Thread t : threadSet)
{
System.out.println("Thread :" + t + ":" + "Thread status : " + t.getState());
}
}
}
PRACTICAL-17
WAP to explain multithreading concept.

A. MULTITHREADING BY EXTEND THREAD

class MultithreadingDemo extends Thread {


public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
public class Multithread1 {
public static void main(String[] args)
{
System.out.println("\nName:- khush bhatt Enroll. no.:-
023321402020 \n");
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}

}
B. MULTITHREADING BY IMPLEMENTS RUNNABLE THREAD
class MultithreadingDemo implements Runnable {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
class Multithread2 {
public static void main(String[] args)
{
System.out.println("\nName:- khush bhatt Enroll. no.:-
02321402020 \n");
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new MultithreadingDemo());
object.start();

} }

PRACTICAL-18
WAP to explain all the string operations

import java.util.Scanner;
public class string
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
String string1,string2,string3;
System.out.println("\nName:- khush bhatt Enroll. no.:-
02321402020 \n");
// get the length of string
System.out.println("***Length Operation***\n");
System.out.print("Enter the value in First String: ");
string1=obj.nextLine();
int length = string1.length();
System.out.println("Length: " + length);

System.out.println("\n***Concatination Operation***\n");
System.out.print("Enter the value in Second String to concatenate: ");
string2=obj.nextLine();
// join two strings
String joinedString = string1.concat(string2);
System.out.println("Joined String: " + joinedString);
System.out.println("\n***Comparision Operation***\n");
System.out.print("Enter the value in Third String for Comparision: ");
string3=obj.nextLine();

// compare first and second strings


boolean result1 = string1.equals(string2);
System.out.println("Strings first and second are equal: " + result1);

// compare first and third strings


boolean result2 = string1.equals(string3);
System.out.println("Strings first and third are equal: " + result2);

}
}
PRACTICAL-19
WAP to explain all the string operations using string buffer method.

import java.util.Scanner;

public class stringBuffer


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

System.out.println("\nName:- khush bhatt Enroll. no.:- 02321402020 \


n");

System.out.println("***append() method***\n");
//The append() method concatenates the given argument with this String.
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java

System.out.println("\n*** insert() method ***\n");


//The insert() method inserts the given String with this string at the given
position.
StringBuffer x=new StringBuffer("Hello ");
x.insert(1,"Java");//now original string is changed
System.out.println(x);//prints HJavaello
System.out.println("\n***replace() method ***\n");
//The replace() method replaces the given String from the specified beginIndex
and endIndex.
StringBuffer y=new StringBuffer("Hello");
y.replace(1,3,"Java");
System.out.println(y);//prints HJavalo

System.out.println("\n***delete() method***\n");
//The delete() method of the StringBuffer class deletes the String from the
specified beginIndex to endIndex.
StringBuffer z=new StringBuffer("Hello");
z.delete(1,3);
System.out.println(z);//prints Hlo

System.out.println("\n***reverse() method ***\n");


//The reverse() method of the StringBuilder class reverses the current String.
StringBuffer b=new StringBuffer("Hello");
b.reverse();
System.out.println(b);//prints olleH
}
}
PRACTICAL-20
WAP to read and write in a file

A. TO CREATE A FILE

import java.io.File; // Import the File class


import java.io.IOException; // Import the IOException class to handle errors

public class CreateFile {


public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
B. TO WRITE IN FILE

import java.io.FileWriter; // Import the FileWriter class


import java.io.IOException; // Import the IOException class to handle errors

public class WriteToFile {


public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
C. TO READ THE FILE

import java.io.File; // Import the File class


import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files

public class ReadFile {


public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
PRACTICAL-21
WAP to display user registration form using applet.

import java.awt.*;
public class Tes extends java.applet.Applet
{
public void init()
{

setLayout(new FlowLayout(FlowLayout.LEFT));

add(new Label("Name :"));


add(new TextField(10));

add(new Label("Address :"));


add(new TextField(10));

add(new Label("Birthday :"));


add(new TextField(10));

add(new Label("Gender :"));


Choice gender = new Choice();
gender.addItem("Man");
gender.addItem("Woman");
Component add = add(gender);
add(new Label("Job :"));
CheckboxGroup job = new CheckboxGroup();
add(new Checkbox("Student", job, false));
add(new Checkbox("Teacher", job, false));

add(new Button("Register"));
add(new Button("Exit"));
}}

HTML Code: -

<html>
<head><title>Register</title></head>
<body>
<applet code="Tes.class" width=230 height=300></applet>
</body>
</html>
PRACTICAL-22
WAP to explain important fields of AWT.

public class trycatch


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

public class cont extends Applet implements ActionListener


{
String name=" ", gender=" ";
int age;
TextField n=new TextField(10);
CheckboxGroup g=new CheckboxGroup();
Checkbox m=new Checkbox("male",g,true);
Checkbox f=new Checkbox("female",g,false);
Choice c=new Choice();
Label l1=new Label("Enter name:");
Label l2=new Label("Selec Gender:");
Label l3=new Label("age:");
Button b=new Button("Button");
public void init()
{
add(l1);
add(n);
add(l2);
add(m);
add(f);
add(l3);
c.add("10");
c.add("15");
c.add("20");
c.add("25");
c.add("30");
c.add("35");
add(c);
add(b);
b.addActionListener(this);
}
public void paint(Graphics g)
{
g.drawString("name: "+name,20,100);
g.drawString("Gender: "+gender,20,120);
g.drawString("age: "+age,20,140);
}
public void actionPerformed(ActionEvent e)
{
name=n.getText();
gender=g.getSelectedCheckbox().getLabel();
age=Integer.parseInt(c.getSelectedItem());
repaint();
}
}

HTML Code: -

<html>
<body>
<applet code="cont.class" height=1000 width=1000></applet>
</body>
</html>
PRACTICAL-23
WAP to explain important fields of event handling.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseExample extends MouseAdapter
{
Frame f;
MouseExample()
{
f=new Frame("Mouse Adapter");
f.addMouseListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
Graphics g=f.getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public static void main(String args[])
{
System.out.println("\nName:- Sameer Enroll. no.:- 04321402020 \n");
new MouseExample();
}
}
PRACTICAL-24
Write a GUI Program to Add Two numbers Using AWT and event
handling

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

public class sum extends Applet implements ActionListener


{
TextField t1=new TextField(10);
TextField t2=new TextField(10);
TextField t3=new TextField(10);
Label l1=new Label("Enter First Number: ");
Label l2=new Label("Enter Second Number: ");
Label l3=new Label("Sum: ");
Button B=new Button("ADD");
public void init(){
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(B);
B.addActionListener(this);
}

public void actionPerformed(ActionEvent e)


{
if(e.getSource()==B)
{
int num1= Integer.parseInt(t1.getText());
int num2= Integer.parseInt(t2.getText());
t3.setText("" +(num1+num2));
}
}
PRACTICAL-25
WAP to show database connection is established.Methods.

import java.sql.*;

public class est


{
public static void main(String[] args)
{
Connection con = null;

try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded");
// query="select * from student ";
con =DriverManager.getConnection("jdbc:mysql://localhost:3306/student"
, "root", "Sameer@000");
System.out.println("Connection established");
}
catch (ClassNotFoundException | SQLException e)
{
System.out.println("Exception caught " + e.getMessage());
}
}
}
PRACTICAL-26
WAP to make a login GUI using TextField, Password Field and Login Button using
Swings.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.Exception;

class CreateLoginForm extends JFrame implements ActionListener


{
JButton b1;
JPanel newPanel;
JLabel userLabel, passLabel;
final JTextField textField1,textField2;

CreateLoginForm()
{
userLabel = new JLabel();
userLabel.setText("Username");
textField1 = new JTextField(15);

passLabel = new JLabel();


passLabel.setText("Password");
textField2 = new JPasswordField(15);
b1 = new JButton("SUBMIT");
newPanel = new JPanel(new GridLayout(3, 1));
newPanel.add(userLabel);
newPanel.add(textField1);
newPanel.add(passLabel);
newPanel.add(textField2);
newPanel.add(b1);
add(newPanel, BorderLayout.CENTER);
b1.addActionListener(this);
setTitle("LOGIN FORM");
}
public void actionPerformed(ActionEvent ae)
{
String userValue = textField1.getText();
String passValue = textField2.getText();

if (userValue.equals("sameer") && passValue.equals("NHLPS"))


{
System.out.println("Login Succesfully");
}

else
{
System.out.println("Please enter valid username and password");
}
}
}

public class LoginFormDemo


{
public static void main(String arg[])
{
try
{
CreateLoginForm form = new CreateLoginForm();
form.setSize(300, 100);
form.setVisible(true);
}

catch (Exception e)
{
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}

You might also like