Java Lab
Java Lab
1 Sum of digits
2 Swapping Numbers
3 Armstrong Number
4 Fibonacci Series
5 Even or Odd
7 Average of 5 Numbers
8 Diamond Pattern
10 Matrix Multiplication
11 Method Overloading
17 Multithreading Strings
18 Synchronized Methods
Multiple Inheritance
19
(Interface)
20 User Defined Packages
27 Applet Message
28 Applet Smiley
29 Applet Factorial
30 Mouse Events
32 Calculator (Swing)
•
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:
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:
ALGORITHM:
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:
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:
ALGORITHM:
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:
ALGORITHM:
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:
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:
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:
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:
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:
PROGRAM:
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:
PROGRAM:
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:
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:
PROGRAM:
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:
ALGORITHM:
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:
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:
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:
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:
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
}
}
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:
PROGRAM:
interface Walkable {
void walk();
interface Swimmable {
void swim();
42
}
System.out.println("Duck is walking.");
System.out.println("Duck is swimming.");
class Main {
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:
PROGRAM:
a) USING PACKAGENAME.
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
package mypack;
import pack.*;
class B{
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{
obj.msg();
OUTPUT:
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
46
package mypack;
class B{
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:
PROGRAM:
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:
PROGRAM:
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:
ALGORITHM:
PROGRAM:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*:
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”);
}
53
}
}
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:
PROGRAM:
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:
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:
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:
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:
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:
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:
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:
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:
AIM:
ALGORITHM:
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