0% found this document useful (0 votes)
7 views89 pages

Java Lab

The document contains a collection of Java programming exercises, including algorithms and sample code for various tasks such as calculating the sum of digits, swapping numbers, checking Armstrong numbers, generating Fibonacci series, and more. Each exercise includes a clear aim, algorithm steps, and a Java program implementation. The document also provides outputs and results confirming successful execution of the programs.

Uploaded by

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

Java Lab

The document contains a collection of Java programming exercises, including algorithms and sample code for various tasks such as calculating the sum of digits, swapping numbers, checking Armstrong numbers, generating Fibonacci series, and more. Each exercise includes a clear aim, algorithm steps, and a Java program implementation. The document also provides outputs and results confirming successful execution of the programs.

Uploaded by

Pradeep deepu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

No Program Signature

1 Sum of digits

2 Swapping Numbers

3 Armstrong Number

4 Fibonacci Series

5 Even or Odd

6 Largest of Three Numbers

7 Average of 5 Numbers

8 Diamond Pattern

9 Sum of Positive Numbers

10 Matrix Multiplication

11 Method Overloading

12 Area of Circle & Triangle

13 Abstract Class Shapes

14 Student Info (Inheritance)

15 Area & Perimeter (Shapes)

16 Bank Account with Threads

17 Multithreading Strings

18 Synchronized Methods
Multiple Inheritance
19
(Interface)
20 User Defined Packages

21 Cube Using Package

22 Multiple Catch Block

23 Division with Exceptions

24 User Defined Exception

25 Read File Content

26 Vowel Words in File

27 Applet Message

28 Applet Smiley

29 Applet Factorial

30 Mouse Events

31 Login Window (Swing)

32 Calculator (Swing)

33 Swing Login with JDBC


EXERCISE NO : 1
BASIC PROGRAM
DATE:

1A. Write a Java program that reads an integer between 0 and 1000 and adds all the digits in the
integer.

AIM:
To write a java program to perform swapping of two number.

ALGORITHM:

Step 1: Start the program.


Step 2: We first prompt the user to enter an integer between 0 and 1000.
Step 3: We check if the entered number is within the valid range.
Step 4: Add it to the ‘sum’, and remove the rightmost digit by dividing ‘tempNumber’ by 10.
Step 5: Stop the program.

PROGRAM:
import java.util.Scanner;
public class DigitSumCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer between 0 and 1000: ");
int number = scanner.nextInt();
int digitSum = calculateDigitSum(number);
System.out.println("The sum of the digits is: " + digitSum);
scanner.close();
}
private static int calculateDigitSum(int number)

1
{
int sum = 0;
while (number > 0) {
int digit = number % 10;
sum += digit;
number /= 10;
}
return sum;
}
}

OUTPUT:

RESULT:
Thus the program has been successfully executed.

2
1B. Write a java program to perform swapping of two number.

AIM:

To write a java program to perform swapping of two number.

ALGORITHM:

Step 1: Start the program.


Step 2: Enter the two number to be swapped.
Step 3: We store the first number in the variable ‘number1’ and the second and the second
number in the variable ‘number2’.
Step 4: We assign the value of ‘number2’ to ‘number1’ and then assign the value of temp to
‘number2’.
Step 5: This swaps the values two variable.

PROGRAM:
public class NumberSwapper {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
System.out.println("Before swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
int temp = num1;
num1 = num2;
num2 = temp;
System.out.println("After swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}
}

3
OUTPUT:

RESULT:
Thus the program has been successfully executed.

4
1C. Write a program to check whether the given number is Armstrong number.

AIM:

To write a java program to check whether the given number is Armstrong number or not.

ALGORITHM:

Step 1: Start the program.


Step 2: We then call the ‘isArmstrongNumber()’ function to check whether the given number is
an Armstrong number.
Step 3: A ‘while’ loop to extact the rightmost digit of the ‘number’ using the modulo operator
%, cube.
Step 4: The digit using ‘Math.pow()’, add it to the ‘sum’, and remove the rightmost digit by
dividing ‘number’ by 10.
Step 5: This process continues until ‘number’ becomes 0, which means we have processed all
the digits.
Step 6: Stop the program.

PROGRAM:
import java.util.Scanner;
public class ArmstrongNumberChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (isArmstrongNumber(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
}
public static boolean isArmstrongNumber(int number) {
int originalNumber = number;
int numDigits = String.valueOf(number).length();

5
int sum = 0;
while (number != 0) {
int digit = number % 10;
sum += Math.pow(digit, numDigits);
number /= 10;
}
return sum == originalNumber;
}
}

OUTPUT:

RESULT:
Thus the program has been successfully executed.

6
1D. Write a java program to perform Fibonacci series.

AIM:

To write a java program to perform Fibonacci series.

ALGORITHM:

Step 1: Start the program.


Step 2: A for loop to iterate ‘numTerms’ times and print the Fibonacci numbers.
Step 3: If n is 0 or 1, we simply return n as it represents the base cases for the ‘Fibonnaci’ series.
Step 4: Calculate the previous two Fibonacci numbers and add them together to get the current
Fibonacci number.
Step 5: Stop the program.

PROGRAM:
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int n = scanner.nextInt();
System.out.println("Fibonacci Series:");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
public static int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
}

7
OUTPUT:

RESULT:
Thus the program has been successfully executed.

8
1E. Write a java program to check for even or odd number.

AIM:

To write a java program to check for even or odd number.

ALGORITHM:

Step 1: Start the program.


Step 2: The ‘isEven()’ function to check whether the given number is even.
Step 3: Inside the ‘isEven()’ function, we use the modulo operator % to check if the number is
divible evenly by 12.
Step 4: If the remainder is 0, it means the number is even, so we return ‘true’. Otherwise, we
return ‘false’.
Step 5: Stop the program.

PROGRAM:
import java.util.Scanner;
public class EvenOddChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (number % 2 == 0) {
System.out.println(number + " is an even number.");
} else {
System.out.println(number + " is an odd number.");
}

scanner.close();
}
}

9
OUTPUT:

RESULT:
Thus the program has been successfully executed.

