Experiment No.
– 1
Study of Programming Paradigms
Imperative Programming:
.
public class SumOfNumbers {
public static void main(String[] args) {
int n = 10;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
[Link]("Sum of numbers from 1 to " + n + " is: " + sum);
}
}
OUTPUT :
Object-Oriented Programming (OOP):
class Circle {
double radius;
double calculateArea() {
return [Link] * radius * radius;
}
}
public class CircleDemo {
public static void main(String[] args) {
Circle myCircle = new Circle();
[Link] = 5.0;
double area = [Link]();
[Link]("Area of the circle is: " + area);
}
}
OUTPUT :
Functional Programming:
import [Link];
import [Link];
public class FunctionalDemo {
public static void main(String[] args) {
List<Integer> numbers = [Link](1, 2, 3, 4, 5);
int sum = [Link]()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum();
[Link]("Sum of even numbers: " + sum);
}
}
OUTPUT :
Procedural Programming:
public class Factorial {
static int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
public static void main(String[] args) {
int n = 5;
int result = factorial(n);
[Link]("Factorial of " + n + " is: " + result);
}
}
OUTPUT :
Experiment No. – 2
Implement Sum of series (1 + 2+ 3+…..n,1+1/2+1/3 +… 1/n,12 + 22+
32 + n2) using JAVA
Sum of Natural Numbers (1 + 2 + 3 + ... + n)
public class SumOfNaturalNumbers {
public static void main(String[] args) {
int n = 10; // Change this value to the desired 'n'
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
[Link]("Sum of natural numbers from 1 to " + n + " is: " + sum);
}
}
OUTPUT:
Sum of Reciprocal of Natural Numbers (1 + 1/2 + 1/3 + ... + 1/n):
public class SumOfReciprocalNumbers {
public static void main(String[] args) {
int n = 10; // Change this value to the desired 'n'
double sum = 0.0;
for (int i = 1; i <= n; i++) {
sum += 1.0 / i;
}
[Link]("Sum of reciprocal numbers from 1 to " + n + " is: " + sum);
}
}
OUTPUT:
Sum of Squares of Natural Numbers (12 + 22 + 32 + ... + n2):
public class SumOfSquares {
public static void main(String[] args) {
int n = 10; // Change this value to the desired 'n'
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i * i;
}
[Link]("Sum of squares of natural numbers from 1 to " + n + " is: " + sum);
}
}
OUTPUT:
Experiment No. – 3
Simple JAVA Programs to implement functions
Calculate Factorial
public class Factorial {
public static void main(String[] args) {
int n = 5; // Change this value to the desired number
long factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
[Link]("Factorial of " + n + " is: " + factorial);
}
}
OUTPUT:
Find Prime Numbers
public class PrimeNumbers {
public static void main(String[] args) {
int limit = 50; // Change this value to the desired limit
for (int num = 2; num <= limit; num++) {
boolean isPrime = true;
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
[Link](num + " ");
}
}
}
}
OUTPUT :
Calculate Fibonacci Sequence
public class Fibonacci {
public static void main(String[] args) {
int n = 10; // Change this value to the desired number of terms
int a = 0, b = 1;
[Link]("Fibonacci Sequence: ");
for (int i = 1; i <= n; i++) {
[Link](a + " ");
int sum = a + b;
a = b;
b = sum;
}
}
}
OUTPUT:
Calculate Power (Exponentiation)
public class Power {
public static void main(String[] args) {
double base = 2.0; // Change this value to the base
int exponent = 3; // Change this value to the exponent
double result = 1.0;
for (int i = 0; i < exponent; i++) {
result *= base;
}
[Link](base + " raised to the power of " + exponent + " is: " + result);
}
}
OUTPUT:
Experiment No. – 4
Simple JAVA Programs with Class and Objects
Create a Class and Object:
class Person {
String name;
int age;
void introduce() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
public class PersonDemo {
public static void main(String[] args) {
// Create two Person objects
Person person1 = new Person();
[Link] = "Alice";
[Link] = 30;
Person person2 = new Person();
[Link] = "Bob";
[Link] = 25;
// Call the introduce method for each person
[Link]("Person 1:");
[Link]();
[Link]("\nPerson 2:");
[Link]();
}
}
OUTPUT:
Bank Account Class:
class BankAccount {
String accountNumber;
String accountHolder;
double balance;
void deposit(double amount) {
balance += amount;
}
void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
} else {
[Link]("Insufficient funds!");
}
}
void displayBalance() {
[Link]("Account Number: " + accountNumber);
[Link]("Account Holder: " + accountHolder);
[Link]("Balance: $" + balance);
}
}
public class BankAccountDemo {
public static void main(String[] args) {
BankAccount account1 = new BankAccount();
[Link] = "12345";
[Link] = "Alice";
[Link] = 1000.0;
[Link]();
[Link](500.0);
[Link]();
[Link](200.0);
[Link]();
}
}
OUTPUT:
Experiment No. – 5
Implement JAVA program - Simple Calculator using polymorphism
class Calculator {
public int calculate(int num1, int num2) {
return num1 + num2;
}
public double calculate(double num1, double num2) {
return num1 + num2;
}
public int calculateSubtraction(int num1, int num2) {
return num1 - num2;
}
public double calculateSubtraction(double num1, double num2) {
return num1 - num2;
}
public int calculateMultiplication(int num1, int num2) {
return num1 * num2;
}
public double calculateMultiplication(double num1, double num2) {
return num1 * num2;
}
public int calculateDivision(int num1, int num2) {
if (num2 != 0) {
return num1 / num2;
} else {
[Link]("Division by zero is not allowed.");
return 0;
}
}
public double calculateDivision(double num1, double num2) {
if (num2 != 0.0) {
return num1 / num2;
} else {
[Link]("Division by zero is not allowed.");
return 0.0;
}
}
}
public class CalculatorDemo {
public static void main(String[] args) {
Calculator calculator = new Calculator();
// Integer addition
[Link]("Integer Addition: " + [Link](5, 3));
// Double addition
[Link]("Double Addition: " + [Link](5.5, 3.3));
// Integer subtraction
[Link]("Integer Subtraction: " + [Link](10, 4));
// Double subtraction
[Link]("Double Subtraction: " + [Link](10.5, 4.2));
// Integer multiplication
[Link]("Integer Multiplication: " + [Link](6, 7));
// Double multiplication
[Link]("Double Multiplication: " + [Link](6.6, 7.7));
// Integer division
[Link]("Integer Division: " + [Link](20, 4));
// Double division
[Link]("Double Division: " + [Link](20.0, 0.0));
}
}
OUTPUT:
Experiment No. – 6
Implement JAVA program - Pay Slip Generator using Inheritance
// Base class Employee
class Employee {
private String name;
private String employeeId;
public Employee(String name, String employeeId) {
[Link] = name;
[Link] = employeeId;
}
public String getName() {
return name;
}
public String getEmployeeId() {
return employeeId;
}
// This method will be overridden by derived classes
public double calculatePay() {
return 0.0;
}
}
// Derived class SalariedEmployee
class SalariedEmployee extends Employee {
private double monthlySalary;
public SalariedEmployee(String name, String employeeId, double monthlySalary) {
super(name, employeeId);
[Link] = monthlySalary;
}
@Override
public double calculatePay() {
return monthlySalary;
}
}
// Derived class HourlyEmployee
class HourlyEmployee extends Employee {
private double hourlyRate;
private int hoursWorked;
public HourlyEmployee(String name, String employeeId, double hourlyRate, int hoursWorked) {
super(name, employeeId);
[Link] = hourlyRate;
[Link] = hoursWorked;
}
@Override
public double calculatePay() {
return hourlyRate * hoursWorked;
}
}
public class PaySlipGenerator {
public static void main(String[] args) {
// Create SalariedEmployee and HourlyEmployee objects
SalariedEmployee salariedEmployee = new SalariedEmployee("Alice", "E001", 5000.0);
HourlyEmployee hourlyEmployee = new HourlyEmployee("Bob", "E002", 15.0, 40);
// Generate pay slips
generatePaySlip(salariedEmployee);
generatePaySlip(hourlyEmployee);
}
// Method to generate pay slip
public static void generatePaySlip(Employee employee) {
[Link]("Pay Slip for Employee: " + [Link]());
[Link]("Employee ID: " + [Link]());
[Link]("Monthly Salary: $" + [Link]());
[Link]("--------------------------");
}
}
OUTPUT:
Experiment No. – 7
Simple JAVA Programs to implement thread
Using the Thread Class:
class MyThread extends Thread {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Thread " + [Link]().getId() + ": Count " + i);
}
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
[Link]();
[Link]();
}
}
OUTPUT:
Using the Runnable Interface:
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Thread " + [Link]().getId() + ": Count " + i);
}
}
}
public class RunnableExample {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread1 = new Thread(myRunnable);
Thread thread2 = new Thread(myRunnable);
[Link]();
[Link]();
}
}
OUTPUT:
Experiment No. – 8
Simple JAVA Programs with Java Data Base Connectivity (JDBC)
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCSample {
public static void main(String[] args) {
Connection connection = null;
try {
// Connect to the database (SQLite in this case)
[Link]("[Link]");
connection = [Link]("jdbc:sqlite:[Link]");
[Link]("Connected to the database.");
// Create a table
Statement statement = [Link]();
String createTableSQL = "CREATE TABLE IF NOT EXISTS employees " +
"(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INT)";
[Link](createTableSQL);
[Link]("Table 'employees' created (if it didn't exist).");
// Insert data
String insertDataSQL = "INSERT INTO employees (name, age) VALUES ('Alice', 30),
('Bob', 25), ('Charlie', 35)";
[Link](insertDataSQL);
[Link]("Data inserted into the table.");
// Query data
String querySQL = "SELECT * FROM employees";
ResultSet resultSet = [Link](querySQL);
// Display query results
[Link]("\nEmployee Data:");
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
int age = [Link]("age");
[Link]("ID: " + id + ", Name: " + name + ", Age: " + age);
}
} catch (ClassNotFoundException | SQLException e) {
[Link]();
} finally {
try {
if (connection != null) {
[Link]();
[Link]("\nDisconnected from the database.");
}
} catch (SQLException e) {
[Link]();
}
}
}
}
OUTPUT:
Experiment No. – 9
Form Design with applet and Swing using JAVA
import [Link].*;
import [Link].*;
import [Link];
import [Link];
public class SimpleFormApplet extends JApplet implements ActionListener {
private JTextField nameField;
private JTextField emailField;
private JButton submitButton;
@Override
public void init() {
// Set up the layout manager
setLayout(new GridLayout(3, 2));
// Create and add components to the form
JLabel nameLabel = new JLabel("Name:");
nameField = new JTextField(20);
JLabel emailLabel = new JLabel("Email:");
emailField = new JTextField(20);
submitButton = new JButton("Submit");
[Link](this);
add(nameLabel);
add(nameField);
add(emailLabel);
add(emailField);
add(new JLabel()); // Empty cell for spacing
add(submitButton);
}
@Override
public void actionPerformed(ActionEvent e) {
if ([Link]() == submitButton) {
// Handle the submit button click
String name = [Link]();
String email = [Link]();
// Display a message dialog with the entered data
[Link](this,
"Name: " + name + "\nEmail: " + email,
"Form Submission",
JOptionPane.INFORMATION_MESSAGE);
// Clear the input fields
[Link]("");
[Link]("");
}
}
}
To run this applet, you can create an HTML file (e.g., [Link]) with the
following content:
<!DOCTYPE html>
<html>
<head>
<title>Simple Form Applet</title>
</head>
<body>
<applet code="[Link]" width="300" height="120"></applet>
</body>
</html>
OUTPUT:
Experiment No. – 10
Simple Python Program to implement functions
Calculate Factorial:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
num = 5 # Change this value to the desired number
result = factorial(num)
print(f"Factorial of {num} is: {result}")
OUTPUT:
Find Prime Numbers:
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
limit = 50 # Change this value to the desired limit
prime_numbers = [num for num in range(2, limit + 1) if is_prime(num)]
print("Prime numbers up to", limit, "are:", prime_numbers)
OUTPUT:
Calculate Fibonacci Sequence:
def fibonacci(n):
fib_sequence = [0, 1]
while len(fib_sequence) < n:
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence
num_terms = 10 # Change this value to the desired number of terms
fibonacci_sequence = fibonacci(num_terms)
print("Fibonacci Sequence:", fibonacci_sequence)
OUTPUT:
Calculate Power (Exponentiation):
def power(base, exponent):
result = 1
for _ in range(exponent):
result *= base
return result
base = 2.0 # Change this value to the base
exponent = 3 # Change this value to the exponent
result = power(base, exponent)
print(f"{base} raised to the power of {exponent} is: {result}")
Python program using control structures and arrays
OUTPUT:
Experiment No. – 11
Python program using control structures and arrays
# Create an array (list) of numbers
numbers = [12, 45, 78, 23, 56, 89, 9, 67, 32, 5]
# Initialize variables to store the maximum and minimum values
max_value = numbers[0]
min_value = numbers[0]
# Use a for loop to iterate through the array and find max and min values
for num in numbers:
if num > max_value:
max_value = num
if num < min_value:
min_value = num
# Print the maximum and minimum values
print("Maximum value in the array:", max_value)
print("Minimum value in the array:", min_value)
OUTPUT:
Experiment No. – 12
Implement Python program - TCP/UDP program using Sockets
TCP Server:
import socket
# Create a socket object
server_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)
# Get the local machine's hostname and specify a port
host = [Link]()
port = 12345
# Bind the socket to the address
server_socket.bind((host, port))
# Listen for incoming connections
server_socket.listen(5)
print("TCP Server listening on {}:{}".format(host, port))
while True:
# Establish a connection with the client
client_socket, addr = server_socket.accept()
print("Connected to {}:{}".format(addr[0], addr[1]))
# Send data to the client
message = "Hello, client! This is the TCP server."
client_socket.send([Link]('utf-8'))
# Receive data from the client
data = client_socket.recv(1024)
print("Received from client: {}".format([Link]('utf-8')))
# Close the client socket
client_socket.close()
OUTPUT:
TCP Client:
import socket
# Create a socket object
client_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)
# Get the server hostname and port
host = [Link]()
port = 12345
# Connect to the server
client_socket.connect((host, port))
# Receive data from the server
data = client_socket.recv(1024)
print("Received from server: {}".format([Link]('utf-8')))
# Send data to the server
message = "Hello, server! This is the TCP client."
client_socket.send([Link]('utf-8'))
# Close the client socket
client_socket.close()
To run the TCP server and client, you can run them in separate terminal windows or on different
machines.
OUTPUT:
UDP Server:
import socket
# Create a UDP socket
server_socket = [Link](socket.AF_INET, socket.SOCK_DGRAM)
# Get the local machine's hostname and specify a port
host = [Link]()
port = 12345
# Bind the socket to the address
server_socket.bind((host, port))
print("UDP Server listening on {}:{}".format(host, port))
while True:
# Receive data from the client
data, addr = server_socket.recvfrom(1024)
print("Received from client {}:{}".format(addr[0], addr[1]))
print("Data: {}".format([Link]('utf-8')))
# Send data back to the client
response = "Hello, client! This is the UDP server."
server_socket.sendto([Link]('utf-8'), addr)
OUTPUT:
UDP Client:
import socket
# Create a UDP socket
client_socket = [Link](socket.AF_INET, socket.SOCK_DGRAM)
# Get the server hostname and port
host = [Link]()
port = 12345
# Send data to the server
message = "Hello, server! This is the UDP client."
client_socket.sendto([Link]('utf-8'), (host, port))
# Receive data from the server
data, addr = client_socket.recvfrom(1024)
print("Received from server {}:{}".format(addr[0], addr[1]))
print("Data: {}".format([Link]('utf-8')))
# Close the client socket
client_socket.close()
OUTPUT:
Experiment No. – 13
Construct NFA and DFA using Python
# Define the NFA transitions as a dictionary
nfa = {
'q0': {'0': ['q0'], '1': ['q0', 'q1']},
'q1': {'0': ['q2']},
'q2': {}
}
def nfa_accepts(input_string, current_state, nfa):
if not input_string:
return current_state in accepting_states
current_char, remaining_input = input_string[0], input_string[1:]
next_states = [Link](current_state, {}).get(current_char, [])
for next_state in next_states:
if nfa_accepts(remaining_input, next_state, nfa):
return True
return False
# Test the NFA
accepting_states = ['q2']
input_string = "0110"
result = nfa_accepts(input_string, 'q0', nfa)
print(f"NFA Result: Input '{input_string}' {'accepted' if result else 'rejected'}")
def powerset(s):
return list(chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)))
def nfa_to_dfa(nfa):
alphabet = set(chain.from_iterable(nfa[state].keys() for state in nfa))
dfa = {}
states_to_explore = [frozenset(['q0'])]
while states_to_explore:
current_state_set = states_to_explore.pop()
dfa[current_state_set] = {}
for char in alphabet:
next_state_set = set()
for nfa_state in current_state_set:
next_state_set.update([Link](nfa_state, {}).get(char, []))
dfa[current_state_set][char] = frozenset(next_state_set)
if frozenset(next_state_set) not in dfa:
states_to_explore.append(frozenset(next_state_set))
return dfa
# Convert NFA to DFA
dfa = nfa_to_dfa(nfa)
# Define accepting states for the DFA
accepting_states_dfa = {k for k, v in [Link]() if any(state in accepting_states for state in k)}
# Test the DFA
input_string_dfa = "0110"
current_state_dfa = frozenset(['q0'])
for char in input_string_dfa:
current_state_dfa = dfa[current_state_dfa][char]
dfa_result = current_state_dfa in accepting_states_dfa
print(f"DFA Result: Input '{input_string_dfa}' {'accepted' if dfa_result else 'rejected'}")
OUTPUT:
Experiment No. – 14
Implement a Python program for the algebraic manipulations using
symbolic paradigm
# Define symbolic variables
x, y = [Link]('x y')
# Define algebraic expressions
expression1 = x**2 + 2*x + 1
expression2 = x**3 - y**3
# Expand an expression
expanded_expression = [Link](expression1)
print("Expanded Expression:", expanded_expression)
# Factorize an expression
factored_expression = [Link](expression2)
print("Factored Expression:", factored_expression)
# Simplify an expression
expression3 = (x**2 - 1)/(x - 1)
simplified_expression = [Link](expression3)
print("Simplified Expression:", simplified_expression)
# Solve equations
equation = [Link](x**2 - 4, 0)
solutions = [Link](equation, x)
print("Solutions to x^2 - 4 = 0:", solutions)
# Differentiate an expression
derivative = [Link](x**3, x)
print("Derivative of x^3:", derivative)
# Integrate an expression
integral = [Link](x**2, x)
print("Integral of x^2:", integral)
OUTPUT:
Experiment No. – 15
Simple Python programs to implement event handling
# Define a function to handle the button click event
def button_click():
[Link](text="Button Clicked!")
# Create the main window
root = [Link]()
[Link]("Event Handling Example")
# Create a label widget
label = [Link](root, text="Click the button")
# Create a button widget and attach the button_click function to its command
button = [Link](root, text="Click Me", command=button_click)
# Pack the label and button widgets
[Link]()
[Link]()
# Start the main event loop
[Link]()
OUTPUT: