1. Python Codes & Practicals (Cheat.py)
Operating Systems & Data Structures (Sem III)
OS Practical 1
Python / OS
Process Communication using Shared Memory
AIM: Understand shared memory concepts in Inter-Process Communication. Implement producer-consumer synchronization using shared memory and semaphores. Explore issues of race conditions and how to avoid them.
from threading import Thread, Semaphore
import random, time
full = Semaphore(0)
empty = Semaphore(10)
mutex = Semaphore(1)
buffer = []
class producerThread(Thread):
def __init__(this, buffer):
Thread.__init__(this)
this.buffer = buffer
def run(this):
for i in range(5):
empty.acquire()
mutex.acquire()
num = random.randint(0, 5)
this.buffer.append(num)
print("Produced", num)
mutex.release()
full.release()
time.sleep(1)
class consumerThread(Thread):
def __init__(this, buffer):
Thread.__init__(this)
this.buffer = buffer
def run(this):
for i in range(5):
full.acquire()
mutex.acquire()
print("Consumed", this.buffer.pop())
mutex.release()
empty.release()
time.sleep(1)
producerThread(buffer).start()
consumerThread(buffer).start()
💻 Output / Result
Produced 3
Consumed 3
Produced 1
Consumed 1
Produced 3
Consumed 3
Produced 0
Consumed 0
Produced 3
Consumed 3
OS Practical 2
Python / OS
Process Communication using Message Passing
AIM: Use message queues/pipes to solve the producer-consumer problem. Compare and contrast shared memory vs message-passing approaches. Analyze blocking vs non-blocking communication.
import threading
import queue
import time
def producer(q):
for i in range(5):
msg = f"Data {i}"
q.put(msg)
print("Producer sent:", msg)
time.sleep(1)
q.put("Done")
def consumer(q):
while True:
msg = q.get()
if msg == "DONE":
break
print("Consumer received:", msg)
if __name__ == "__main__":
q = queue.Queue()
t1 = threading.Thread(target = producer, args = (q,))
t2 = threading.Thread(target = consumer, args = (q,))
t1.start()
t2.start()
t1.join()
t2.join()
💻 Output / Result
Producer sent: Data 0
Consumer received: Data 0
Producer sent: Data 1
Consumer received: Data 1
Producer sent: Data 2
Consumer received: Data 2
Producer sent: Data 3
Consumer received: Data 3
Producer sent: Data 4
Consumer received: Data 4
Consumer received: Done
OS Practical 3
Python / OS
Threading a Single Thread Control Flow vs Sequential Execution
AIM: Practice thread creation and basic thread lifecycle using standard libraries. Observe execution order, thread joining, and delays.
import threading, time
def task():
print("Start")
time.sleep(2)
print("End")
start = time.time()
t1 = threading.Thread(target = task)
t2 = threading.Thread(target = task)
t1.start()
t2.start()
t1.join()
t2.join()
print("Threading Time:", round(time.time() - start, 2))
start = time.time()
task()
task()
print("Sequential Time:", round(time.time() - start, 2))
💻 Output / Result
Start
Start
End
End
Threading Time: 2.0
Start
End
Start
End
Sequential Time: 4.01
OS Practical 4
Python / OS
Multi-threading and Fibonacci Generation
AIM: Implement multi-threading to generate and print Fibonacci sequences. Explore thread safety and synchronization when accessing shared variables. Introduce concepts of thread pooling and task delegation.
import threading, time
fib = []
lock = threading.Lock()
def generate(n):
a, b = 0, 1
for _ in range(n):
with lock:
fib.append(a)
a, b = b, a + b
time.sleep(0.1)
def display(n):
while True:
with lock:
print(fib)
if len(fib) >=n:
break
time.sleep(0.2)
if __name__ == "__main__":
n = 10
t1 = threading.Thread(target = generate, args = (n, ))
t2 = threading.Thread(target = display, args = (n, ))
t1.start()
t2.start()
t1.join()
t2.join()
print("Final: ", fib)
💻 Output / Result
[0]
[0, 1]
[0, 1, 1, 2]
[0, 1, 1, 2, 3, 5]
[0, 1, 1, 2, 3, 5, 8, 13]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Final: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
OS Practical 5
Python / OS
Process Synchronization and Bounded Buffer Problem
AIM: Simulate the producer-consumer bounded buffer scenario using mutex and semaphores. Implement buffer control with synchronized access. Introduce circular queue techniques for managing shared buffers.
import threading, time, random
BUFFER_SIZE, NUM_ITEMS = 5, 5
buffer = []
empty = threading.Semaphore(BUFFER_SIZE)
full = threading.Semaphore(0)
mutex = threading.Lock()
def producer():
for _ in range(NUM_ITEMS):
item = random.randint(1, 100)
empty.acquire()
mutex.acquire()
buffer.append(item)
print("Producer:", item, "| Buffer:", buffer)
mutex.release()
full.release()
time.sleep(random.uniform(0.5, 1.5))
def consumer():
for _ in range(NUM_ITEMS):
full.acquire()
mutex.acquire()
item = buffer.pop(0)
print("Consumer: ", item, "| Buffer: ", buffer)
mutex.release()
empty.release()
time.sleep(random.uniform(0.5, 1.5))
t1 = threading.Thread(target = producer)
t2 = threading.Thread(target = consumer)
t1.start()
t2.start()
t1.join()
t2.join()
💻 Output / Result
Producer: 15 | Buffer: [15]
Consumer: 15 | Buffer: []
Producer: 34 | Buffer: [34]
Consumer: 34 | Buffer: []
Producer: 11 | Buffer: [11]
Consumer: 11 | Buffer: []
Producer: 72 | Buffer: [72]
Consumer: 72 | Buffer: []
Producer: 12 | Buffer: [12]
Consumer: 12 | Buffer: []
DS Practical 1A
Python / DS
Create and Manipulate Structure (Student ADT)
AIM: Define an Abstract Data Type (Student class) with properties name, roll_no, marks, and a display method.
class Student:
def __init__(self, name, roll_no, marks):
self.name = name
self.roll_no = roll_no
self.marks = marks
def display(self):
print("Roll No:", self.roll_no)
print("Name:", self.name)
print("Marks:", self.marks)
s1 = Student("Sanjayoo", 101, 85)
print("Student Details:")
s1.display()
💻 Output / Result
Student Details:
Roll No: 101
Name: Sanjayoo
Marks: 85
DS Practical 1B
Python / DS
Basic Dictionary Operations (Create, Update, Delete)
AIM: Perform dictionary operations in Python to store student records, insert new record, update marks, and delete record.
students = {
101: {"name": "Sanjay", "marks": 85},
102: {"name": "Rohit", "marks": 90},
}
students[103] = {"name": "Sakshi", "marks": 90}
students[101]["marks"] = 95
del students[102]
print("Student Records:")
for roll, details in students.items():
print(roll, ":", details)
💻 Output / Result
Student Records:
101 : {'name': 'Sanjay', 'marks': 95}
103 : {'name': 'Sakshi', 'marks': 90}
DS Practical 2
Python / DS
Singly Linked List Implementation
AIM: Implement Singly Linked List with Node structure, insertion at end, and traversal display in Python.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(self, data):
new = Node(data)
if self.head is None:
self.head = new
else:
temp = self.head
while temp.next:
temp = temp.next
temp.next = new
def display(self):
temp = self.head
while temp:
print(temp.data, end = "->")
temp = temp.next
print("None")
l1 = LinkedList()
l1.insert(10)
l1.insert(20)
l1.insert(30)
l1.display()
💻 Output / Result
10->20->30->None
DS Practical 3
Python / DS
Polynomial Addition using Dictionary Representation
AIM: Represent polynomials as power:coefficient dictionaries and compute their polynomial addition.
poly1 = {2: 3, 1: 2, 0: 5}
poly2 = {2: 4, 1: 1, 0: 6}
result = {}
for power in set(poly1) | set(poly2):
result[power] = poly1.get(power, 0) + poly2.get(power, 0)
print("Result: ")
for p in sorted(result, reverse = True):
print(result[p], "x^", p, end = " ")
💻 Output / Result
Result:
7 x^ 2 3 x^ 1 11 x^ 0
DS Practical 4
Python / DS
Doubly Linked List Implementation
AIM: Implement a Doubly Linked List with prev and next pointers and traverse forward.
class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
head = Node(10)
second = Node(20)
third = Node(30)
head.next = second
second.prev = head
second.next = third
third.prev = second
temp = head
while temp:
print(temp.data, end = " ")
temp = temp.next
💻 Output / Result
10 20 30
DS Practical 5
Python / DS
Stack Implementation (Push, Pop, Peek)
AIM: Implement Stack LIFO operations in Python using a list.
stack = []
stack.append(10)
stack.append(20)
stack.append(30)
print("Stack:", stack)
print("Pop:", stack.pop())
print("Peek:", stack[-1])
💻 Output / Result
Stack: [10, 20, 30]
Pop: 30
Peek: 20
Cheat.py
Python Source
Complete Cheat.py Source Code (OS & DS Practicals)
AIM: Full contents of Cheat.py containing Operating Systems Sem III and Data Structures Sem III practical programs.
#-------OPERATING SYSTEMS PRACTICALS SYCS SEM III-------
#Practical 1 -- Process Communication shared using Memory
#Aim:- Understand shared memory concepts in Inter-Process Communication.
#Implement producer-consumer synchronization using shared memory and semaphores.
#Explore issues of race conditions and how to avoid them.
from threading import Thread, Semaphore
import random, time
full = Semaphore(0)
empty = Semaphore(10)
mutex = Semaphore(1)
buffer = []
class producerThread(Thread):
def __init__(this, buffer):
Thread.__init__(this)
this.buffer = buffer
def run(this):
for i in range(5):
empty.acquire()
mutex.acquire()
num = random.randint(0, 5)
this.buffer.append(num)
print("Produced", num)
mutex.release()
full.release()
time.sleep(1)
class consumerThread(Thread):
def __init__(this, buffer):
Thread.__init__(this)
this.buffer = buffer
def run(this):
for i in range(5):
full.acquire()
mutex.acquire()
print("Consumed", this.buffer.pop())
mutex.release()
empty.release()
time.sleep(1)
producerThread(buffer).start()
consumerThread(buffer).start()
#Output:
#Produced 3
#Consumed 3
#Produced 1
#Consumed 1
#Produced 3
#Consumed 3
#Produced 0
#Consumed 0
#Produced 3
#Consumed 3
##Practical 2 -- Process Communication using message passing
#Aim :- Use message queues/pipes to solve the producer-consumer problem.
#Compare and contrast shared memory vs message-passing approaches.
#Analyze blocking vs non-blocking communication.
import threading
import queue
import time
def producer(q):
for i in range(5):
msg = f"Data {i}"
q.put(msg)
print("Producer sent:", msg)
time.sleep(1)
q.put("Done")
def consumer(q):
while True:
msg = q.get()
if msg == "DONE":
break
print("Consumer received:", msg)
if __name__ == "__main__":
q = queue.Queue()
t1 = threading.Thread(target = producer, args = (q,))
t2 = threading.Thread(target = consumer, args = (q,))
t1.start()
t2.start()
t1.join()
t2.join()
#Output:
#Producer sent: Data 0
#Consumer received: Data 0
#Producer sent: Data 1
#Consumer received: Data 1
#Producer sent: Data 2
#Consumer received: Data 2
#Producer sent: Data 3
#Consumer received: Data 3
#Producer sent: Data 4
#Consumer received: Data 4
#Consumer received: Done
#Practical 3 -- Threading a single thread control flow
#Aim :- Practice thread creation and basic thread lifecycle using standard libraries.
#Observe execution order, thread joining, and delays.
import threading, time
def task():
print("Start")
time.sleep(2)
print("End")
start = time.time()
t1 = threading.Thread(target = task)
t2 = threading.Thread(target = task)
t1.start()
t2.start()
t1.join()
t2.join()
print("Threading Time:", round(time.time() - start, 2))
start = time.time()
task()
task()
print("Sequential Time:", round(time.time() - start, 2))
#Ouptput:
#Start
#Start
#End
#End
#Threading Time: 2.0
#Start
#End
#Start
#End
#Sequential Time: 4.01
#Practical 4 -- Multi-threading and Fibonacci Generation
#Aim :- Implement multi-threading to generate and print Fibonacci sequences.
#Explore thread safety and synchronization when accessing shared variables.
#Introduce concepts of thread pooling and task delegation.
import threading, time
fib = []
lock = threading.Lock()
def generate(n):
a, b = 0, 1
for _ in range(n):
with lock:
fib.append(a)
a, b = b, a + b
time.sleep(0.1)
def display(n):
while True:
with lock:
print(fib)
if len(fib) >=n:
break
time.sleep(0.2)
if __name__ == "__main__":
n = 10
t1 = threading.Thread(target = generate, args = (n, ))
t2 = threading.Thread(target = display, args = (n, ))
t1.start()
t2.start()
t1.join()
t2.join()
print("Final: ", fib)
#Output:
#[0]
#[0, 1]
#[0, 1, 1, 2]
#[0, 1, 1, 2, 3, 5]
#[0, 1, 1, 2, 3, 5, 8, 13]
#[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
#Final: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
#Practical 5 -- Process Synchronization and bounded buffer problem
#Aim:- Simulate the producer-consumer bounded buffer scenario using mutex and semaphores.
#Implement buffer control with synchronized access.
#Introduce circular queue techniques for managing shared buffers.
import threading, time, random
BUFFER_SIZE, NUM_ITEMS = 5, 5
buffer = []
empty = threading.Semaphore(BUFFER_SIZE)
full = threading.Semaphore(0)
mutex = threading.Lock()
def producer():
for _ in range(NUM_ITEMS):
item = random.randint(1, 100)
empty.acquire()
mutex.acquire()
buffer.append(item)
print("Producer:", item, "| Buffer:", buffer)
mutex.release()
full.release()
time.sleep(random.uniform(0.5, 1.5))
def consumer():
for _ in range(NUM_ITEMS):
full.acquire()
mutex.acquire()
item = buffer.pop(0)
print("Consumer: ", item, "| Buffer: ", buffer)
mutex.release()
empty.release()
time.sleep(random.uniform(0.5, 1.5))
t1 = threading.Thread(target = producer)
t2 = threading.Thread(target = consumer)
t1.start()
t2.start()
t1.join()
t2.join()
#Output:
#Producer: 15 | Buffer: [15]
#Consumer: 15 | Buffer: []
#Producer: 34 | Buffer: [34]
#Consumer: 34 | Buffer: []
#Producer: 11 | Buffer: [11]
#Consumer: 11 | Buffer: []
#Producer: 72 | Buffer: [72]
#Consumer: 72 | Buffer: []
#Producer: 12 | Buffer: [12]
#Consumer: 12 | Buffer: []
#-----DATA STRUCTURES PRACTICALS SYCS SEM III-----
#(A) Create and Manipulate Structure (Student ADT)
class Student:
def __init__(self, name, roll_no, marks):
self.name = name
self.roll_no = roll_no
self.marks = marks
def display(self):
print("Roll No:", self.roll_no)
print("Name:", self.name)
print("Marks:", self.marks)
s1=Student("Sanjayoo", 101, 85)
print("Student Details:")
s1.display()
#Output:
#Student Details:
#Roll No: 101
#Name: Sanjayoo
#Marks: 85
#(B) Implement Basic Operations (Create, Update, Delete)
students = {
101: {"name": "Sanjay", "marks": 85},
102: {"name": "Rohit", "marks": 90},
}
students[103] = {"name": "Sakshi", "marks": 90}
students[101]["marks"] = 95
del students[102]
print("Student Records:")
for roll, details in students.items():
print(roll, ":",details)
#Output:
#Student Records:
#101 : {'name': 'Sanjay', 'marks': 95}
#103 : {'name': 'Sakshi', 'marks': 90}
#Practical 2 Singly Linked List
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(self,data):
new = Node(data)
if self.head is None:
self.head = new
else:
temp =self.head
while temp.next:
temp = temp.next
temp.next = new
def display(self):
temp = self.head
while temp:
print(temp.data, end = "->")
temp = temp.next
print("None")
l1 =LinkedList()
l1.insert(10)
l1.insert(20)
l1.insert(30)
l1.display()
#Output:
#10->20->30->None
#PRACTICAL 3 Polynomial Addition
poly1 = {2:3,1:2,0:5}
poly2 = {2:4,1:1,0:6}
result = {}
for power in set(poly1)|set(poly2):
result[power]=poly1.get(power,0)+poly2.get(power,0)
print("Result: ")
for p in sorted(result,reverse = True):
print(result[p],"x^",p,end= " ")
#Output:
#Result:
#7 x^ 2 3 x^ 1 11 x^ 0 %
#PRACTICAL 4 Doubly Linked List
class Node:
def __init__(self,data):
self.data = data
self.prev = None
self.next = None
head = Node(10)
second = Node(20)
third = Node(30)
head.next = second
second.prev = head
second.next = third
third.prev = second
temp = head
while temp:
print(temp.data,end = " ")
temp = temp.next
#Output:
#10 20 30 %
#PRACTICAL 5 Stack
stack = []
stack.append(10)
stack.append(20)
stack.append(30)
print("Stack:",stack)
print("Pop:",stack.pop())
print("Peek:",stack[-1])
#Output:
#Stack: [10, 20, 30]
#Pop: 30
#Peek: 20
Java Practical 1
Java
Constructor Overloading, Method Overloading & Overriding (super)
AIM: Demonstrate constructor overloading, method overloading to calculate area, and method overriding with the super keyword.
class test{
double ar;
static int a;
String name, city;
test(){
System.out.println("Example of Constructor overloading");
System.out.println("This is a default Constructor Executing First");
}
test(String n, String c){
name = n;
city = c;
}
void Calarea(double radius){
ar = 3.14*radius*radius;
System.out.println("Area of Circle:"+ar);
}
void Calarea(double base, double hight){
ar = 0.5*base*hight;
System.out.println("Area of tringle:"+ar);
}
static void disp(){
a = 10;
System.out.println("a:"+a);
}
}
class practical1A{
public static void main(String args[]){
test obj = new test();
test obj1 = new test("SANJAY","VASAI");
System.out.println("Student Name:"+obj1.name+"\nStudent city:"+obj1.city);
System.out.println("Example of Method overloading");
obj.Calarea(5);
obj.Calarea(8,5);
System.out.println("Example of static Method");
test.disp();
}
}
class Base{
void display(){
System.out.println("Base class Method");
}
}
class Derived extends Base{
void display(){
super.display();
System.out.println("Derived class Method");
}
}
class Practical1B{
public static void main(String args[]){
Derived obj = new Derived();
obj.display();
}
}
💻 Output / Explanation
Example of Constructor overloading
This is a default Constructor Executing First
Area of Circle:78.5
Area of tringle:25.0
a:10
Base class Method
Derived class Method
Java Practical 2
Java
Abstract Classes vs Interfaces in Java
AIM: Implement abstract classes with abstract methods findarea() and findvolume(), and demonstrate the equivalent implementation using an Interface.
import java.util.*;
abstract class Roundshape {
double radius;
final double pi = 3.14;
abstract void findarea();
abstract void findvolume();
void disp() {
System.out.println("This is an example of abstract class");
}
}
class sphere extends Roundshape {
double area;
double volume;
Scanner sc = new Scanner(System.in);
void findarea() {
System.out.println("Enter radius of sphere:");
radius = sc.nextDouble();
area = 4 * pi * radius * radius;
System.out.println("Area of Sphere is: " + area);
}
void findvolume() {
System.out.println("Enter radius of sphere:");
radius = sc.nextDouble();
volume = (4.0 / 3.0) * pi * radius * radius * radius;
System.out.println("Volume of Sphere is: " + volume);
}
}
class practical2A {
public static void main(String args[]) {
sphere s = new sphere();
s.disp();
s.findarea();
s.findvolume();
}
}
import java.util.*;
interface Roundshape {
double pi = 3.14;
void findarea();
void findvolume();
}
class Sphere implements Roundshape {
double area, volume, radius;
Scanner sc = new Scanner(System.in);
Sphere() {
System.out.print("Enter radius of sphere: ");
radius = sc.nextDouble();
}
public void findarea() {
area = 4 * pi * radius * radius;
System.out.println("Area of Sphere is: " + area);
}
public void findvolume() {
volume = (4.0 / 3.0) * pi * radius * radius * radius;
System.out.println("Volume of Sphere is: " + volume);
}
}
public class Practical2B {
public static void main(String args[]) {
Sphere s = new Sphere();
s.findarea();
s.findvolume();
}
}
💻 Output / Explanation
Enter radius of sphere: 5
Area of Sphere is: 314.0
Volume of Sphere is: 523.3333333333334
Java Practical 3
Java
Custom Exception Handling & Multithreading
AIM: 1. Implement custom user-defined exception AuthenticationFailure. 2. Implement multithreading by implementing the Runnable interface.
import java.io.*;
class AuthenticationFailure extends Exception {
public AuthenticationFailure()
{
System.out.println("Invalid Password");
}
}
class Practical3A
{
public static void main(String args[]) throws IOException
{
try
{
String pass;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Password:");
pass = br.readLine();
if (pass.equals("rose"))
System.out.println("Login Successful");
else
throw new AuthenticationFailure();
}
catch (AuthenticationFailure e)
{
System.out.println(e);
}
}
}
class DemoThread implements Runnable {
Thread tobj;
DemoThread() {
tobj = new Thread(this, "Demo Thread");
tobj.start(); // Start the child thread
}
public void run() {
try {
for (int n = 5; n > 0; n--) {
System.out.println("Child Thread: " + n);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child Thread Interrupted");
}
System.out.println("Child Thread Execution Completed");
}
}
public class Practical3B {
public static void main(String args[]) {
new DemoThread();
try {
for (int n = 15; n > 10; n--) {
System.out.println("Main Thread: " + n);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Error....Interrupted");
}
System.out.println("Main Thread Execution Completed");
}
}
💻 Output / Explanation
Enter Password:rose
Login Successful
Child Thread: 5
Child Thread: 4
Child Thread: 3
Child Thread: 2
Child Thread: 1
Child Thread Execution Completed
Java Practical 4
Java
Java Collections Framework (ArrayList, HashSet, HashMap)
AIM: Implement collection data structures: dynamic resizable ArrayList, unique element HashSet, and key-value mapping HashMap.
import java.util.*;
public class Practical4A{
public static void main(String args[]){
ArrayList <String> obj = new ArrayList<String>();
obj.add("Ajeet");
obj.add("Harry");
obj.add("Chaitanya");
obj.add("Steve");
obj.add("Anuj");
System.out.println("Original ArrayList");
for(String str:obj)
System.out.println(str);
obj.add(0,"Rahul");
obj.add(1,"Justin");
System.out.println("ArrayList after Add Operation");
for(String str:obj)
System.out.println(str);
obj.remove("Chaitanya");
obj.remove("Harry");
System.out.println("ArrayList after remove Operation");
for(String str:obj)
System.out.println(str);
obj.remove(1);
System.out.println("Final ArrayList");
for(String str:obj)
System.out.println(str);
}
}
import java.util.*;
class Practical4B {
public static void main(String args[]) {
HashSet<String> h = new HashSet<String>();
h.add("India");
h.add("Australia");
h.add("South Africa");
h.add("India");
System.out.println(h);
System.out.println("List Contains India or not: " + h.contains("India"));
h.remove("Australia");
System.out.println("List after removing Australia: " + h);
}
}
import java.util.*;
public class Practical4C {
public static void main(String args[]) {
Map map = new HashMap();
map.put(1, "Amit");
map.put(5, "Rahul");
map.put(2, "Jai");
map.put(6, "Amit");
Set set = map.entrySet();
Iterator itr = set.iterator();
while (itr.hasNext()) {
Map.Entry entry = (Map.Entry) itr.next();
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
💻 Output / Explanation
Original ArrayList: [Ajeet, Harry, Chaitanya, Steve, Anuj]
ArrayList after Add Operation: [Rahul, Justin, Ajeet, Harry, Chaitanya, Steve, Anuj]
ArrayList after remove Operation: [Rahul, Justin, Ajeet, Steve, Anuj]
HashSet elements: [Australia, South Africa, India]
List Contains India or not: true
List after removing Australia: [South Africa, India]
HashMap entries:
1 Amit
2 Jai
5 Rahul
6 Amit
Java Practical 5
Java / Swing
Java Swing GUI Calculator Application
AIM: Design and build an interactive graphical Calculator application using Java Swing components (JFrame, JButton, JTextField, GridLayout, BorderLayout) and ActionListener.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame
implements ActionListener {
JButton b10, b11, b12, b13, b14, b15;
JButton b[] = new JButton[10];
int i, r, n1, n2;
JTextField res;
char op;
public Calculator() {
super("Calculator");
setLayout(new BorderLayout());
JPanel p = new JPanel();
p.setLayout(new GridLayout(4, 4));
for (i = 0; i <= 9; i++) {
b[i] = new JButton("" + i);
p.add(b[i]);
b[i].addActionListener(this);
}
b10 = new JButton("+");
p.add(b10);
b10.addActionListener(this);
b11 = new JButton("-");
p.add(b11);
b11.addActionListener(this);
b12 = new JButton("*");
p.add(b12);
b12.addActionListener(this);
b13 = new JButton("/");
p.add(b13);
b13.addActionListener(this);
b14 = new JButton("=");
p.add(b14);
b14.addActionListener(this);
b15 = new JButton("C");
p.add(b15);
b15.addActionListener(this);
res = new JTextField(10);
add(res, BorderLayout.NORTH);
add(p, BorderLayout.CENTER);
setSize(250, 250);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae) {
JButton pb = (JButton) ae.getSource();
if (pb == b15) {
r = n1 = n2 = 0;
res.setText("");
} else if (pb == b14) {
n2 = Integer.parseInt(res.getText());
eval();
res.setText("" + r);
} else {
boolean opf = false;
if (pb == b10) {
op = '+';
opf = true;
}
if (pb == b11) {
op = '-';
opf = true;
}
if (pb == b12) {
op = '*';
opf = true;
}
if (pb == b13) {
op = '/';
opf = true;
}
if (!opf) {
for (i = 0; i < 10; i++) {
if (pb == b[i]) {
String t = res.getText();
t += i;
res.setText(t);
}
}
} else {
n1 = Integer.parseInt(res.getText());
res.setText("");
}
}
}
void eval() {
switch (op) {
case '+':
r = n1 + n2;
break;
case '-':
r = n1 - n2;
break;
case '*':
r = n1 * n2;
break;
case '/':
if (n2 != 0) {
r = n1 / n2;
} else {
res.setText("Cannot Divide by zero");
return;
}
break;
}
}
public static void main(String args[]) {
new Calculator();
}
}
💻 Output / Explanation
GUI window launched with numeric keypad 0-9 and operators (+, -, *, /).
Calculations evaluated on '=' click and cleared on 'C'.
Java Practical 6
Java / Swing
Java Swing GUI Forms (Login & User Registration)
AIM: 1. Build an interactive Login dialog with username, password, login/clear/exit buttons. 2. Build a Registration Form with RadioButtons for Gender and CheckBoxes for Hobbies.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Practical6A extends JFrame implements ActionListener {
JButton b1, b2, b3;
JTextField t1;
JLabel l1, l2;
JPasswordField t2;
public Practical6A() {
super("Login Page");
b1 = new JButton("Login");
b2 = new JButton("Clear");
b3 = new JButton("Exit");
l1 = new JLabel("Enter your Username");
l2 = new JLabel("Enter your Password");
t1 = new JTextField(10);
t2 = new JPasswordField(6);
setLayout(new GridLayout(4, 2));
add(l1);
add(l2);
add(t1);
add(t2);
add(b1);
add(b2);
add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae) {
String s1 = t1.getText();
String s2 = new String(t2.getPassword());
if (ae.getSource() == b1) {
if (s1.equals("admin") && s2.equals("1234"))
JOptionPane.showMessageDialog(this, "Login Successful");
else
JOptionPane.showMessageDialog(this, "Login Faild");
}
if (ae.getSource() == b2) {
t1.setText("");
t2.setText("");
}
if (ae.getSource() == b3) {
System.exit(0);
}
}
public static void main(String args[]) {
Practical6A lo = new Practical6A();
lo.setSize(300, 200);
lo.setVisible(true);
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Practical6B extends JFrame implements ActionListener {
JButton b1;
JLabel lbldisp;
JTextField jtf;
JPasswordField jpf;
JRadioButton m, f;
JCheckBox cb1, cb2, cb3;
ButtonGroup bg;
String str = "Gender: ";
String h = "Hobbies: ";
public Practical6B() {
JLabel lb1 = new JLabel("User Name: ");
jtf = new JTextField(10);
JLabel lb2 = new JLabel("Password: ");
jpf = new JPasswordField(10);
JLabel lb3 = new JLabel("Gender: ");
m = new JRadioButton("Male");
f = new JRadioButton("Female");
bg = new ButtonGroup();
bg.add(m);
bg.add(f);
m.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED)
str = "Gender: " + m.getText();
}
});
f.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED)
str = "Gender: " + f.getText();
}
});
JLabel lb4 = new JLabel("Hobbies: ");
cb1 = new JCheckBox("Listening Music");
cb2 = new JCheckBox("Reading Books");
cb3 = new JCheckBox("Playing Games");
ItemListener hobbyListener = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
h = "Hobbies: ";
if (cb1.isSelected())
h += cb1.getText() + " ";
if (cb2.isSelected())
h += cb2.getText() + " ";
if (cb3.isSelected())
h += cb3.getText() + " ";
}
};
cb1.addItemListener(hobbyListener);
cb2.addItemListener(hobbyListener);
cb3.addItemListener(hobbyListener);
b1 = new JButton("Display");
b1.addActionListener(this);
lbldisp = new JLabel(" ");
setLayout(new GridLayout(4, 1));
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
p1.add(lb1);
p1.add(jtf);
p1.add(lb2);
p1.add(jpf);
p2.add(lb3);
p2.add(m);
p2.add(f);
p3.add(lb4);
p3.add(cb1);
p3.add(cb2);
p3.add(cb3);
p4.setLayout(new GridLayout(2, 1));
p4.add(b1);
p4.add(lbldisp);
add(p1);
add(p2);
add(p3);
add(p4);
setTitle("Practical 6B");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
String password = new String(jpf.getPassword());
lbldisp.setText("<html>"
+ "Name: " + jtf.getText()
+ "<br>" + str
+ "<br>" + h
+ "<br>Password: " + password
+ "</html>");
}
}
public static void main(String args[]) {
new Practical6B();
}
}
💻 Output / Explanation
Practical6A: Graphical Login form with input validation.
Practical6B: Registration form capturing username, password, selected radio gender, and checked hobbies.
Java Practical 7A
Java / Servlets
Java Servlets - HTTP Cookie Creation & Display
AIM: Create cookies in CookieServlet from HTML form inputs and retrieve them using DisplayCookie servlet.
package mypack;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/CookieServlet")
public class CookieServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String cname = request.getParameter("cname");
String cvalue = request.getParameter("cvalue");
Cookie ck = new Cookie(cname, cvalue);
ck.setMaxAge(60 * 60 * 24); // 1 day
response.addCookie(ck);
out.println("<h2>Cookie Stored Successfully!</h2>");
out.println("<h3>Cookie Name: " + cname + "</h3>");
out.println("<h3>Cookie Value: " + cvalue + "</h3>");
out.println("<br><a href='index.html'>Add More Cookie</a>");
out.println("<br><br><a href='DisplayCookie'>View All Cookies</a>");
}
}
package mypack;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/DisplayCookie")
public class DisplayCookie extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie[] cookies = request.getCookies();
out.println("<h2>All Stored Cookies:</h2>");
if (cookies != null && cookies.length > 0) {
for (Cookie c : cookies) {
out.println(c.getName() + " = " + c.getValue() + "<br>");
}
} else {
out.println("No Cookies Found");
}
out.println("<br><a href='index.html'>Add More Cookie</a>");
}
}
<!DOCTYPE html>
<html>
<head><title>Cookie Demo</title></head>
<body>
<h2>Enter Data to Store in Cookie</h2>
<form action="CookieServlet" method="post">
Cookie Name: <input type="text" name="cname" required><br><br>
Cookie Value: <input type="text" name="cvalue" required><br><br>
<input type="submit" value="Store in Cookie">
</form>
</body>
</html>>
💻 Output / Explanation
Form submits username and age -> Cookie created and response added -> DisplayCookie reads request.getCookies() and prints values.
Java Practical 7B
Java / Servlets
Java Servlets - Chained Servlets & Request Forwarding with Cookies
AIM: Demonstrate servlet chaining and cookie propagation between FirstServlet and SecondServlet.
package com.example;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("un");
// Create cookie
Cookie ck = new Cookie("un", name);
// Add cookie to browser
response.addCookie(ck);
out.println("<html>");
out.println("<body>");
out.println("<h2>Welcome " + name + "</h2>");
out.println("<p>Cookie has been created.</p>");
out.println("<form action='SecondServlet' method='post'>");
out.println("<input type='submit' value='Display Cookie'>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
}
package com.example;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/SecondServlet")
public class SecondServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h2>Cookie Data</h2>");
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie ck : cookies) {
if (ck.getName().equals("un")) {
out.println("<h3>Hello " + ck.getValue() + "</h3>");
}
}
} else {
out.println("<p>No cookies found.</p>");
}
out.println("</body>");
out.println("</html>");
}
}
<!DOCTYPE html>
<!--
Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Html.html to edit this template
-->
<html>
<head>
<title>Cookie Example</title>
</head>
<body>
<h2>Cookie Example</h2>
<form action="FirstServlet" method="post">
Name:
<input type="text" name="un">
<br><br>
<input type="submit" value="GO">
</form>
</body>
</html>
💻 Output / Explanation
FirstServlet processes credentials, creates cookie, and delegates/links to SecondServlet to render personalized welcome view.
Java Practical 7C
Java / Servlets
Java Servlets - Server-side HTTP Session Management (HttpSession)
AIM: Store and manage user profile attributes across page requests using HttpSession in Java Servlets.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/SessionServlet")
public class SessionServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Get data from HTML form
String name = request.getParameter("name");
String email = request.getParameter("email");
String course = request.getParameter("course");
// Create/Get session
HttpSession session = request.getSession();
// Store data as session variables
session.setAttribute("name", name);
session.setAttribute("email", email);
session.setAttribute("course", course);
// Display stored session variables
out.println("<html><body>");
out.println("<h2>Student Details Stored in Session</h2>");
out.println("Name: " + session.getAttribute("name") + "<br>");
out.println("Email: " + session.getAttribute("email") + "<br>");
out.println("Course: " + session.getAttribute("course") + "<br>");
out.println("</body></html>");
}
}
<!DOCTYPE html>
<html>
<head>
<title>Session Example</title>
</head>
<body>
<h2>Enter Student Details</h2>
<form action="SessionServlet" method="post">
Name:
<input type="text" name="name"><br><br>
Email:
<input type="text" name="email"><br><br>
Course:
<input type="text" name="course"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
💻 Output / Explanation
User profile captured in form -> request.getSession() stores attributes -> Servlet renders active session ID and stored attributes.
Java Practical 8A
JSP / Web
JSP - Cookie Handling & Lifecycle Management
AIM: Create, configure expiration (24 hours), and store client cookies directly inside Java Server Pages (JSP).
<%@ page import="javax.servlet.http.Cookie" %>
<html>
<head>
<title>Cookie Example</title>
</head>
<body>
<h2>Store Data in Cookie</h2>
<form method="post">
Enter your name:
<input type="text" name="username">
<input type="submit" value="Save Cookie">
</form>
<%
String name = request.getParameter("username");
if (name != null && !name.isEmpty()) {
Cookie c = new Cookie("username", name);
c.setMaxAge(24 * 60 * 60);
response.addCookie(c);
out.println("<h3>Cookie stored successfully!</h3>");
out.println("Stored Name: " + name);
}
%>
</body>
</html>
<%@ page import="javax.servlet.http.Cookie" %>
<html>
<head>
<title>Cookie and Session Example</title>
</head>
<body>
<h2>JSP Cookie and Session Example</h2>
<!-- Store Data as Cookie -->
<h3>1. Store Data as Cookie</h3>
<form method="post">
Enter Name:
<input type="text" name="username">
<input type="submit" name="action" value="Store Cookie">
</form>
<!-- Store Data as Session -->
<h3>2. Store Data as Session Variable</h3>
<form method="post">
Enter Name:
<input type="text" name="sessionname">
<input type="submit" name="action" value="Store Session">
</form>
<%
String action = request.getParameter("action");
// Store data as Cookie
if ("Store Cookie".equals(action)) {
String name = request.getParameter("username");
if (name != null && !name.isEmpty()) {
Cookie c = new Cookie("username", name);
// Cookie remains for 1 day
c.setMaxAge(24 * 60 * 60);
response.addCookie(c);
out.println("<h3>Cookie Stored Successfully!</h3>");
}
}
// Store data as Session
if ("Store Session".equals(action)) {
String sessionName = request.getParameter("sessionname");
if (sessionName != null && !sessionName.isEmpty()) {
session.setAttribute("sessionname", sessionName);
out.println("<h3>Session Variable Stored Successfully!</h3>");
}
}
%>
<hr>
<h2>Stored Data</h2>
<%
// Display Cookie
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("username".equals(cookie.getName())) {
out.println("<p><b>Cookie Value:</b> "
+ cookie.getValue() + "</p>");
}
}
}
// Display Session
Object sessionValue = session.getAttribute("sessionname");
if (sessionValue != null) {
out.println("<p><b>Session Value:</b> "
+ sessionValue + "</p>");
}
%>
</body>
</html>
💻 Output / Explanation
JSP response shows: Cookie stored successfully! Stored Name: [username] with 86400 seconds max age.
Java Practical 8B
JSP / Web
JSP - Storing and Displaying Cookies Across Separate Pages
AIM: Separate cookie storage in store.jsp from retrieval in display.jsp.
<%@ page import="javax.servlet.http.Cookie" %>
<%
String username = request.getParameter("username");
Cookie cookie = new Cookie("username", username);
cookie.setMaxAge(60 * 60 * 24); // 1 day
response.addCookie(cookie);
%>
<!DOCTYPE html>
<html>
<head>
<title>Cookie Stored</title>
</head>
<body>
<h2>Cookie Stored Successfully!</h2>
<p>Hello, <%= username %></p>
<p>Your name has been stored in a cookie.</p>
<a href="display.jsp">View Cookie</a>
</body>
</html>
<%@ page import="javax.servlet.http.Cookie" %>
<!DOCTYPE html>
<html>
<head>
<title>Display Cookie</title>
</head>
<body>
<h2>Cookie Data</h2>
<%
Cookie[] cookies = request.getCookies();
String username = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("username".equals(cookie.getName())) {
username = cookie.getValue();
break;
}
}
}
if (username != null) {
%>
<p>Stored Name: <b><%= username %></b></p>
<%
} else {
%>
<p>No cookie found.</p>
<%
}
%>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Cookie Example</title>
</head>
<body>
<h2>Enter Your Name</h2>
<form action="store.jsp" method="post">
Name:
<input type="text" name="username" required>
<input type="submit" value="Store Cookie">
</form>
</body>
</html>
💻 Output / Explanation
store.jsp writes cookie to browser -> link to display.jsp loops through request.getCookies() and displays names and values.
Java Practical 8C
JSP / Web
JSP - Session Variable Storage & Tracking
AIM: Store and retrieve session variables using implicit session object (session.setAttribute & getAttribute) in JSP.
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP Session Example</title>
</head>
<body>
<%
String name = request.getParameter("username");
session.setAttribute("username", name);
String storedName = (String) session.getAttribute("username");
%>
<h2>JSP Session Variable</h2>
<p>Name entered: <%= name %></p>
<p>Name stored in session: <%= storedName %></p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>JSP Session Example</title>
</head>
<body>
<form action="store.jsp" method="post">
Enter Your Name:
<input type="text" name="username">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
💻 Output / Explanation
JSP Session Variable: Name entered: [username] stored and rendered on server.
Java Practical 9A
Java / Servlets
Java Servlets - Web-based Calculator Application
AIM: Build a dynamic web calculator servlet processing arithmetic operations (+, -, *, /) from HTML forms.
package com.mycompany.calculatorservlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/CalculatorServlet")
public class Calculatorservlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
double num1 = Double.parseDouble(request.getParameter("num1"));
double num2 = Double.parseDouble(request.getParameter("num2"));
String operation = request.getParameter("operation");
double result = 0;
if (operation.equals("add")) {
result = num1 + num2;
}
else if (operation.equals("sub")) {
result = num1 - num2;
}
else if (operation.equals("mul")) {
result = num1 * num2;
}
else if (operation.equals("div")) {
if (num2 == 0) {
out.println("<h2>Cannot divide by zero!</h2>");
return;
}
result = num1 / num2;
}
out.println("<html>");
out.println("<head><title>Calculator Result</title></head>");
out.println("<body>");
out.println("<h2>Calculator Result</h2>");
out.println("<p>First Number: " + num1 + "</p>");
out.println("<p>Second Number: " + num2 + "</p>");
out.println("<p>Result: " + result + "</p>");
out.println("<br>");
out.println("<a href='index.html'>Back to Calculator</a>");
out.println("</body>");
out.println("</html>");
}
}
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
</head>
<body>
<h2>Simple Calculator</h2>
<form action="CalculatorServlet" method="post">
<label>Enter First Number:</label>
<input type="number" name="num1" required>
<br><br>
<label>Enter Second Number:</label>
<input type="number" name="num2" required>
<br><br>
<label>Select Operation:</label>
<select name="operation">
<option value="add">Addition (+)</option>
<option value="sub">Subtraction (-)</option>
<option value="mul">Multiplication (*)</option>
<option value="div">Division (/)</option>
</select>
<br><br>
<input type="submit" value="Calculate">
</form>
</body>
</html>
💻 Output / Explanation
Input: num1=15, num2=25, operation=+ -> Output: Result = 40 rendered in formatted HTML.
Java Practical 9B
Java / Servlets
Java Servlets - Secure Login Authentication Servlet
AIM: Validate user login credentials (admin / 1234) submitted from HTML form and display status messages.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
if ("admin".equals(username) && "1234".equals(password)) {
out.println("<h2>Login Successful</h2>");
out.println("<h3>Welcome, " + username + "!</h3>");
} else {
out.println("<h2>Login Failed</h2>");
out.println("<a href='index.html'>Try Again</a>");
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login Page</h2>
<form action="LoginServlet" method="post">
Username:
<input type="text" name="username" required>
<br><br>
Password:
<input type="password" name="password" required>
<br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
💻 Output / Explanation
admin / 1234 -> Login Successful! Welcome Admin
invalid credentials -> Invalid username or password.