10
PROGRAM TO IMPLEMENT VARIOUS LOOPING
EXERCISE NO : 2 STRUCTURES AND ARRAYS
DATE:

1. Looping structures:
2A.Write a java program to find the largest of three numbers.

AIM:
To write a java program to find the largest of three numbers.

ALGORITHM:

Step 1: Start the program.


Step 2: In this program, we use the ‘Scanner’ class to read three numbers from the user.
Step 3: The ‘findLargest’ method takes three numbers as parameter and compares them to find
the largest one.
Step 4: Finally, the result is printed to the console.
Step 5: Stop the program.

PROGRAM:
import java.util.Scanner;
public class LargestOfThreeNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.println("Enter the second number: ");
int num2 = scanner.nextInt();
System.out.println("Enter the third number: ");
int num3 = scanner.nextInt();
int largestNumber = num1;
if (num2 > largestNumber) {
largestNumber = num2;
}
if (num3 > largestNumber) {

11
largestNumber = num3;
}
System.out.println("The largest number is: " + largestNumber);
}
}

OUTPUT:

RESULT:
Thus the program has been successfully executed.

12
2B. Write a Java program to find the average of 5 numbers using a while loop.

AIM:

To execute the java program to find average of 5 numbers using a while loop.

ALGORITHM:

Step 1: Start the program


Step 2: We initialize two variable ‘count’ and ‘sum’ to keep track of the number of inputs and
the sum of the numbers
Step 3: Inside the loop, we read a number from the user and add it to the ‘sum’.
Step 4: We also increment the ‘count’ by 1 each iteration.
Step 5: Stop the program.

PROGRAM:

import java.util.Scanner;
public class Average
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int sum = 0;
int count = 1;
while (count <= 5) {
System.out.println("Enter number " + count + ":");
int number = scanner.nextInt();
sum += number;
count++;
}
double average = sum / 5;
System.out.println("The average is " + average);
}
}

13
OUTPUT:

RESULT:
Thus the program has been successfully executed.

14
2C. Write a program in Java to display the pattern like a diamond.Test Data (Input number of
rows (half of the diamond)) :7

AIM:
To a program in Java to display the pattern like a diamond.Test Data (Input number of rows (half
of the diamond)) :7

ALGORITHM:

Step 1: Start the program.


Step 2: This program first asks the user to enter the number of rows (half of the diamond).
Step 3: Then, it uses two nested loops to print the diamond pattern.
Step 4: The number of spaces and asterisks to be printed is determined by the current row number.
Step 5: Stop the program.

PROGRAM:

import java.util.Scanner;
public class Exercise21 {
public static void main(String[] args)
{
int i,j,r;
System.out.print("Input number of rows (half of the diamond) : ");
Scanner in = new Scanner(System.in);
r = in.nextInt();
for(i=0;i<=r;i++)
{
for(j=1;j<=r-i;j++)
System.out.print(" ");
for(j=1;j<=2*i-1;j++)
System.out.print("*");
System.out.print("\n");
}
for(i=r-1;i>=1;i--)
{
for(j=1;j<=r-i;j++)
System.out.print(" ");
for(j=1;j<=2*i-1;j++)
System.out.print("*");
System.out.print("\n");

15
}
}
}

OUTPUT:

RESULT:
Thus the program has been successfully executed.

16
2D. Write a Java program to find the sum of positive numbers using do-while loop.

AIM:
To a Java program to find the sum of positive numbers using do-while loop.

ALGORITHM:

Step 1: Stop the program.


Step 2: This program first creates a Scanner object to read user input.
Step 3: Then, it initializes two variables, `number` and `sum`.
Step 4: The `number` variable will store the user-inputted number, and the `sum` variable will
store the sum of all positive numbers.
Step 5: Stop the program.

PROGRAM:

import java.util.Scanner;
public class SumOfPositiveNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = 0;
int sum = 0;
do {
System.out.print("Enter a positive number: ");
number = scanner.nextInt();
if (number > 0) {
sum += number;
}
} while (number > 0);
System.out.println("The sum of positive numbers is " + sum);
}
}

17
OUTPUT:

RESULT:
Thus the program has been successfully executed.

18
2E. Write a java program for matrix multiplication.

AIM:
To a java program for matrix multiplication.

ALGORITHM:

Step 1: Start the program.


Step 2: First gets the dimensions of the two matrices from the user. Then, it creates the two
matrices and the product matrix.
Step 3: Finally, it loops through the product matrix and prints its elements.
Step 4: To run this program, you can save it as a `.java` file and compile it using the `javac`
command.
Step 5: Stop the program.

PROGRAM:

public class MatrixMultiplicationExample


{
public static void main(String args[])
{
int a[][]={{2,4,5},{1,4,6},{2,2,2}};
int b[][]={{2,9,6},{10,2,2},{3,3,3}};
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();
}
}
}

19
OUTPUT:

RESULT:
Thus the program has been successfully executed.

20
EXERCISE NO : 3 PROGRAM TO ILLUSTRATE USE OF OVERLOADING
AND OVERRIDING
DATE:

3A. Write a java program to implement method overloading based on the number of arguments.
Create three methods with the same name but all methods have a different number of arguments
to calculate the sum of given arguments.

AIM:

To Create three methods with the same name but all methods have a different number of arguments
to calculate the sum of given arguments

ALGORITHM:

Step 1: Start the program.


Step 2: This program defines three methods named `sum()`.
Step 3: The first method takes two arguments, the second method takes three arguments, and the
third method takes four arguments.
Step 4: The `main()` method of the program calls each of the `sum()` methods with different
arguments and prints the results.
Step 5: Stop the program.

PROGRAM:

public static int sum(int a, int b) {


return a + b;
}
public static int sum(int a, int b, int c) {
return a + b + c;
}
public static int sum(int a, int b, int c, int d) {
return a + b + c + d;
}
public static void main(String[] args) {
System.out.println(sum(1, 2));
System.out.println(sum(1, 2, 3));

21
System.out.println(sum(1, 2, 3, 4));
}
}

OUTPUT:

RESULT:
Thus the program has been successfully executed.

22
3B. Write a java program to find area of cricle and triangle.

AIM:
To write a program to find area of cricle and triangle.

ALGORITHM:

Step 1: Start the program.


Step 2: Then, it calculates the area of the circle using the formula `Math.PI * radius * radius`.
Step 3: Next, the program gets the base and height of the triangle from the user.
Step 4: Then, it calculates the area of the triangle using the formula `(base * height) / 2`.
Step 5: Finally, the program prints the areas of the circle and the triangle.
Step 6: Stop the program.

PROGRAM:

import java.util.Scanner;
public class Area {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the radius of the circle: ");
int radius = scanner.nextInt();
double areaOfCircle = Math.PI * radius * radius;
System.out.print("Enter the base of the triangle: ");
int base = scanner.nextInt();
System.out.print("Enter the height of the triangle: ");
int height = scanner.nextInt();
double areaOfTriangle = (base * height) / 2;
System.out.println("The area of the circle is " + areaOfCircle);
System.out.println("The area of the triangle is " + areaOfTriangle);
}
}

23
OUTPUT:

RESULT:
Thus the program has been successfully executed.

24
EXERCISE NO : 4 PROGRAM TO ILLUSTRATE THE USE OF INHERITANCE
DATE:

4A. To create an abstract class named shape that contains two integers and an empty method
named printArea. Provide three classes named Rectangle, Triangle and Circle subclass that each
one of the classes extends the Class Shape. Each one of the classes contains only the method
printArea() that prints the area of Shape.

AIM:
To create an abstract class named shape that contains two integers and an empty method named
printArea. Provide three classes named Rectangle, Triangle and Circle subclass that each one of
the classes extends the Class Shape. Each one of the classes contains only the method printArea()
that prints the area of Shape.

ALGORITHM:

Step 1: Start the program.


Step 2: To create an abstract class named `Shape` that contains two integers and an
empty method named `printArea`.
Step 3: It also provides three classes named `Rectangle`, `Triangle`, and `Circle` that extend
the class `Shape`.
Step 4: Each one of the classes contains only the method `printArea()` that prints the area of
the shape.
Step 5: Stop the program.

PROGRAM:

abstract class Shape {


private String name;
public Shape() {
this.name = "Unknown shape";
}
public Shape(String name) {
this.name = name;
}

25
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
public abstract void draw();
public abstract double getArea();
public abstract double getPerimeter();
}
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
super("Rectangle");
this.width = width;
this.height = height;
}
public void draw() {
System.out.println("Drawing a rectangle...");
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2.0 * (width + height);
}
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
super("Circle");
this.radius = radius;
}
public void draw() {
System.out.println("Drawing a circle...");
}
public double getArea() {

26
return Math.PI * radius * radius;
}
public double getPerimeter() {
return 2.0 * Math.PI * radius;
}
}
class ShapeUtil {
public static void drawShapes(Shape[] list) {
for (int i = 0; i < list.length; i++)
list[i].draw();
}
}
public static void printShapeDetails(Shape[] list) {
for (int i = 0; i < list.length; i++)
String name = list[i].getName();
double area = list[i].getArea();
double perimeter = list[i].getPerimeter();
System.out.println("Name: " + name);
System.out.println("Area: " + area);
System.out.println("Perimeter: " + perimeter);
}
}
}
public class Main {
public static void main(String[] args) {
Shape[] shapeList = new Shape[2];
shapeList[0] = new Rectangle(2.0, 4.0);
shapeList[1] = new Circle(5.0);
ShapeUtil.drawShapes(shapeList);
ShapeUtil.printShapeDetails(shapeList);
}
}

27
OUTPUT:

RESULT:
Thus the program has been successfully executed.

28
4B. Write a java program to print a student information using multilevel inheritance.

AIM:

To write a java program to print a student information using multilevel inheritance.

ALGORITHM:

Step 1: Start the program.


Step 2: The Person class is the base class, and the Student and GraduateStudent classes inherit
from the Person class.
Step 3: The GraduateStudent class inherits all the properties and methods from the Person and
Student classes.
Step 4: The main() method creates a GraduateStudent object and prints the student's information.
Step 5: Stop the program.

PROGRAM:

class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void printInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
class Student extends Person {
String studentId;
public Student(String name, int age, String studentId) {
super(name, age);
this.studentId = studentId;
}
public void printInfo() {
super.printInfo();
System.out.println("Student ID: " + studentId);

29
}
}
class GraduateStudent extends Student {
String degree;
public GraduateStudent(String name, int age, String studentId, String degree) {
super(name, age, studentId);
this.degree = degree;
}
public void printInfo() {
super.printInfo();
System.out.println("Degree: " + degree);
}
public static void main(String[] args) {
GraduateStudent student = new GraduateStudent("John Doe", 21, "123456", "Masters");
student.printInfo();
}
}

OUTPUT:

RESULT:
Thus the program has been successfully executed.

30
4C. Write a java program to print area and perimeter circle, square and triangle using hierarchy
inheritance.

AIM:
To write a java program to print area and perimeter circle, square and triangle using hierarchy
inheritance.

ALGORITHM:

Step 1: Start the program.


Step 2: This program first creates a `Shape` object.
Step 3: Then, it prompts the user to enter the side of the shape and the type of shape they want
to calculate.
Step 4: The program then creates a new object of the appropriate type and calculates the area and
perimeter of the shape.
Step 5: Finally, the program prints the results.
Step 6: To run the program, you can save it as a `.java` file and compile it using the `javac`
command.
Step 7: Stop the program.

PROGRAM:

import java.util.Scanner;
public class Perimeter
{
int r, l, b, s1, s2, s3;
double pi = 3.14,perimeter;
Scanner s = new Scanner(System.in);
void circle()
{
System.out.print("Enter radius of circle:");
r = s.nextInt();
perimeter = 3 * pi * r;
System.out.println("Perimeter of circle:"+perimeter);
}
void rectangle()
{
System.out.print("Enter length of rectangle:");
l = s.nextInt();

31
System.out.print("Enter breadth of rectangle:");
b = s.nextInt();
perimeter = 3 * (l + b);
System.out.println("Perimeter of rectangle:"+perimeter);
}
void triangle()
{
System.out.print("Enter length of first side of triangle:");
s1 = s.nextInt();
System.out.print("Enter length of second side of triangle:");
s2 = s.nextInt();
System.out.print("Enter length of third side of triangle:");
s3 = s.nextInt();
perimeter = s1 + s2 + s3;
System.out.println("Perimeter of triangle:"+perimeter);
}
public static void main(String[] args)
{
Perimeter obj = new Perimeter();
obj.circle();
obj.rectangle();
obj.triangle();
}
}

