Werbtech Record Part 2
Werbtech Record Part 2
Date :20/09/2023
AIM
To implement interface, abstract, polymorphism in java programming
I. Write a Java program to implement the following specified in the picture using inheritance,
interface concepts and calculate the salary of an employee. Use super keyword , access modifiers
SOURCE CODE
import java.util.*; import java.io.*; interface payable{
double getPaymentAmount();
}
class employee implements payable{
String firstname;
String lastname;
String socialsecuritynumber;
66
public employee(String firstname, String lastname, String socialsecuritynumber ) {
this.firstname = firstname;
this.lastname = lastname;
this.socialsecuritynumber = socialsecuritynumber;
}
@Override
public double getPaymentAmount() {
throw new UnsupportedOperationException("Not supported yet."); // Generated from
nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
68
}
@Override
public double getPaymentAmount(){
return commissionRate*grossSales;
}
}
class Hourlyemployee extends employee {
private double wage;
private double hours;
public Hourlyemployee(String firstname, String lastname, String socialsecuritynumber,double
wage,double hours) {
super(firstname, lastname, socialsecuritynumber);
this.wage=wage;
this.hours=hours;
}
@Override
public double getPaymentAmount() {
if (hours <= 40) // no overtime
return wage * hours;
else
return 40 * wage + (hours - 40) * wage * 1.5;
}}
class SalariedEmployee extends employee {
private double weeklySalary;
70
1. OUTPUT
II. We have to calculate the percentage of marks obtained in three subjects (each out of 100) by
student A and in four subjects (each out of 100) by student B. Create an abstract class 'Marks' with an
abstract method 'getPercentage'. It is inherited by two other classes 'A' and 'B' each having a method
with the same name which returns the percentage of the students. The constructor of student A takes
the marks in three subjects as its parameters and the marks in four subjects as its parameters for
student B. Create an object for each of the two classes and print the percentage of marks for both the
students.
1. SOURCE CODE
abstract class Marks {
abstract double getPercentage();
}
class StudentA extends Marks {
private double subject1, subject2, subject3;
public StudentA(double subject1, double subject2, double subject3) {
this.subject1 = subject1;
this.subject2 = subject2;
this.subject3 = subject3;
}
@Override
double getPercentage() {
double totalMarks = subject1 + subject2 + subject3;
return (totalMarks / 300) * 100;
}
}
71
class StudentB extends Marks {
private double subject1, subject2, subject3, subject4;
public StudentB(double subject1, double subject2, double subject3, double subject4) {
this.subject1 = subject1;
this.subject2 = subject2;
this.subject3 = subject3;
this.subject4 = subject4;
}
@Override
double getPercentage() {
double totalMarks = subject1 + subject2 + subject3 + subject4;
return (totalMarks / 400) * 100;
}
}
public class two {
public static void main(String[] args) {
// Create objects for Student A and Student B
StudentA studentA = new StudentA(85, 90, 78);
StudentB studentB = new StudentB(92, 88, 75, 80);
// Calculate and print the percentage of marks for both students
System.out.println("Percentage of marks for Student A: " + studentA.getPercentage() + "%");
System.out.println("Percentage of marks for Student B: " + studentB.getPercentage() + "%");
}
}
2. OUTPUT
72
III. Write a program OnlinebookShop which sells and then add College Books and Story books as
subclasses of the Book class which holds the details about book name, publisher, Published year,
edition and price. Implement the polymorphic behavior through overriding methods. Explore the
usage of Upcasting and Downcasting also
1. SOURCE CODE
class Book {
private String name;
private String publisher;
private int publishedYear;
private int edition;
private double price;
public Book(String name, String publisher, int publishedYear, int edition, double price) {
this.name = name;
this.publisher = publisher;
this.publishedYear = publishedYear;
this.edition = edition;
this.price = price;
}
public void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Publisher: " + publisher);
System.out.println("Published Year: " + publishedYear);
System.out.println("Edition: " + edition);
System.out.println("Price: $" + price);
}
}
class CollegeBook extends Book {
String course;
public CollegeBook(String name, String publisher, int publishedYear, int edition, double price, String
course) {
super(name, publisher, publishedYear, edition, price);
this.course = course;
}
@Override
public void displayDetails() {
73
super.displayDetails();
System.out.println("Course: " + course);
}
}
class StoryBook extends Book {
String genre;
public StoryBook(String name, String publisher, int publishedYear, int edition, double price, String genre)
{
super(name, publisher, publishedYear, edition, price);
this.genre = genre;
}
@Override
public void displayDetails() {
super.displayDetails();
System.out.println("Genre: " + genre);
}
}
public class OnlineBookShop {
public static void main(String[] args) {
Book collegeBook = new CollegeBook("Advanced Mathematics", "XYZ Publications", 2023, 5, 50.0,
"Calculus");
Book storyBook = new StoryBook("Harry Potter and the Sorcerer's Stone", "Scholastic", 1997, 1, 20.0,
"Fantasy");
Book[] books = new Book[2];
books[0] = collegeBook;
books[1] = storyBook;
for (Book book : books) {
book.displayDetails();
System.out.println();
}
if (books[0] instanceof CollegeBook) {
CollegeBook downcastedCollegeBook = (CollegeBook) books[0];
System.out.println("Downcasted Course: " + downcastedCollegeBook.course);
}
if (books[1] instanceof StoryBook) {
74
StoryBook downcastedStoryBook = (StoryBook) books[1];
System.out.println("Downcasted Genre: " + downcastedStoryBook.genre);
}
}
}
2. OUTPUT
Result:
Thus interface, abstract, polymorphism were implemented in java programming.
75
8. EXCEPTION HANDLING
Expt. No.: 8
Date :27/09/2023
AIM:
To implement exception handling in java programming.
I. Develop a Java Console application to design a Vending Machine which follows following
requirements
1. Accepts coins of ₹1, ₹5, ₹10, ₹25, ₹50
2. Allows user to select products (Chocolate(10), Snack(25), Nuts(50), Juice(20))
3. Allow user to take refund by cancelling the request
4. Return selected product and remaining change, if any
5. Allow reset operation for vending machine supplier
Use Interface, Inheritance, Constructor, abstract class, polymorphism, exception (Unchecked
Exception, checked Exception, Custom Exception (NotPaidFullAmoutException,
NoSufficientChangeException, SoldOutException)) concepts and also use static, final and this keyword
wherever applicable to design a java application.
1. SOURCE CODE
import java.util.*;
class NotPaidFullAmountException extends Exception {
public NotPaidFullAmountException(String message) {
super(message);
}
}
class NoSufficientChangeException extends Exception {
public NoSufficientChangeException(String message) {
super(message);
}
}
class SoldOutException extends Exception {
public SoldOutException(String message) {
super(message);
}
76
}
abstract class Product {
protected String name;
protected int price;
public Product(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
public abstract String getDescription();
}
class Chocolate extends Product {
public Chocolate() {
super("Chocolate", 10);
}
public String getDescription() {
return "A delicious chocolate bar";
}
}
class Snack extends Product {
public Snack() {
super("Snack", 25);
}
public String getDescription() {
return "A tasty snack";
}
}
class Nuts extends Product {
public Nuts() {
super("Nuts", 50);
77
}
public String getDescription() {
return "Healthy nuts";
}
}
class Juice extends Product {
public Juice() {
super("Juice", 20);
}
public String getDescription() {
return "Refreshing juice";
}
}
enum Coin {
ONE(1), FIVE(5), TEN(10), TWENTY_FIVE(25), FIFTY(50);
private int value;
Coin(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
class VendingMachine {
private Map<Product, Integer> products;
private Map<Coin, Integer> coins;
public VendingMachine() {
products = new HashMap<>();
coins = new HashMap<>();
initializeProducts();
initializeCoins();
}
private void initializeProducts() {
products.put(new Chocolate(), 5);
products.put(new Snack(), 5);
78
products.put(new Nuts(), 5);
products.put(new Juice(), 5);
}
private void initializeCoins() {
coins.put(Coin.ONE, 10);
coins.put(Coin.FIVE, 10);
coins.put(Coin.TEN, 10);
coins.put(Coin.TWENTY_FIVE, 10);
coins.put(Coin.FIFTY, 10);
}
public void insertCoin(Coin coin) {
if (coins.containsKey(coin)) {
coins.put(coin, coins.get(coin) + 1);
}
}
public void displayProducts() {
System.out.println("Available Products:");
for (Product product : products.keySet()) {
System.out.println(product.getName() + " - ₹" + product.getPrice());
}
}
public void selectProduct(Product product) throws SoldOutException, NotPaidFullAmountException,
NoSufficientChangeException {
if (!products.containsKey(product) || products.get(product) <= 0) {
throw new SoldOutException("Sorry, " + product.getName() + " is sold out.");
}
if (getTotalInsertedAmount() < product.getPrice()) {
throw new NotPaidFullAmountException("Please insert more coins to purchase " +
product.getName());
}
int change = getTotalInsertedAmount() - product.getPrice();
if (!hasSufficientChange(change)) {
throw new NoSufficientChangeException("No sufficient change available to purchase " +
product.getName());
}
79
System.out.println("Dispensing " + product.getName() + ". Enjoy your " + product.getDescription() +
".");
products.put(product, products.get(product) - 1);
giveChange(change);
clearCoins();
}
public int getTotalInsertedAmount() {
int totalAmount = 0;
for (Coin coin : coins.keySet()) {
totalAmount += coins.get(coin) * coin.getValue();
}
return totalAmount;
}
private boolean hasSufficientChange(int change) {
for (Coin coin : Coin.values()) {
if (coins.get(coin) * coin.getValue() >= change) {
return true;
}
}
return false;
}
private void giveChange(int change) {
for (Coin coin : Coin.values()) {
int coinCount = Math.min(change / coin.getValue(), coins.get(coin));
change -= coinCount * coin.getValue();
coins.put(coin, coins.get(coin) - coinCount);
if (change == 0) {
break;
}
}
}
void clearCoins() {
for (Coin coin : Coin.values()) {
coins.put(coin, 0);
}
80
}
public void supplierReset() {
initializeProducts();
initializeCoins();
}
}
public class VendingMachineApp {
public static void main(String[] args) {
VendingMachine vendingMachine = new VendingMachine();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\n===== Vending Machine Menu =====");
System.out.println("1. Insert Coin");
System.out.println("2. Select Product");
System.out.println("3. Display Products");
System.out.println("4. Take Refund");
System.out.println("5. Supplier Reset");
System.out.println("6. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Available Coins: ₹1, ₹5, ₹10, ₹25, ₹50");
System.out.print("Enter coin value: ");
int coinValue = scanner.nextInt();
if (coinValue == 1 || coinValue == 5 || coinValue == 10 || coinValue == 25 || coinValue == 50) {
vendingMachine.insertCoin(Coin.valueOf("FIFTY"));
} else {
System.out.println("Invalid coin value.");
}
break;
case 2:
vendingMachine.displayProducts();
System.out.print("Enter the product name: ");
String productName = scanner.next();
81
try {
switch (productName.toLowerCase()) {
case "chocolate":
vendingMachine.selectProduct(new Chocolate());
break;
case "snack":
vendingMachine.selectProduct(new Snack());
break;
case "nuts":
vendingMachine.selectProduct(new Nuts());
break;
case "juice":
vendingMachine.selectProduct(new Juice());
break;
default:
System.out.println("Invalid product selection.");
}
} catch (SoldOutException | NotPaidFullAmountException | NoSufficientChangeException e) {
System.out.println("Error: " + e.getMessage());
}
break;
case 3:
vendingMachine.displayProducts();
break;
case 4:
int refundAmount = vendingMachine.getTotalInsertedAmount();
if (refundAmount > 0) {
System.out.println("Refunding ₹" + refundAmount);
vendingMachine.clearCoins();
} else {
System.out.println("No coins inserted to refund.");
}
break;
case 5:
vendingMachine.supplierReset();
82
System.out.println("Supplier reset operation completed.");
break;
case 6:
System.out.println("Exiting the vending machine. Have a nice day!");
System.exit(0);
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}
2. OUTPUT
83
84
II. Calculate EMI for the product which customer purchased for Rs. 100000/- with the rate of
interest:18% for a total of 3 years, if there is no balance in the account to pay an EMI raise a custom
exception also use try catch finally mechanism.
1. SOURCE CODE
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
public class EMI_Calculator {
public static void main(String[] args) {
double principal = 100000;
double annualInterestRate = 18;
int numberOfYears = 3;
int numberOfMonths = numberOfYears * 12;
try {
double monthlyInterestRate = annualInterestRate / (12 * 100);
double emi = calculateEMI(principal, monthlyInterestRate, numberOfMonths);
System.out.println("EMI: Rs. " + emi);
if (emi > 0) {
throw new InsufficientBalanceException("Insufficient balance to pay the EMI");
}
} catch (InsufficientBalanceException e) {
System.err.println("Error: " + e.getMessage());
} finally {
System.out.println("Transaction completed.");
}
}
public static double calculateEMI(double principal, double monthlyInterestRate, int numberOfMonths) {
return (principal * monthlyInterestRate * Math.pow(1 + monthlyInterestRate, numberOfMonths))/
(Math.pow(1 + monthlyInterestRate, numberOfMonths) - 1);
}
}
85
2. OUTPUT
Result:
Thus exception handling implemented in java programming.
86
9. REGULAR EXPRESSION
Expt. No.: 9
Date :04/10/2023
Aim:
To implement regular expressions in java programming.
I. Write a java program for registering the details of student in university. The requirements are
mentioned below. i) username should always end with _deptname and there should be atleast
minimum of characters to the left of _deptname. ii) Validate the emaild provided by the user.
iii) Password should accept only characters and numbers.
1. SOURCE CODE
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
87
String password = scanner.nextLine();
if (!isValidPassword(password)) {
System.out.println("Invalid password format. Password should only contain letters and numbers.");
return;
}
System.out.println("Registration successful!");
System.out.println("Username: " + username);
System.out.println("Email: " + email);
}
private static boolean isValidUsername(String username) {
return username.matches("^.+(_[a-zA-Z]+)$");
}
private static boolean isValidEmail(String email) {
String regex = "^[A-Za-z0-9+_.-]+@(.+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
private static boolean isValidPassword(String password) {
return password.matches("^[a-zA-Z0-9]+$");
}
}
2. OUTPUT
II. An company requires each employee to maintain a secret code. The secret code needs to pass
certain validation for getting accepted. The validation rules are given as follows:
i. The secret code should be eight characters long
88
ii. The first three characters should be Abbreviated company name
iii. There should be at least one digit in code (use isDigit)
iv. The first character should always be an upper case letter (Use isUpperCase)
v. The code should contain only alphabets and digits
Return true if the above validation is passed.
1. SOURCE CODE
import java.util.*;
Result:
Thus regular expressions were implemented in java programming.
90
10. INPUT AND OUTPUT MANIPULATION ON FILES, SERIALIZATION
Expt. No.: 10
Date :14/10/2023
Aim:
To implement input and output manipulation on files, serialization in java programming.
I. 1. Write a java program using byte streams to read a text file and makes an alphabetical list of all
the words in that file. Those list of words is written to another file. Improve the program so that it also
keeps track of the number of times that each word occurs in the file. Two lists should be displayed in
the output file. The first list contains the words in alphabetical order. The number of times that the
word occurred in the file should be listed along with the word. Then write a second list to the output
file in which the words are sorted according to the number of times that they occurred in the files. The
word that occurred most often should be listed first
1. SOURCE CODE
import java.io.*;
import java.util.*;
public class WordCount {
public static void main(String[] args) {
String inputFile = "input.txt";
String outputFile = "output.txt";
try (BufferedReader br = new BufferedReader(new FileReader(inputFile);
BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile))) {
String line;
Map<String, Integer> wordCountMap = new HashMap<>();
while ((line = br.readLine()) != null) {
String[] words = line.split("\\s+");
for (String word : words) {
// Remove punctuation and convert to lowercase
word = word.replaceAll("[^a-zA-Z]", "").toLowerCase();
if (!word.isEmpty()) {
91
wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
}
}
}
List<Map.Entry<String, Integer>> sortedWordCountList = new
ArrayList<>(wordCountMap.entrySet());
sortedWordCountList.sort(Comparator.comparing(Map.Entry::getKey));
for (Map.Entry<String, Integer> entry : sortedWordCountList) {
bw.write(entry.getKey() + " - " + entry.getValue() + "\n");
}
bw.newLine();
sortedWordCountList.sort((e1, e2) -> e2.getValue().compareTo(e1.getValue()));
for (Map.Entry<String, Integer> entry : sortedWordCountList) {
bw.write(entry.getKey() + " - " + entry.getValue() + "\n");
}
System.out.println("Word count lists have been written to " + outputFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. OUTPUT
II. 2. Write a java program to have country class and serialize country name and continent name to
which the country belongs to. You don’t want to serialize population attribute as it will change with
time, so declare population as transient. Perform deserialization, Print country name, continent name
and population of the country
92
1. SOURCE CODE
import java.io.*;
class Country implements Serializable {
private String name;
private String continent;
private transient int population;
public Country(String name, String continent, int population) {
this.name = name;
this.continent = continent;
this.population = population;
}
public String getName() {
return name;
}
public String getContinent() {
return continent;
}
public int getPopulation() {
return population;
}
}
public class CountrySerializationExample {
public static void main(String[] args) {
Country countryToSerialize = new Country("United States", "North America", 331002651);
try (FileOutputStream fileOut = new FileOutputStream("country.ser");
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut)) {
objectOut.writeObject(countryToSerialize);
System.out.println("Country object serialized to country.ser");
} catch (IOException e) {
e.printStackTrace();
}
Country deserializedCountry = null;
try (FileInputStream fileIn = new FileInputStream("country.ser");
ObjectInputStream objectIn = new ObjectInputStream(fileIn)) {
93
deserializedCountry = (Country) objectIn.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
if (deserializedCountry != null) {
System.out.println("Country Name: " + deserializedCountry.getName());
System.out.println("Continent: " + deserializedCountry.getContinent());
System.out.println("Population: " + deserializedCountry.getPopulation());
}
}
}
2. OUTPUT
III. 3. Write a Java program using character stream classes that copies one file content to another,
replacing all lower characters by their upper case equivalents
1. SOURCE CODE
import java.io.*;
public class CopyFileWithUppercaseConversion {
public static void main(String[] args) {
String inputFile = "input.txt";
String outputFile = "output.txt";
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
int charCode;
while ((charCode = reader.read()) != -1) {
char character = (char) charCode;
char upperCaseCharacter = Character.toUpperCase(character);
94
writer.write(upperCaseCharacter);
}
System.out.println("File content copied with uppercase conversion to " + outputFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. OUTPUT
Result:
Thus input and output manipulation on files, serialization in java programming were implemented.
95
11. CLIENT-SERVER NETWORK APPLICATION USING JAVA SOCKETS
Expt. No.: 11
Date :14/10/2023
Aim:
To implement client-server network application using java sockets in java programming.
I. Write a java program to simulate chatbot for online shopping application which does two way
communication between customer and retailer using connection oriented protocol
1. SOURCE CODE
Server:
import java.io.*;
import java.net.*;
public class OnlineShoppingServer {
public static void main(String[] args) {
final int PORT = 12345;
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Server is running and waiting for connections...");
while (true) {
try (Socket clientSocket = serverSocket.accept()) {
System.out.println("Client connected from " + clientSocket.getInetAddress());
BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println("Welcome to the Online Shopping Chatbot!");
out.println("How can I assist you today?");
String clientMessage;
while ((clientMessage = in.readLine()) != null) {
System.out.println("Client: " + clientMessage);
String response = getChatbotResponse(clientMessage);
out.println("Chatbot: " + response);
}
96
} catch (IOException e) {
System.err.println("Error handling client: " + e.getMessage());
}
}
} catch (IOException e) {
System.err.println("Server error: " + e.getMessage());
}
}
private static String getChatbotResponse(String userMessage) {
return "I'm just a basic chatbot. Please provide more details for assistance.";
}
}
Client:
import java.io.*;
import java.net.*;
public class OnlineShoppingClient {
public static void main(String[] args) {
final String SERVER_ADDRESS = "localhost";
final int SERVER_PORT = 12345;
try (Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT)) {
BufferedReader serverIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter clientOut = new PrintWriter(socket.getOutputStream(), true);
String serverMessage;
while ((serverMessage = serverIn.readLine()) != null) {
System.out.println("Server: " + serverMessage);
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
System.out.print("You: ");
String userMessage = userInput.readLine();
clientOut.println(userMessage);
}
} catch (IOException e) {
System.err.println("Client error: " + e.getMessage());
}
}
}
97
2. OUTPUT
II. Write a java program to perform two way communication between client and server where
message sent by client are converted to upper case and displayed in server side, message sent by server
should be converted to lower case and displayed in client side. Implement the scenario using
connectionless protocol.
1. SOURCE CODE
Server:
import java.net.*;
import java.io.*;
public class UDPServer {
public static void main(String[] args) {
final int PORT = 9876;
try (DatagramSocket serverSocket = new DatagramSocket(PORT)) {
System.out.println("UDP Server is running and waiting for messages...");
while (true) {
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
98
serverSocket.receive(receivePacket);
String clientMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received from client: " + clientMessage);
String response = clientMessage.toUpperCase();
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
byte[] sendData = response.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress,
clientPort);
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.err.println("Server error: " + e.getMessage());
}
}
}
Client:
import java.net.*;
import java.io.*;
public class UDPClient {
public static void main(String[] args) {
final String SERVER_ADDRESS = "localhost";
final int SERVER_PORT = 9876;
try (DatagramSocket clientSocket = new DatagramSocket()) {
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in);
while (true) {
System.out.print("You: ");
String userMessage = userInput.readLine();
byte[] sendData = userMessage.getBytes();
InetAddress serverAddress = InetAddress.getByName(SERVER_ADDRESS);
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress,
SERVER_PORT);
clientSocket.send(sendPacket);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
99
clientSocket.receive(receivePacket);
String serverResponse = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Server: " + serverResponse);
}
} catch (IOException e) {
System.err.println("Client error: " + e.getMessage());
}
}
}
2. OUTPUT
Result:
Thus client-server network application using java sockets in java programming were executed.
100
12. MULTITHREADING
Expt. No.: 12
Date :18/10/2023
Aim:
To implement multithreading in java programming.
I. Write a Java program that creates three threads. First thread displays “Hello!” every one second,
the second thread displays “Happy Holidays !” every two seconds and “Enjoy!” every 5 seconds.
1. SOURCE CODE
public class ThreadDemo {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
while (true) {
System.out.println("Hello!");
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(() -> {
while (true) {
System.out.println("Happy Holidays !");
try {
Thread.sleep(2000); // Sleep for 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
101
Thread thread3 = new Thread(() -> {
while (true) {
System.out.println("Enjoy!");
try {
Thread.sleep(5000); // Sleep for 5 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
hread3.start();
}
}
2. OUTPUT
102
II. Write a Java program to create five threads with different priorities. Send two threads of the
highest priority to sleep state. Check the aliveness of the threads and mark which thread is long
lasting.
1. SOURCE CODE
class MyThread extends Thread {
private long startTime;
public MyThread(String name, int priority) {
super(name);
setPriority(priority);
}
@Override
public void run() {
startTime = System.currentTimeMillis();
for (int i = 0; i < 5; i++) {
System.out.println(getName() + " is running");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println(getName() + " was interrupted");
return;
}
}
}
public long getThreadDuration() {
return System.currentTimeMillis() - startTime;
}
}
public class ThreadPriority {
public static void main(String[] args) {
MyThread thread1 = new MyThread("Thread 1 (Lowest Priority)", Thread.MIN_PRIORITY);
MyThread thread2 = new MyThread("Thread 2", Thread.NORM_PRIORITY);
MyThread thread3 = new MyThread("Thread 3", Thread.NORM_PRIORITY);
MyThread thread4 = new MyThread("Thread 4 (Highest Priority)", Thread.MAX_PRIORITY);
MyThread thread5 = new MyThread("Thread 5 (Highest Priority)", Thread.MAX_PRIORITY);
thread1.start();
103
thread2.start();
thread3.start();
thread4.start();
thread5.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Main thread was interrupted");
}
// Send two highest-priority threads to sleep
thread4.sleep(1000);
thread5.sleep(1000);
if (longestLastingThread != null) {
System.out.println(longestLastingThread.getName() + " is the longest-lasting thread.");
}else{
System.out.println("No long lasting threads");
104
}
}
}
2. OUTPUT
III. Write a java program that implements a multi-thread applications that has three threads. First
thread generates random integer every 1 second and if the value is even, second thread computes the
105
square of the number and prints. If the value is odd, the thread will compute and print the cube of the
number
1. SOURCE CODE
import java.util.Random;
@Override
public void run() {
while (true) {
int randomNumber = random.nextInt(100); // Generate a random integer between 0 and 99
System.out.println("Generated number: " + randomNumber);
if (randomNumber % 2 == 0) {
SquareThread squareThread = new SquareThread(randomNumber);
squareThread.start();
} else {
CubeThread cubeThread = new CubeThread(randomNumber);
cubeThread.start();
}
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void run() {
int square = number * number;
System.out.println("Square of " + number + " is: " + square);
}
}
@Override
public void run() {
106
int cube = number * number * number;
System.out.println("Cube of " + number + " is: " + cube);
}
}
107
IV. Create an application that executes two threads. First thread displays the alphabets A to Z at
every one second. The second thread will display the alphabets Z to A at every two seconds. Both the
threads need to synchronize with each other for printing alphabets. The second thread has to wait
until the first thread finishes its execution. The application waits for all thread to finish the execution.
1. SOURCE CODE
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
Result:
Thus multithreading in java programming was implemented.
109
13. INTER THREAD COMMUNICATION
Expt. No.: 13
Date :25/10/2023
Aim:
To implement inter thread communication in java programming
I. Implement the following scenario (Single producer/ Multiple Consumers) for inter thread
communication using Java.
1. SOURCE CODE
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
class Producer implements Runnable {
private BlockingQueue<Integer> queue;
public Producer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
System.out.println("Producing: " + i);
queue.put(i);
Thread.sleep(100); // Simulate some work
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
110
private BlockingQueue<Integer> queue;
private int id;
public Consumer(BlockingQueue<Integer> queue, int id) {
this.queue = queue;
this.id = id;
}
@Override
public void run() {
try {
while (true) {
int value = queue.take();
System.out.println("Consumer " + id + " consumed: " + value);
Thread.sleep(200); // Simulate some work
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
try {
producerThread.join();
for (Thread consumerThread : consumerThreads) {
consumerThread.join();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
111
2. OUTPUT
Result:
Thus inter thread communication in java programming was implemented.
112
14. SIMPLE GUI APPLICATION DEVELOPMENT USING SWING
Expt. No.: 14
Date :1/11/2023
Aim:
To implement simple gui application development using swing.
I.Implement the following form using Java Swing and display the contents in another form.
1. SOURCE CODE
package webtech.asses;
import javax.swing.ButtonGroup;
public class swing extends javax.swing.JFrame {
swing() {
initComponents();
113
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jRadioButtonMenuItem1 = new javax.swing.JRadioButtonMenuItem();
jPanel1 = new javax.swing.JPanel();
jTextPane1 = new javax.swing.JTextPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
name = new javax.swing.JTextField();
mail = new javax.swing.JTextField();
gen = new javax.swing.JRadioButton();
gen2 = new javax.swing.JRadioButton();
jPasswordField1 = new javax.swing.JPasswordField();
jPasswordField2 = new javax.swing.JPasswordField();
mob = new javax.swing.JTextField();
course = new javax.swing.JComboBox<>();
branch = new javax.swing.JComboBox<>();
sem = new javax.swing.JTextField();
jRadioButtonMenuItem1.setSelected(true);
jRadioButtonMenuItem1.setText("jRadioButtonMenuItem1");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
panel1.setLayout(panel1Layout);
panel1Layout.setHorizontalGroup(
114
panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
panel1Layout.setVerticalGroup(
panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jScrollPane1.setViewportView(jTextPane1);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane2.setViewportView(jTextArea1);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Name:");
name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nameActionPerformed(evt);
}
});
jLabel2.setText("Gender");
jLabel3.setText("mail id");
buttonGroup1.add(gen);
gen.setText("male")
buttonGroup1.add(gen2);
gen2.setText("female");
jButton1.setText("submit");
115
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel4.setText("password ")
jPasswordField1.setText("jPasswordField1");
jLabel5.setText("Register A New Student");
jLabel6.setText("confirm password");
jPasswordField2.setText("jPasswordField2");
jLabel7.setText("mobile number");
mob.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mobActionPerformed(evt);
}
})
jLabel8.setText("courses ");
course.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "b.tech", "b.e", "m.tech",
"m.e" }));
course.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
courseActionPerformed(evt);
}
})
jLabel9.setText("branch");
branch.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "IT", "ECE", "E&I",
"MECH", "PT", "AUTO", "RPT" }));
jLabel10.setText("semester");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(15, 15, 15)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
116
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 58,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 37,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 77,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 58,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 120,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(gen, javax.swing.GroupLayout.PREFERRED_SIZE, 98,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(gen2, javax.swing.GroupLayout.PREFERRED_SIZE, 98,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 148,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(mail, javax.swing.GroupLayout.PREFERRED_SIZE, 141,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE,
119, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPasswordField2, javax.swing.GroupLayout.PREFERRED_SIZE, 123,
javax.swing.GroupLayout.PREFERRED_SIZE)
117
.addGap(89, 89, 89))))
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 314,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 147,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING,
false)
.addComponent(jLabel8, javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addComponent(jLabel7, javax.swing.GroupLayout.Alignment.LEADING,
javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mob, javax.swing.GroupLayout.PREFERRED_SIZE, 110,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(course, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 80,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(sem, javax.swing.GroupLayout.PREFERRED_SIZE, 71,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 94,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(branch, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(213, Short.MAX_VALUE))
);
118
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 40,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(gen)
.addComponent(gen2))
.addGap(24, 24, 24))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addGap(18, 18, 18)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(mail, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
119
.addComponent(jPasswordField2, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 28,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(mob, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 25,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(course, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(23, 23, 23)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(branch, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9))
.addGap(22, 22, 22)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10)
.addComponent(sem, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40,
Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 54,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15))
);
pack();
}// </editor-fold>
@Override
public String toString() {
120
return "swing{" + "jLabel1=" + jLabel1 + ", jLabel2=" + jLabel2 + ", jRadioButton1=" + jRadioButton1
+ ", jRadioButton2=" + jRadioButton2 + ", jTextField1=" + name + '}';
}
private void nameActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
SecondForm sc=new SecondForm();
sc.u1.setText(name.getText());
sc.u2.setText(mail.getText());
if (gen.isSelected()){sc.u3.setText(gen.getText());}
else{sc.u3.setText(gen2.getText());}
sc.u4.setText(mob.getText());
sc.u5.setText((String) course.getSelectedItem());
sc.u6.setText((String) branch.getSelectedItem());
sc.u7.setText(sem.getText());
sc.setVisible(true);
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(swing.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(swing.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
} catch (IllegalAccessException ex) {
121
java.util.logging.Logger.getLogger(swing.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(swing.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new swing().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JComboBox<String> branch;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.ButtonGroup buttonGroup3;
private javax.swing.ButtonGroup buttonGroup4;
private javax.swing.ButtonGroup buttonGroup5;
private javax.swing.ButtonGroup buttonGroup6;
private javax.swing.ButtonGroup buttonGroup7;
private javax.swing.ButtonGroup buttonGroup8;
private javax.swing.JComboBox<String> course;
private javax.swing.JRadioButton gen;
private javax.swing.JRadioButton gen2;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
122
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPasswordField jPasswordField1;
private javax.swing.JPasswordField jPasswordField2;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextPane jTextPane1;
private javax.swing.JTextField mail;
private javax.swing.JTextField mob;
public javax.swing.JTextField name;
private java.awt.Panel panel1;
private javax.swing.JTextField sem;
// End of variables declaration
}
2. OUTPUT
II,Write a program to simulate Deepavali celebrations by animating crackers and displaying greeting
message using Java Swing.
123
1. SOURCE CODE
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
125
2. OUTPUT
126
Result:
Thus simple gui application development using swing was implemented in java programming.
127