APP
EXPERIMENTS
1.Simple JAVA program using control
structures
public class SimpleProgram
{
public static void main(String[]args)
{
int num = 10;
if (num > 0)
{
System.out.println("The number is positive.");
}
else if (num < 0)
{
System.out.println("The number is negative.");
}
else
{
System.out.println("The number is zero.");
}
for (int i = 1; i <= 5; i++)
{
System.out.println("Count: "+i);
}
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers)
{
System.out.println("Number: "+ number);
}
switch (num){
case 1:
System.out.println("The number is 1.");
break;
case 2:
System.out.println("The number is 2.");
break;
default:
System.out.println("The number is neither 1 nor 2.");
break;
}
}
}
2.Implement Sum of series (1 + 2+ 3+
…..n,1+1/2+1/3 +……..1/n,12 + 22+ 32 +
…….n2) using JAVA
public class SeriesSum
{
public static void main(String[]args)
{
int n = 5;
// Sum of series (1 + 2 + 3 + ... + n)
int sum1 = Series1(n);
System.out.println("Sum of series 1: " + sum1);
// Sum of series (1 + 1/2 + 1/3 + ... + 1/n)
double sum2 = Series2(n);
System.out.println("Sum of series 2: " + sum2);
// Sum of series (12+22+32 + ... + n^2)
int sum3 = Series3(n);
System.out.println("Sum of series 3: " + sum3);
}
public static int Series1(int n)
{
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
public static double Series2(double n)
{
double sum = 0;
for (double i = 1; i <= n; i++){
sum += 1/i;
}
return sum;
}
public static int Series3(int n) {
int sum = 0;
for (int i = 1; i <= n; i++)
{
sum += Math.pow(i, 2);
}
return sum;
}
}
3.Simple JAVA Programs to implement
functions
class Function
{
public static void main(String[]args)
{
int x = 25;
int y = function(x);
System.out.println("The value of y : " + y);
}
public static int function(int input)
{
int result = input * 2;
return result;
}
}
4.Simple JAVA Programs with Class and
Objects
class Add
{
public static void main(String[] args)
{
int num1 = 5;
int num2 = 10;
addition a1= new addition ();
int sum = a1.add(num1, num2);
System.out.println("Sum: "+sum);
}
}
class addition
{
public int add(int num1, int num2)
{
return num1 + num2;
}
}
5.Implement JAVA program - Simple
Calculator using polymorphism
public class ArithmeticOperations
{
public static void main(String[] args)
{
int num1=10;
int num2=20;
int choice= 1;
float result;
switch (choice)
{
case 1:
result = num1 + num2;
System.out.println("Addition: "+ result);
break;
case 2:
result = num1 - num2;
System.out.println("Subtraction: " + result);
break;
case 3:
result = num1 * num2;
System.out.println("Multiplication: " + result);
break;
case 4:
result=num1/num2;
System.out.println("division: " + result);
break;
default:
System.out.println("Invalid operator!");
break;
}
}
}
6.Implement JAVA program - Pay Slip
Generator using Inheritance
import java.util.Scanner;
class Employee {
private String name;
private int id;
public Employee(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public double calculateSalary() {
return 0;
}
}
class FullTimeEmployee extends Employee {
private double salary;
public FullTimeEmployee(String name, int id, double salary) {
super(name, id);
this.salary = salary;
}
@Override
public double calculateSalary() {
return salary;
}
}
class PartTimeEmployee extends Employee {
private double hourlyRate;
private int hoursWorked;
public PartTimeEmployee(String name, int id, double hourlyRate, int hoursWorked) {
super(name, id);
this.hourlyRate = hourlyRate;
this.hoursWorked = hoursWorked;
}
@Override
public double calculateSalary() {
return hourlyRate * hoursWorked;
}
}
class PaySlipGenerator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the employee name: ");
String name = scanner.nextLine();
System.out.print("Enter the employee ID: ");
int id = scanner.nextInt();
System.out.print("Enter the employee type (1 - Full Time, 2 - Part Time): ");
int employeeType = scanner.nextInt();
double salary = 0;
if (employeeType == 1) {
System.out.print("Enter the monthly salary: ");
salary = scanner.nextDouble();
FullTimeEmployee fullTimeEmployee = new FullTimeEmployee(name, id, salary);
salary = fullTimeEmployee.calculateSalary();
} else if (employeeType == 2) {
System.out.print("Enter the hourly rate: ");
double hourlyRate = scanner.nextDouble();
System.out.print("Enter the hours worked: ");
int hoursWorked = scanner.nextInt();
PartTimeEmployee partTimeEmployee = new PartTimeEmployee(name, id,
hourlyRate, hoursWorked);
salary = partTimeEmployee.calculateSalary();
} else {
System.out.println("Invalid employee type!");
System.exit(0);
}
System.out.println("\n--- Pay Slip ---");
System.out.println("\n Employee Name: " + name);
System.out.println("\n Employee ID: " + id);
System.out.println("\n Salary: $" + salary);
}
}
7.Simple JAVA Programs to implement
thread
public class MyThread extends Thread
{
private String threadName;
public MyThread(String name)
{
threadName = name;
System.out.println("Creating " + threadName);
}
public void run()
{
System.out.println("Running " + threadName);
try
{
for (int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
Thread.sleep(50);
}
}
catch (InterruptedException e)
{
System.out.println("Thread " + threadName + " interrupted.");}
System.out.println("Thread " + threadName + " exiting.");
}
public static void main(String args[])
{
MyThread thread1 = new MyThread("Thread 1");
MyThread thread2 = new MyThread("Thread 2");
thread1.start();
thread2.start();
try
{
thread1.join();
thread2.join();
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
8.Simple JAVA Programs with Java Data
Base Connectivity (JDBC)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnectivity
{
public static void main(String[] args)
{
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
try
{
Class.forName(“com.mysql.cj.jdbc.Driver”);
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println("Connected to database");
//perform database operations here
Connection.close();
} catch(ClassNotFoundException e) {
System.out.println(“MySQL JDBC driver not found ");
}catch (SQLException e)
{
System.out.println("Database connection error: " + e.getMessage());
}
} }
9.Form Design with applet and Swing using
JAVA
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class FormDesign extends JApplet {
private JTextField nameField;
private JRadioButton maleRadioButton;
private JRadioButton femaleRadioButton;
private JComboBox<String> countryComboBox;
private JTextArea addressArea;
private JButton submitButton;
public void init() {
setLayout(new FlowLayout());
JLabel nameLabel = new JLabel("Name:");
nameField = new JTextField(20);
JLabel genderLabel = new JLabel("Gender:");
maleRadioButton = new JRadioButton("Male");
femaleRadioButton = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
genderGroup.add(maleRadioButton);
genderGroup.add(femaleRadioButton);
JLabel countryLabel = new JLabel("Country:");
String[] countries = {"USA", "Canada", "UK"};
countryComboBox = new JComboBox<>(countries);
JLabel addressLabel = new JLabel("Address:");
addressArea = new JTextArea(5, 20);
submitButton = new JButton("Submit");
add(nameLabel);
add(nameField);
add(genderLabel);
add(maleRadioButton);
add(femaleRadioButton);
add(countryLabel);
add(countryComboBox);
add(addressLabel);
add(addressArea);
add(submitButton);
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String gender = maleRadioButton.isSelected() ? "Male" : "Female";
String country = (String) countryComboBox.getSelectedItem();
String address = addressArea.getText();
JOptionPane.showMessageDialog(null,
"Name: " + name + "\n" +
"Gender: " + gender + "\n" +
"Country: " + country + "\n" +
"Address: " + address);
}
});
}
public static void main(String[] args) {
// Create an instance of the FormDesign class
FormDesign formDesign = new FormDesign();
// Initialize the applet
formDesign.init();
// Create a JFrame to display the applet
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(formDesign);
frame.setSize(400, 300);
frame.setVisible(true);
}
}
10.Simple Python Program to implement
functions
def addition(n1, n2):
return n1 + n2
n1 = int(input("Enter the first number: "))
n2 = int(input("Enter the second number: "))
sum_result = addition(n1, n2)
print("Sum:", sum_result)
11.Python program using control structures
and arrays
def find_avg(nums):
total = 0
for num in nums:
total += num
avg = total / len(nums)
return avg
num_ele = int(input("Enter the number of elements in the array: "))
array = []
for i in range(num_ele):
ele = int(input("Enter element {}: ".format(i + 1)))
array.append(ele)
avg = find_avg(array)
print("Average:", avg)
12.Implement Python program - TCP/UDP
program using Sockets
import socket
def tcp_server():
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_socket.bind(('localhost', 8888))
tcp_socket.listen(1)
print('TCP Server is listening...')
while True:
conn, addr = tcp_socket.accept()
print('Connected to', addr)
data = conn.recv(1024).decode()
if not data:
break
print('Received:', data)
conn.sendall('Hello from TCP Server!'.encode())
conn.close()
def tcp_client():
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_socket.connect(('localhost', 8888))
tcp_socket.sendall('Hello from TCP Client!'.encode())
data = tcp_socket.recv(1024).decode()
print('Received:', data)
tcp_socket.close()
def udp_server():
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_socket.bind(('localhost', 9999))
print('UDP Server is listening...')
while True:
data, addr = udp_socket.recvfrom(1024)
if not data:
break
print('Received:', data.decode())
udp_socket.sendto('Hello from UDP Server!'.encode(), addr)
def udp_client():
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_socket.sendto('Hello from UDP Client!'.encode(), ('localhost', 9999))
data, addr = udp_socket.recvfrom(1024)
print('Received:', data.decode())
udp_socket.close()
tcp_server()
tcp_client()
udp_server()
udp_client()
13.Construct NFA and DFA using Python
class State:
def init (self, name):
self.name = name
self.transitions = {}
def add_transition(self, symbol, state):
if symbol in self.transitions:
self.transitions[symbol].add(state)
else:
self.transitions[symbol] = {state}
class NFA:
def init (self, start_state, accept_states):
self.start_state = start_state
self.accept_states = accept_states
def accepts(self, input_string):
current_states = {self.start_state}
for symbol in input_string:
next_states = set()
for state in current_states:
if symbol in state.transitions:
next_states.update(state.transitions[symbol])
current_states = next_states
return any(state in self.accept_states for state in current_states)
class DFA:
def init (self, start_state, accept_states):
self.start_state = start_state
self.accept_states = accept_states
self.transitions = {} # Define transitions as an empty dictionary
def add_transition(self, from_state, symbol, to_state):
if from_state not in self.transitions:
self.transitions[from_state] = {}
if symbol not in self.transitions[from_state]:
self.transitions[from_state][symbol] = set()
self.transitions[from_state][symbol].add(to_state)
def accepts(self, input_string):
current_states = {self.start_state}
for symbol in input_string:
next_states = set()
for state in current_states:
if state in self.transitions and symbol in self.transitions[state]:
next_states.update(self.transitions[state][symbol])
current_states = next_states
return any(state in self.accept_states for state in current_states)
# Create an NFA for the language (a|b)*abb
start_state = State("q0")
accept_state = State("q3")
start_state.add_transition("a", start_state)
start_state.add_transition("b", start_state)
start_state.add_transition("a", accept_state)
accept_state.add_transition("b", accept_state)
nfa = NFA(start_state, {accept_state})
# Test the NFA
print(nfa.accepts("abba")) # True
print(nfa.accepts("ab")) # False
# Convert the NFA to a DFA
dfa_start_state = frozenset({start_state})
dfa_accept_states = {state for state in nfa.accept_states if state in dfa_start_state}
dfa = DFA(dfa_start_state, dfa_accept_states)
# Test the DFA
print(dfa.accepts("abba")) # True
print(dfa.accepts("ab")) # False
14.Implement a Python program for the
algebraic manipulations using symbolic
paradigm
python
from sympy import symbols, sin, cos, exp, log
# Define the symbolic variables
x = symbols('x')
y = symbols('y')
# Define the expression
expression = sin(x) + cos(y)
# Perform algebraic manipulation
result = exp(log(expression))
# Evaluate the result
value = result.subs(x, 1.0).subs(y, 2.0)
# Print the result
print("Result:", value)
15.Simple Python programs to implement
event handling
class Event:
def init (self, name):
self.name = name
self.handlers = []
def add_handler(self, handler):
self.handlers.append(handler)
def remove_handler(self, handler):
self.handlers.remove(handler)
def fire(self, *args, **kwargs):
for handler in self.handlers:
handler(*args, **kwargs)
class Button:
def init (self, label):
self.label = label
self.click_event = Event('click')
def click(self):
self.click_event.fire()
def button_click_handler():
print("Button clicked!")
button = Button("Click me")
button.click_event.add_handler(button_click_handler)
button.click()