32
OUTPUT:

RESULT:
Thus the program has been successfully executed.

33
EXERCISE NO : 5 PROGRAM TO ILLUSTRATE THE USE OF MULTI-
THREADING
DATE:

5A. Write a Java program that creates a bank account with concurrent deposits and withdrawals
using threads.

AIM:
To write a java program creates a bank account with concurrent deposits and withdrawals using
threads.

ALGORITHM:

Step 1: Start the program.


Step 2: This program creates a bank account with an initial balance of 0.
Step 3: Then creates two threads, one that deposits 100 each time it runs, and the other that
withdraws 50 each time it runs.
Step 4: The threads run concurrently, and the final balance of the account is printed to the console.
Step 5: Create a BankAccount object and initialize the balance to 0.0 and create a ReentrantLock
object.
Step 6: Stop the program.

PROGRAM:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class BankAccount {
private double balance;
private Lock lock;
public BankAccount() {
balance = 0.0;
lock = new ReentrantLock();
}
public void deposit(double amount) {
lock.lock();
try {

34
balance += amount;
System.out.println("Deposit: " + amount);
System.out.println("Balance after deposit: " + balance);
} finally {
lock.unlock();
}
}
public void withdraw(double amount) {
lock.lock();
try {
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawal: " + amount);
System.out.println("Balance after withdrawal: " + balance);
} else {
System.out.println("Try to Withdraw: " + amount);
System.out.println("Insufficient funds. Withdrawal cancelled.");
}
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
BankAccount account = new BankAccount();
Thread depositThread1 = new Thread(() -> account.deposit(2000));
Thread depositThread2 = new Thread(() -> account.deposit(500));
Thread withdrawalThread1 = new Thread(() -> account.withdraw(200));
Thread withdrawalThread2 = new Thread(() -> account.withdraw(1500));
depositThread1.start();
depositThread2.start();
withdrawalThread1.start();
withdrawalThread2.start();
}
}

35
OUTPUT:

RESULT:
Thus the program has been successfully executed.

36
5B. Write a java program generalize multithreading for an sample sequence of strings with a
delay of 1000 millisecond for displaying it using Java threads.

AIM:
To write a java program to generalize multithreading for an sample sequence of strings with a
delay of 1000 millisecond for displaying it using Java threads.

ALGORITHM:

Step 1: Start the program.


Step 2: Create a class named MyThread that extends the Thread class.
Step 3: This program will create 4 threads, one for each string in the sequence.
Step 4: Each thread will sleep for 1000 milliseconds, and then print the string it is responsible
for. The threads will be executed in parallel, so the strings will be printed in a non-deterministic
order.
Step 5: The program will print the strings in a non-deterministic order, with a delay of 1000
milliseconds between each string.
Step 6: Stop the program.

