[Go to site: main page, start]

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

Java and Python Programming Examples

Programs

Uploaded by

manotnj2023
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views21 pages

Java and Python Programming Examples

Programs

Uploaded by

manotnj2023
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java and Python Programs

Name : Shanmuga Nathan Manavalan


[Link] : 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) {
[Link](number + " is even.");
} else {
[Link](number + " is odd.");
}

// for loop example


[Link]("For Loop:");
for (int i = 0; i < 5; i++) {
[Link](i);
}

// while loop example


[Link]("While Loop:");
int j = 0;
while (j < 5) {
[Link](j);
j++;
}

// switch example
int day = 3;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("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 [Link];

public class DeclarativeExample {


public static void main(String[] args) {
int sum = [Link](new int[]{1, 2, 3, 4, 5}).sum();
[Link]("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;
}
[Link]("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 = [Link](2, 3);
[Link]("Result: " + result);
}
}
Object Output:

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

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


return a + b;
}
}

Procedure output:

3. Logic :
import [Link];
import [Link];

public class LogicExample {


public static void main(String[] args) {
List<Integer> numbers = [Link](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
[Link](number);
}
}

[Link]("Even Numbers (Logic-Based): " + evenNumbers);


}

// Rule definition for even numbers


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

Logic output:
Functional:
import [Link];
import [Link];

public class FunctionalExample {


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

// Functional approach with streams and lambda expression


List<Integer> evenNumbers = [Link]()
.filter(number -> number % 2 == 0) // Lambda expression
for even check
.collect([Link]());

[Link]("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) {


[Link]("Addition: " + add(5, 3));
[Link]("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) {


[Link] = name;
[Link] = age;
}

void display() {
[Link]("Name: " + name + ", Age: " + age);
}
}

public class Main {


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

class Dog extends Animal {


void sound() {
[Link]("Dog barks");
}
}

public class PolymorphismExample {


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

void showName() {
[Link]("Name: " + name);
}
}

class Employee extends Person {


int employeeId;

void showEmployeeId() {
[Link]("Employee ID: " + employeeId);
}
}

public class InheritanceExample {


public static void main(String[] args) {
Employee emp = new Employee();
[Link] = "Bob";
[Link] = 101;
[Link]();
[Link]();
}
}
OUTPUT:
Question 7:
Simple JAVA Programs to implement thread
Solution:
import [Link];
class Thread1 extends Thread {
public void run() {
[Link]("Thread1 is running");
}
}

class Thread2 extends Thread {


public void run() {
[Link]("Thread2 is running");
}
}

public class ThreadExample {


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

public class JDBCExample {


public static void main(String[] args) {
try {
Connection con =
[Link]("jdbc:mysql://localhost:3306/mydatabase",
"user", "password");
Statement stmt = [Link]();
String sql = "CREATE TABLE Students (ID INT PRIMARY KEY, Name
VARCHAR(50))";
[Link](sql);
[Link]("Table created");
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}
OUTPUT:
Question 9:
Form Design with applet and Swing using JAVA
Solution:
import [Link].*;
import [Link];
import [Link];

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");

[Link](label);
[Link](textField);
[Link](button);
[Link](new [Link]());
[Link](300, 200);
[Link](true);

[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = [Link]();
[Link]("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 = [Link](socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("[Link]", 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 = [Link](1024)
if not data:
break
print("Received from client:", [Link]())
[Link](b"Message received")

[Link]()
server_socket.close()

if __name__ == "__main__":
tcp_server()

OUTPUT:
TCP client:
import socket

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

try:
message = "Hello, TCP Server!"
client_socket.sendall([Link]())

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

if __name__ == "__main__":
tcp_client()

OUTPUT:
UDP server:
import socket

def udp_server():
server_socket = [Link](socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(("[Link]", 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}: {[Link]()}")
server_socket.sendto(b"Message received", addr)

if __name__ == "__main__":
udp_server()

OUTPUT:

UDP client:
import socket

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

message = "Hello, UDP Server!"


client_socket.sendto([Link](), server_address)

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

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 = [Link]()
[Link]("Event Handling Example")

# Create a button and bind the click event


button = [Link](window, text="Click Me", command=on_button_click)
[Link]()

# Run the event loop


[Link]()

OUTPUT:

Common questions

Powered by AI

Polymorphism allows objects to be treated as instances of their parent class, enhancing flexibility and integration. In the Java example, a reference variable of type 'Animal' is used to refer to a 'Dog' object. When calling the 'sound' method on this 'Animal' reference, the program dynamically binds to the 'Dog's' implementation of the method, demonstrating polymorphism by allowing different behaviors for the same method call based on object type .

Procedural programming focuses on sequences of instructions to manipulate data, as seen in functions like 'add' and 'subtract', which perform operations through explicit sequences. Functional programming, on the other hand, embraces higher-order functions and avoids side effects, using concepts like map, filter, and reduce for data processing. For example, functional programming in Python may use lambda expressions within the Stream API to perform operations seamlessly without modifying state .

Inheritance in Java is demonstrated by extending a base class ('Person') with a derived class ('Employee'). The derived class inherits fields and methods from the base class, allowing for code reuse. In this example, 'Employee' inherits the 'name' field and 'showName' method from 'Person'. It also introduces additional fields and methods, such as 'employeeId' and 'showEmployeeId', extending the functionality of the base class .

TCP is a connection-oriented protocol ensuring reliable data transfer, demonstrated by Python examples where the server listens for connections and acknowledges receipt of messages. UDP is connectionless and does not guarantee delivery, offering lower overhead, which is apparent in the code where the server simply awaits messages and responses are not guaranteed. These structural differences influence their use cases, with TCP suitable for reliability and UDP for simplicity and speed .

Java Swing is utilized to create GUI applications by providing a set of lightweight components. In the example, JFrame is used as a top-level container for the window, JLabel for text fields, JTextField for input fields, and JButton for actions. The components are added to the frame using a layout manager, in this case, FlowLayout, outlining a simple interface and event handling through ActionListener .

Java's exception handling mechanism uses try-catch blocks to manage runtime errors, such as those that may occur during database connections. In a JDBC example, establishing a connection might throw an SQLException if errors occur. This is handled by wrapping connection attempts and queries within a try block, and using catch to handle exceptions, logging or displaying the error without crashing the program, thereby ensuring robustness .

Thread creation in Java involves extending the Thread class or implementing the Runnable interface. In the provided example, two classes, Thread1 and Thread2, extend Thread, each overriding the run method to define the code that will execute concurrently. These threads are started using the start method, and they run independently, showcasing concurrent execution in Java .

Constructing NFAs involves defining states and transitions that may lead to multiple states for a given input, resulting in a non-deterministic process. In Python, this is represented with dynamic state transitions where multiple possibilities per character lead to different states. DFAs, on the other hand, represent a deterministic approach, with each state having exactly one transition per input character, reducing complexity and ensuring direct state paths. These differences necessitate varying cognitive strategies for design and verification to ensure acceptance of input strings .

In declarative programming, control structures are abstracted away, focusing on what should be achieved rather than how it is done. For example, using Java Streams in a declarative approach allows summing an array by simply defining the desired operation (sum). In contrast, the imperative paradigm explicitly outlines the control structures used to manipulate the program flow, as shown by the use of a loop to iterate and accumulate values manually .

OOP offers several advantages over procedural programming, such as improved code organization through classes and objects, which encapsulate data and methods. This encapsulation enhances modularity and reusability. For instance, in OOP, a class like 'Calculator' can define methods that are easily reused without redefining them, whereas procedural programming involves standalone functions that can lead to code duplication and harder maintenance .

You might also like