0% found this document useful (0 votes)
20 views21 pages

APP Java and Python Program

Programs

Uploaded by

manotnj2023
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
20 views21 pages

APP Java and Python Program

Programs

Uploaded by

manotnj2023
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 21

Java and Python Programs

Name : Shanmuga Nathan Manavalan


Reg.no : RA2311030050031
Subject code : 21CSC203P
Subject name : Advanced Programming Practice
Question 1:
Study of Programming Paradigms(Control Structures Using Java)
Solution:
public class ControlStructures {
public static void main(String[] args) {
int number = 10;

// if-else example
if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}

// for loop example


System.out.println("For Loop:");
for (int i = 0; i < 5; i++) {
System.out.println(i);
}

// while loop example


System.out.println("While Loop:");
int j = 0;
while (j < 5) {
System.out.println(j);
j++;
}

// switch example
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Other day");
break;
}
}
}
OUTPUT:
Question 2:
Comparative Analysis between programming Paradigms
1. Declarative Vs Imperative
2. Object Vs Procedural
3. Logic Vs Functional
Solution:
1. Declarative
import java.util.Arrays;

public class DeclarativeExample {


public static void main(String[] args) {
int sum = Arrays.stream(new int[]{1, 2, 3, 4, 5}).sum();
System.out.println("Sum: " + sum);
}
}
Declarative Output:

Imperative
public class ImperativeExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int number : numbers) {
sum += number;
}
System.out.println("Sum: " + sum);
}
}
Imperative Output:

2. Object :
// Object-Oriented example
class Calculator {
public int add(int a, int b) {
return a + b;
}
}

public class ObjectOrientedExample {


public static void main(String[] args) {
Calculator calculator = new Calculator();
int result = calculator.add(2, 3);
System.out.println("Result: " + result);
}
}
Object Output:

Procedural :
// Procedural example
public class ProceduralExample {
public static void main(String[] args) {
int result = add(2, 3);
System.out.println("Result: " + result);
}

public static int add(int a, int b) {


return a + b;
}
}

Procedure output:

3. Logic :
import java.util.ArrayList;
import java.util.List;

public class LogicExample {


public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = new ArrayList<>();

for (int number : numbers) {


if (isEven(number)) { // Logic: Only select even numbers
evenNumbers.add(number);
}
}

System.out.println("Even Numbers (Logic-Based): " + evenNumbers);


}

// Rule definition for even numbers


public static boolean isEven(int number) {
return number % 2 == 0;
}
}

Logic output:
Functional:
import java.util.List;
import java.util.stream.Collectors;

public class FunctionalExample {


public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

// Functional approach with streams and lambda expression


List<Integer> evenNumbers = numbers.stream()
.filter(number -> number % 2 == 0) // Lambda expression
for even check
.collect(Collectors.toList());

System.out.println("Even Numbers (Functional-Based): " +


evenNumbers);
}
}

Functional output:
Question 3:
Simple JAVA Programs to implement functions
Solution:
public class SimpleFunctions {
public static int add(int a, int b) {
return a + b;
}

public static int subtract(int a, int b) {


return a - b;
}

public static void main(String[] args) {


System.out.println("Addition: " + add(5, 3));
System.out.println("Subtraction: " + subtract(5, 3));
}
}
OUTPUT:
Question 4:
Simple JAVA Programs with Class and Objects
Solution:
class Student {
String name;
int age;

Student(String name, int age) {


this.name = name;
this.age = age;
}

void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

public class Main {


public static void main(String[] args) {
Student student = new Student("Alice", 20);
student.display();
}
}
OUTPUT:
Question 5:
Implement JA VA program using polymorphism
Solution:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Dog barks");
}
}

public class PolymorphismExample {


public static void main(String[] args) {
Animal myAnimal = new Dog(); // Polymorphism
myAnimal.sound(); // Calls Dog's sound method
}
}
OUTPUT:
Question 6:
Implement JAVA program using Inheritance
Solution:
class Person {
String name;

void showName() {
System.out.println("Name: " + name);
}
}

class Employee extends Person {


int employeeId;

void showEmployeeId() {
System.out.println("Employee ID: " + employeeId);
}
}

public class InheritanceExample {


public static void main(String[] args) {
Employee emp = new Employee();
emp.name = "Bob";
emp.employeeId = 101;
emp.showName();
emp.showEmployeeId();
}
}
OUTPUT:
Question 7:
Simple JAVA Programs to implement thread
Solution:
import java.lang.Thread;
class Thread1 extends Thread {
public void run() {
System.out.println("Thread1 is running");
}
}

class Thread2 extends Thread {


public void run() {
System.out.println("Thread2 is running");
}
}