PROGRAM:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MultithreadingDemo {
public static void main(String[] args) {
String[] strings = {"Hello", "World", "Java", "Multithreading"};
ExecutorService executorService = Executors.newFixedThreadPool(4);
for (String string : strings) {
executorService.submit(() -> {
try {
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(string);
});
}

37
executorService.shutdown();
}
}

OUTPUT:

RESULT:
Thus the program has been successfully executed.

38
5C. Write a java program to identify the use of synchronized blocks to synchronized methods.

AIM:
To write a java program to identify the use of synchronized blocks to synchronized methods.

ALGORITHM:

Step 1: Start the program.


Step 2: The `increment()` method is a synchronized method, which means that only one thread
can execute it at a time.
Step 3: This program has two methods in the `Counter` class: `increment()` and
`incrementUsingBlock()`.
Step 4: The main() method of the `SynchronizedDemo` class creates two threads, each of
which calls one of the `increment()` methods.
Step 5: The `incrementUsingBlock()` method uses a synchronized block, which means that
only one thread can execute the code inside the block at a time.
Step 6: Stop the program.

PROGRAM:

import java.io.*;
class Line
{
public void getLine()
{
for (int i = 0; i < 5; i++)
{
System.out.println(i);
try
{
Thread.sleep(400);
}
catch (Exception e)
{
System.out.println(e);
}
}

39
}
}

class Train extends Thread


{
Line line;

Train(Line line)
{
this.line = line;
}
@Override
public void run()
{
line.getLine();
}
}
class GFG
{
public static void main(String[] args)
{
Line obj = new Line();
Train train1 = new Train(obj);
Train train2 = new Train(obj);
train1.start();
train2.start();
}
}

40
OUTPUT:

RESULT:
Thus the program has been successfully executed.

41
EXERCISE NO : 6 PROGRAM TO IMPLEMENT THE CONCEPT OF
INTERFACES AND PACKAGES
DATE:

6A. Write a java program to illustrate the multiple inheritance by using Interfaces.

AIM:
To write a java program to illustrate the multiple inheritance by using Interfaces.

ALGORITHM:

Step 1: Start the program.


Step 2: This program illustrates how multiple inheritance can be achieved using interfaces.
Step 3: This program defines two interfaces, a`Bird`, and a class `Duck` that implements both
interfaces.
Step 4: Inside the main method:
 Create an instance of the Duck class called a.
 Invoke the eat method on the a object, which will print "Duck is walking".
 Invoke the travel method on the a object, which will print "Duck is
swimming".
Step 5: The `Duck` class implements both of these methods, so it can make a sound and fly. The
main method of the program creates a `Duck` object and calls the `makeSound()` and `fly()`
methods. Stop the program.

PROGRAM:
interface Walkable {

void walk();

interface Swimmable {

void swim();

42
}

class Duck implements Walkable, Swimmable {

public void walk()

System.out.println("Duck is walking.");

public void swim()

System.out.println("Duck is swimming.");

class Main {

public static void main(String[] args)

Duck duck = new Duck();

duck.walk();

duck.swim();

43
OUTPUT:

RESULT:
Thus the program has been successfully executed.

44
6B. Write a java program to demonstrate use of user defined packages.

AIM:
To a java Program to demonstrate use of user defined packages.

ALGORITHM:

Step 1: Start the program.


Step 2: The first line of the code declares the package name as `packagename`.
Step 3: Create two package Import package.*; Import package.ClassName; Using fully qualified
class.
Step 4: Display output.
Step 5: Stop the program.

PROGRAM:

a) USING PACKAGENAME.
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();

obj.msg();

45
OUTPUT:

b) USING PACKAGE.CLASSNAME
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
Package mypack;

import pack.A;

class B{

public static void main(String args[]){

pack.A obj = new pack.A();

obj.msg();

OUTPUT:

c) USING FULLY QUALIFIED NAME

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

46
package mypack;

class B{

public static void main(String args[]){

pack.A obj = new pack.A();

obj.msg();

}}

OUTPUT:

RESULT:
Thus the program has been successfully executed.

47
6C. Write a java program to find the cube of a number for various data types using package and
then import and display the results.

AIM:

To write a Program to find the cube of a number for various data types using package and then
import and display the results

ALGORITHM:

Step 1: Start the program.


Step 2: It will import the Cube class from the math package and calculate the cubes of different
numbers.
Step 3: This class will contain methods to calculate the cube for different data types:
Step 4: Let's create the main program in a separate file.
Step 5: Stop the program.

PROGRAM:

public class cube{


public static void main(String args[])
{
int a=4;
int volume=a*a*a;
System.out.println("Volume ot the cube="+volume);
}
}

48
OUTPUT:

RESULT:
Thus the program has been successfully executed.

49
EXERCISE NO : 7 GENERATE THE PROGRAM USING EXCEPTIONS
HANDLING MECHANISM
DATE:

7A. Write a Java program to illustrate multiple catch block using command line argument.
AIM:

To Write a Java program to illustrate multiple catch block using command line argument

ALGORITHM:

Step 1: Start the program.


Step 2: The ‘ArrayIndexOutOfBoundsException’ catch block handles the case when
insufficient command line arguments are provided.
Step 3: The ‘NumberFormatException’ catch block handles the case when the index value is
not a valid integer.
Step 4: The ‘generic Exception catch block’handles any other exceptions that might occur. It
prints a stack trace to provide more information about the exception.
Step 5: In this program, we have a main method that accepts command line arguments.
Step 6: Stop the program.

PROGRAM:

public class MultipleCatchBlock2 {


public static void main(String[] args) {
try{
int a[]=new int[5];
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}

50
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

OUTPUT:

RESULT:
Thus the program has been successfully executed.

51
7B. Write a program that creates a user interface to perform integer divisions. The user enters two
numbers in the text fields, Num1 and Num2. The division of Num1 and Num2 is displayed in the
Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program
would throw a NumberFormatException. If Num2 were Zero, the program would throw an
Arithmetic Exception Display the exception in a message dialog box.

AIM:

Write a program that creates a user interface to perform integer divisions.

ALGORITHM:

Step 1: Start the program.


Step 2: The ‘initComponents()’ method initializes the text fields, result field, and divide
button.
Step 3: The ‘actionPerformed()’ method is invoked when the divide button is clicked.
Step 4: If a ‘NumberFormatException’ occurs, it displays an error message dialog indicating
invalid input. If an ‘ArithmeticException’ occurs due to division by zero, it shows an error
message dialog with the corresponding exception message.
Step 5: In the main() method, we create an instance of IntegerDivisionUI and make it visible
using ‘SwingUtilities.invokeLater()’ to ensure proper initialization and rendering on the Swing
Event Dispatch Thread.
Step 6: Stop the program.

PROGRAM:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*:

public class Division extends JFrame implements ActionListener


{
Container c;
JButton btn;
JLabel lbl1,lbl2,lbl3;
JTextField tf1,tf2,tf3;
JPanel p;

Division()
{
super(“Exception Handler”);
c=getContentPane();

52
c.setBackground(Color.red);
btn=new JButton(“DIVIDE”);
btn.addActionListener(this);
tf1=new JTextField(30);
tf2=new JTextField(30);
tf3=new JTextField(30);
lbl1=new JLabel(“NUM 1”);
lbl2=new JLabel(“NUM 2”);
lbl3=new JLabel(“RESULT”);
p=new JPanel();
p.setLayout(new GridLayout(3,2));
p.add(lbl1);
p.add(tf1);
p.add(lbl2); p.add(tf2);
p.add(lbl3); p.add(tf3);
c.add(new JLabel(“Division”),”North”);
c.add(p,”Center”);
c.add(btn,”South”);
}

public void actionPerformed(ActionEvent e)


{
if(e.getSource()==btn)
{
try
{
int a=Integer.parseInt(tf1.getText());
int b=Integer.parseInt(tf2.getText());
int c=a/b;
tf3.setText(“”+c);
}
catch(NumberFormatException ex)
{
tf3.setText(“–“);
JOptionPane.showMessageDialog(this,”NumberFormatException”);
}
catch(ArithmeticException ex)
{
tf3.setText(“–“);
JOptionPane.showMessageDialog(this,”Division by zero”);
}
catch(Exception ex)
{
tf3.setText(“–“);
JOptionPane.showMessageDialog(this,”Other Err “+ex.getMessage());

53
}
}

public static void main(String args[])


{
Division b=new Division();
b.setSize(200,200);
b.setVisible(true);
}
}

54
OUTPUT:

RESULT:
Thus the program has been successfully executed.

55
7C. Write a java program for user defined exception.

AIM:
To write a java Program for user defined exception

ALGORITHM:

Step 1: Start the Program.


Step 2: The ‘InvalidAgeException’ class has a constructor that accepts a message and passes it
to the superclass constructor using the super() statement.
Step 3: We also have a class called User, which represents a user with a name and age. The
constructor of the User class throws an ‘InvalidAgeException’ if the age provided is negative.
Step 4: In the main() method, we create a User object with a negative age to trigger the custom
exception.
Step 5: We catch the ‘InvalidAgeException’ and print the error message using ‘getMessage()’.

PROGRAM:

class InvalidAgeException extends Exception


{
public InvalidAgeException (String str)
{
super(str);
}
}
public class TestCustomException1
{
static void validate (int age) throws InvalidAgeException{
if(age < 18){
throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}
public static void main(String args[])
{
try
{

56
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");
System.out.println("Exception occured: " + ex);
}
System.out.println("rest of the code...");
}
}

OUTPUT:

RESULT:
Thus the program has been successfully executed.

57
EXERCISE NO : 8 IMPLEMENT THE FILE OPERATIONS
DATE:

8A. Write a Java program to read and display the content of a given file. The name of file must
be received by user at run-time of the program.

AIM:

To write a Java program to read and display the content of a given file. The name of file must be
received by user at run-time of the program.

ALGORITHM:

Step 1: Start the program.


Step 2: Import the required classes: java.util.Scanner and java.io.*.
Step 3: We use the BufferedReader class to read the contents of the file.
Step 4: If an error occurs during the process, an error message is displayed.
Step 5: The user is prompted to enter the file name, and the program attempts to open and read
the file.
Step 6: Display the Output.
Step 7: Stop the program.

PROGRAM:

import java.util.Scanner;
import java.io.*;
public class CodesCracker
{
public static void main(String[] args)
{
String fname;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the Name of File: ");
fname = scan.nextLine();
String line = null;

58
try
{
FileReader fileReader = new FileReader(fname);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
bufferedReader.close();
}
catch(IOException ex)
{
System.out.println("\nError occurred");
System.out.println("Exception Name: " +ex);
}
}

OUTPUT:

RESULT:
Thus the program has been successfully executed.

59
8B. Write a java program to Find Vowel Words in a File.

AIM:
To write a java program to find vowel words in a file.

ALGORITHM:

Step 1: Start the program.


Step 2: For each line, we split it into individual words using the split method, assuming that
words are separated by whitespace.
Step 3: We iterate over each word and check if it starts with a vowel using the 'isVowelWord'
method.
Step 4: The isVowelWord method checks the first character of the word after converting it to
lowercase. If it is 'a', 'e', 'i', 'o', or 'u', the method returns true, indicating that it is a vowel word.
Step 5: Inside the nested for loop, iterate over each character in the current word using
words[i].length().
Step 6: Stop the program.

PROGRAM:

package File;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileVowelsWord
{
public static void main(String[] args) throws IOException
{
File f1=new File("input.txt");
String[] words=null;
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
String s;
int flag=0;
while((s=br.readLine())!=null)
{
words=s.split(" ");
for(int i=0;i<words.length;i++)

60
{
for(int j=0;j<words[i].length();j++)
{
char ch=words[i].charAt(j);
if(ch == 'a' || ch == 'e' || ch == 'i' ||ch == 'o' || ch == 'u')
{
flag=1;
}
}
if(flag==1)
{
System.out.println(words[i]);
}
flag=0;
}
}
}
}

61
OUTPUT:

RESULT:
Thus the program has been successfully executed.

62
EXERCISE NO : 9 PROGRAM USING APPLETS
DATE:

9A. Write a java program Develop an applet that displays a simple message.

AIM:
To write a java program to develop an applet that displays a simple message.

ALGORITHM:

Step 1: Start the program.


Step 2: The ‘paint’ method is overridden, and within this method, we use the ‘Graphics’ object
to draw a string on the applet window.
Step 3: The ‘drawString’ method takes the message to display as the first argument.
Step 4: The coordinates (x, y) for the position of the message as the second and third arguments.
Step 5: The ‘<applet>’ tag is used to embed the applet.
Step 6: Stop the program.

PROGRAM:

import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}

63
OUTPUT:

RESULT:
Thus the program has been successfully executed.

64
9B. Write a Java program to draw smiley in an applet window using Java Applet class methods.

AIM:
To write a Java program to draw smiley in an applet window using Java Applet class methods.

ALGORITHM:

Step 1: Start the program.


Step 2: Import java package awt,applet
Step 3: We create a class SmileyApplet that extends the Applet class.
Step 4: The paint method is overridden, and within this method, we use the Graphics object to
draw a smiley face on the applet window.
Step 5: We first set the background color of the applet window to white using setBackground.
Step 6: Then, we set the color for the smiley face to yellow using setColor.
Step 7: The fillOval method is used to draw the face, eyes, and mouth by specifying the x and y
coordinates of the top-left corner of the oval, as well as its width and height.
Step 8: Display the output.
Step 9: Stop the program.

PROGRAM:

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class SmileyApplet extends Applet {
public void paint(Graphics g) {
setBackground(Color.WHITE);
g.setColor(Color.YELLOW);
g.fillOval(50, 50, 200, 200);
g.setColor(Color.BLACK);
g.fillOval(90, 110, 40, 40);
g.fillOval(180, 110, 40, 40);
g.fillArc(70, 150, 160, 80, 180, 180);
}
}

65
OUTPUT:

RESULT:
Thus the program has been successfully executed.

66
9C. Develop an applet that receives an integer in one text field and compute its factorial value in
another text field, when the button named ‘Compute” is clicked.

AIM:

To write a java program to Develop an applet that receives an integer in one text field and
compute its factorial value in another text field, when the button named ‘Compute” is
clicked.

ALGORITHM:
Step 1: Start the program.
Step 2: The updated applet code remains mostly the same as the previous version.
Step 3: However, there was a small error in the last response.
Step 4: To fix that, the ‘addActionListener’ method is now correctly assigned to the
‘computeButton’ object.
Step 5: Stop the program.

PROGRAM:

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code="FactorialApplet" width=500 height=250>
</applet>*/
public class FactorialApplet extends Applet implements ActionListener {
Label L1,L2;
TextField T1,T2;
Button B1;
public void init() {
L1=new Label("Enter any Number : ");
add(L1);
T1=new TextField(10);
add(T1);
L2=new Label("Factorial of Num : ");
add(L2);
T2=new TextField(10);
add(T2);
B1=new Button("Compute");
add(B1);
B1.addActionListener(this);

67
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==B1)
{
int value=Integer.parseInt(T1.getText());
int fact=factorial(value);
T2.setText(String.valueOf(fact));
}
}
int factorial(int n) {
if(n==0)
return 1;
else
return n*factorial(n-1);
}
}

OUTPUT:

RESULT:
Thus the program has been successfully executed.

68
EXERCISE NO : 10 PROGRAM TO HANDLE MOUSE EVENTS, KEYBOARD
DATE: EVENTS ANDWORK WITH GUI COMPONENTS

10A. Write a java program that handles all mouse events and shows the event name at the center
of the window when a mouse event is fired.

AIM:
To write a java program that handles all mouse events and shows the event name at the center of
the window when a mouse event is fired.

ALGORITHM:

Step 1: Start the program.


Step 2: In this program, we create a class ‘MouseEventDemo’ that extends ‘JFrame’ and
implements the ‘MouseListener’ and ‘MouseMotionListener’ interfaces.
Step 3: The ‘JFrame’ provides the window for our program, and the implemented listener
interfaces allow us to handle various mouse events.
Step 4: We create a ‘JLabel’ named ‘eventLabel’ to display the event name at the center of the
window.
Step 5: In the constructor, we set up the window by setting the title, size, and location, as well as
adding the ‘eventLabel’ to the frame.
Step 6: We register this as the listener for mouse events and mouse motion events using
‘addMouseListener’ and ‘addMouseMotionListener’ methods.
Step 7: Stop the program.

PROGRAM:

import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
class MouseEventPerformer extends Jframe implements MouseListener
{
Jlabel l1;
public MouseEventPerformer()

69
{
setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);
setSize(300,300);
setLayout(new FlowLayout(FlowLayout.CENTER));
l1 = new Jlabel();
Font f = new Font(“Verdana”, Font.BOLD, 20);
l1.setFont(f);
l1.setForeground(Color.BLUE);
add(l1);
addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent m)
{
l1.setText(“Mouse Exited”);
}
public void mouseEntered(MouseEvent m)
{
l1.setText(“Mouse Entered”);
}
public void mouseReleased(MouseEvent m)
{
l1.setText(“Mouse Released”);
}
public void mousePressed(MouseEvent m)
{
l1.setText(“Mouse Pressed”);
}
public void mouseClicked(MouseEvent m)
{
l1.setText(“Mouse Clicked”);
}
public static void main(String[] args) {
MouseEventPerformer mep = new MouseEventPerformer();
}
}

70
OUTPUT:

RESULT:
Thus the program has been successfully executed.

71
10B. Write a java program to Design Login Window Using Swing Controls (Button, Label,
Textfield).

AIM:
To write a Java Program to Design Login Window Using Swing Controls (Button, Label,
Textfield).

ALGORITHM:

Step 1: Start the program.


Step 2: We create a class ‘LoginWindow’ that extends ‘JFrame’ and implements the
‘ActionListener’ interface.
Step 3: The ‘JFrame’ provides the window for our login interface, and the implemented listener
interface allows us to handle button clicks.
Step 4: Inside the constructor, we set up the window by setting the title, size, and location.
Step 5: We create a ‘JPanel’ named panel and set its layout to ‘GridLayout’ to arrange the
components in a grid format.
Step 6: We create labels for the username and password fields, and ‘JTextField’ and
‘JPasswordField’ for user input. Additionally, we create a ‘JButton’ named ‘loginButton’ for
initiating the login process.
Step 7: Stop the program.

PROGRAM:

import java.awt.*;
import java.awt.event.*;
class MyLoginWindow extends Frame
{
TextField name,pass;
Button b1,b2;
MyLoginWindow()
{
setLayout(new FlowLayout());
this.setLayout(null);
Label n=new Label("Name:",Label.CENTER);
Label p=new Label("password:",Label.CENTER);
name=new TextField(20);
pass=new TextField(20);

72
pass.setEchoChar('#');
b1=new Button("submit");
b2=new Button("cancel");
this.add(n);
this.add(name);
this.add(p);
this.add(pass);
this.add(b1);
this.add(b2);
n.setBounds(70,90,90,60);
p.setBounds(70,130,90,60);
name.setBounds(200,100,90,20);
pass.setBounds(200,140,90,20);
b1.setBounds(100,260,70,40);
b2.setBounds(180,260,70,40);
}
public static void main(String args[])
{
MyLoginWindow ml=new MyLoginWindow();
ml.setVisible(true);
ml.setSize(400,400);
ml.setTitle("my login window");
}
}

73
OUTPUT:

RESULT:
Thus the program has been successfully executed.

74
10C. Write a Java program that works as a simple calculator. Use a grid Layout to arrange buttons
for the digits and for the +, -, *, / operations. Add a text field to display the results.

AIM:
To Write a Java program that works as a simple calculator. Use a grid Layout to arrange buttons
for the digits and for the +, -, *, / operations. Add a text field to display the results.

ALGORITHM:

Step1: Start the program.


Step2: Create a class with the name ‘MyCalculator’ that ‘extendsApplet’ implements
‘ActionListener’.
Step3: Declare the Button , ‘TextField’ variables.
Step4: Add listener to each layout and to the panel.
Step5: Add Text Field to display the result.
Step6: Handle any Exceptions like divide by zero.
Step7: Display the output.
Step8: Stop the program.

PROGRAM:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*
<applet code="MyCalculator" width=300 height=300>
</applet>
*/
public class MyCalculator extends Applet implements ActionListener {
int num1,num2,result;
TextField T1;
Button NumButtons[]=new Button[10];
Button Add,Sub,Mul,Div,clear,EQ;
char Operation;
Panel nPanel,CPanel,SPanel;
public oid init() {
nPanel=new Panel();
T1=new TextField(30);

75
nPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
nPanel.add(T1);
CPanel=new Panel();
CPanel.setBackground(Color.white);
CPanel.setLayout(new GridLayout(5,5,3,3));
for(int i=0;i<10;i++) {
NumButtons[i]=new Button(""+i);
}
Add=new Button("+");
Sub=new Button("-");
Mul=new Button("*");
Div=new Button("/");
clear=new Button("clear");
EQ=new Button("=");
T1.addActionListener(this);
for(int i=0;i<10;i++) {
CPanel.add(NumButtons[i]);
}
CPanel.add(Add);
CPanel.add(Sub);
CPanel.add(Mul);
CPanel.add(Div);
CPanel.add(EQ);
SPanel=new Panel();
SPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
SPanel.setBackground(Color.yellow);
SPanel.add(clear);
for(int i=0;i<10;i++) {
NumButtons[i].addActionListener(this);
}
Add.addActionListener(this);
Sub.addActionListener(this);
Mul.addActionListener(this);
Div.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
this.setLayout(new BorderLayout());
add(nPanel,BorderLayout.NORTH);
add(CPanel,BorderLayout.CENTER);
add(SPanel,BorderLayout.SOUTH);

76
}
public void actionPerformed(ActionEvent ae) {
String str=ae.getActionCommand ();
char ch=str.charAt(0);
if(Character.isDigit(ch))
T1.setText(T1.getText()+str);
else
if(str.equals("+")){
num1=Integer.parseInt (T1.getText());
Operation='+';
T1.setText ("");
}
if(str.equals("-")){
num1=Integer.parseInt(T1.getText());
Operation='-';
T1.setText("");
}
if(str.equals("*")){
num1=Integer.parseInt(T1.getText());
Operation='*';
T1.setText("");
}
if(str.equals("/")){
num1=Integer.parseInt(T1.getText());
Operation='/';
T1.setText("");
}
if(str.equals("%")){
num1=Integer.parseInt(T1.getText());
Operation='%';
T1.setText("");
}
if(str.equals("=")) {
num2=Integer.parseInt(T1.getText());
switch(Operation)
{
case '+':result=num1+num2;
break;
case '-':result=num1-num2;
break;

77
case '*':result=num1*num2;
break;
case '/':try {
result=num1/num2;
}
catch(ArithmeticException e) {
result=num2;
JOptionPane.showMessageDialog(this,"Divided by zero");
}
break;
}
T1.setText(""+result);
}
if(str.equals("clear")) {
T1.setText("");
}
}
}

78
OUTPUT:

RESULT:
Thus the program has been successfully executed.

79
EXERCISE NO : 11 PROGRAM USING JDBC
DATE:

Write a java Swing Login Form With Database Connection.

AIM:

To design aJava Swing Login Form With Database Connection.

ALGORITHM:

Step 1: Start the program.


Step 2: Create a package named com.javaguides.javaswing.login to encapsulate the code.
Step 3: Import the required classes and packages, including java.awt, java.awt.event, java.sql,
javax.swing, and javax.swing.border.
Step4: Define a public class named UserLogin that extends JFrame.
Step5: Inside the UserLogin class, declare the necessary instance variables: textField
(JTextField), passwordField (JPasswordField), btnNewButton (JButton), label (JLabel), and
contentPane (JPanel).
Step 6: Create a JPanel named contentPane and set its layout to null.
Step 7: Create a JLabel named lblNewLabel to display the "Login" heading.
Step 8: Create a JTextField named textField to input the username.
Step 9: Create a JPasswordField named passwordField to input the password.
Step 10: Create JLabel instances for the "Username" and "Password" labels.
Step 11: Create a JButton named btnNewButton for the login functionality.Inside the
actionPerformed method of the btnNewButton's ActionListener, retrieve the entered username
and password from the textField and passwordField.
Step 12: Establish a database connection using JDBC (DriverManager.getConnection) with
the appropriate credentials.
Step 13: Execute the query using executeQuery and retrieve the result set.
Step 14: Display the output.
Step 15: Stop the Program.

80
PROGRAM:

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class UserLogin extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField textField;
private JPasswordField passwordField;
private JButton btnNewButton;
private JLabel label;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UserLogin frame = new UserLogin();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}

81
});
}
/**
* Create the frame.
*/
public UserLogin() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(450, 190, 1014, 597);
setResizable(false);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Login");
lblNewLabel.setForeground(Color.BLACK);
lblNewLabel.setFont(new Font("Times New Roman", Font.PLAIN, 46));
lblNewLabel.setBounds(423, 13, 273, 93);
contentPane.add(lblNewLabel);
textField = new JTextField();
textField.setFont(new Font("Tahoma", Font.PLAIN, 32));
textField.setBounds(481, 170, 281, 68);
contentPane.add(textField);
textField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setFont(new Font("Tahoma", Font.PLAIN, 32));
passwordField.setBounds(481, 286, 281, 68);
contentPane.add(passwordField);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBackground(Color.BLACK);
lblUsername.setForeground(Color.BLACK);
lblUsername.setFont(new Font("Tahoma", Font.PLAIN, 31));
lblUsername.setBounds(250, 166, 193, 52);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setForeground(Color.BLACK);
lblPassword.setBackground(Color.CYAN);
lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 31));
lblPassword.setBounds(250, 286, 193, 52);
contentPane.add(lblPassword);
btnNewButton = new JButton("Login");

82
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 26));
btnNewButton.setBounds(545, 392, 162, 73);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String userName = textField.getText();
String password = passwordField.getText();
try {
Connection connection = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/swing_demo",
"root", "root");
PreparedStatement st = (PreparedStatement) connection
.prepareStatement("Select name, password from student where name=? and
password=?");
st.setString(1, userName);
st.setString(2, password);
ResultSet rs = st.executeQuery();
if (rs.next()) {
dispose();
UserHome ah = new UserHome(userName);
ah.setTitle("Welcome");
ah.setVisible(true);
JOptionPane.showMessageDialog(btnNewButton, "You have successfully logged in");
} else {
JOptionPane.showMessageDialog(btnNewButton, "Wrong Username & Password");
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
});
contentPane.add(btnNewButton);
label = new JLabel("");
label.setBounds(0, 0, 1008, 562);
contentPane.add(label);
}
}

83
OUTPUT:

RESULT:
Thus the program has been successfully executed.

84

You might also like