public class ThreadExample {


public static void main(String[] args) {
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
t1.start();
t2.start();
}
}
OUTPUT:
Question 8:
Simple JAVA Programs with Java Data Base Connectivity (JDBC)
Solution:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class JDBCExample {


public static void main(String[] args) {
try {
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",
"user", "password");
Statement stmt = con.createStatement();
String sql = "CREATE TABLE Students (ID INT PRIMARY KEY, Name
VARCHAR(50))";
stmt.executeUpdate(sql);
System.out.println("Table created");
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
OUTPUT:
Question 9:
Form Design with applet and Swing using JAVA
Solution:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class FormDesign {


public static void main(String[] args) {
JFrame frame = new JFrame("Form");
JLabel label = new JLabel("Name:");
JTextField textField = new JTextField(20);
JButton button = new JButton("Submit");

frame.add(label);
frame.add(textField);
frame.add(button);
frame.setLayout(new java.awt.FlowLayout());
frame.setSize(300, 200);
frame.setVisible(true);

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = textField.getText();
System.out.println("Name: " + name);
}
});
}
}
OUTPUT:
Question 10:
Simple Python Program to implement functions
Solution:
def add(a, b):
return a + b

def subtract(a, b):


return a - b

def multiply(a, b):


return a * b

def divide(a, b):


return a / b if b != 0 else "Cannot divide by zero"

# Test the functions


print("Addition:", add(5, 3))
print("Subtraction:", subtract(5, 3))
print("Multiplication:", multiply(5, 3))
print("Division:", divide(5, 3))

OUTPUT:
Question 11:
Python program using control structures and arrays
Solution:
numbers = [1, 2, 3, 4, 5]
even_numbers = []
odd_numbers = []

for number in numbers:


if number % 2 == 0:
even_numbers.append(number)
else:
odd_numbers.append(number)

print("Even Numbers:", even_numbers)


print("Odd Numbers:", odd_numbers)

OUTPUT:
Question 12:
Implement Python program - TCP/UDP program using Sockets
Solution:
TCP server:
import socket

def tcp_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("192.168.31.116", 2224)) # Use server's local
IP address
server_socket.listen(1)
print("TCP Server is listening on port 2224...")

conn, addr = server_socket.accept()


print(f"Connection from {addr}")

while True:
data = conn.recv(1024)
if not data:
break
print("Received from client:", data.decode())
conn.sendall(b"Message received")

conn.close()
server_socket.close()

if __name__ == "__main__":
tcp_server()

OUTPUT:
TCP client:
import socket

def tcp_client():
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("192.168.31.116", 2224)) # Connect to
server's local IP

try:
message = "Hello, TCP Server!"
client_socket.sendall(message.encode())

response = client_socket.recv(1024)
print("Received from server:", response.decode())
finally:
client_socket.close()

if __name__ == "__main__":
tcp_client()

OUTPUT:
UDP server:
import socket

def udp_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(("192.168.31.116", 2224)) # Use server's local
IP address
print("UDP Server is listening on port 12345...")

while True:
data, addr = server_socket.recvfrom(1024)
print(f"Received from {addr}: {data.decode()}")
server_socket.sendto(b"Message received", addr)

if __name__ == "__main__":
udp_server()

OUTPUT:

UDP client:
import socket

def udp_client():
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ("192.168.31.116", 2224) # Use server's local IP
address

message = "Hello, UDP Server!"


client_socket.sendto(message.encode(), server_address)

data, _ = client_socket.recvfrom(1024)
print("Received from server:", data.decode())

client_socket.close()

if __name__ == "__main__":
udp_client()

OUTPUT:
Question 13:
Construct NFA and DFA using Python
Solution:
Non-deterministic Finite Automaton(NFA)
def nfa_accepts(string):
current_states = {0} # Start with initial state 0
for char in string:
next_states = set()
for state in current_states:
if state == 0:
if char == '0':
next_states.update([0, 1]) # Stay in 0 or move to
1
elif char == '1':
next_states.add(0) # Stay in 0 on '1'
elif state == 1:
if char == '1':
next_states.add(2) # Move to accepting state 2
current_states = next_states

return 2 in current_states # Accept if any current state is 2

# Test the NFA


test_string = "1101"
print(f"NFA accepts '{test_string}':", nfa_accepts(test_string))

OUTPUT:
Deterministic Finite Automaton (DFA)
def dfa_accepts(string):
state = 0 # Start state
for char in string:
if state == 0:
state = 1 if char == '0' else 0
elif state == 1:
state = 2 if char == '1' else 1
elif state == 2:
state = 1 if char == '0' else 0
return state == 2 # Accept if in state 2

# Test the DFA


test_string = "1101"
print(f"DFA accepts '{test_string}':", dfa_accepts(test_string))

OUTPUT:
Question 14:
Implement a Python program for the algebraic manipulations using
symbolicparadigm
Solution:
from sympy import symbols, expand, factor

# Define symbolic variables


x, y = symbols('x y')

# Algebraic manipulation
expression = (x + y)**2

expanded_expr = expand(expression)
factored_expr = factor(expanded_expr)

print("Original Expression:", expression)


print("Expanded Expression:", expanded_expr)
print("Factored Expression:", factored_expr)

OUTPUT:
Question 15:
Simple Python programs to implement event handling
Solution:
import tkinter as tk

def on_button_click():
print("Button clicked!")

# Create the main window


window = tk.Tk()
window.title("Event Handling Example")

# Create a button and bind the click event


button = tk.Button(window, text="Click Me", command=on_button_click)
button.pack()

# Run the event loop


window.mainloop()

OUTPUT:

You might also like