0% found this document useful (0 votes)
3 views37 pages

Java Lab Manual Tybtech

The document is a laboratory manual for a Java programming course at JSPM University Pune, detailing various programming assignments and objectives for students. It covers topics such as calculating factorials, control flow statements, constructors, bank account management, multilevel inheritance, and run-time polymorphism. Each section includes problem statements, aims, objectives, source code examples, and conclusions to enhance understanding of Java programming concepts.

Uploaded by

adeshthorat6509
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)
3 views37 pages

Java Lab Manual Tybtech

The document is a laboratory manual for a Java programming course at JSPM University Pune, detailing various programming assignments and objectives for students. It covers topics such as calculating factorials, control flow statements, constructors, bank account management, multilevel inheritance, and run-time polymorphism. Each section includes problem statements, aims, objectives, source code examples, and conclusions to enhance understanding of Java programming concepts.

Uploaded by

adeshthorat6509
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

JSPM University Pune

Faculty of Science and Technology


School of Computational Sciences

Foundation of Java Programming


(F.Y./S.Y./T.Y, 2025 Course)

LABORATORY MANUAL
(Effective from AY: 2025-26)
JSPM University Pune
Faculty of Science and Technology
School of Computational Sciences
Department of------------------------------------------------------

INDEX
1. Implement a Java program to calculate the factorial of a number using
loops.
2. Write a Java program to demonstrate all control flow statements (if-else,
switch, for, while, do-while).
3.
Write a program to demonstrate the use of constructors.

4 Write a program to create a class Bank Account with methods to deposit,


withdraw, and check balance.
5. Demonstrate multilevel inheritance using a Person → Student → Graduate
hierarchy.
Create a Java application that demonstrates run-time polymorphism with
6. overriding and interfaces.

7. Create a Java program that throws user-defined exceptions for invalid age
input.

8. Create a program that handles multiple exceptions in a single block and logs
errors into a file.

9. Create multiple threads that print even and odd numbers using Thread and
Runnable.

10. Develop a chat application using Java Socket programming (basic one-to-
one).

11. Build a JDBC program to perform CRUD operation on all student records
from a database.

12. A company wants to maintain a list of employees who attended a training.


Write a program to store their names in a Collection, remove duplicates, and
display them in alphabetical order
1. Problem Statement: Implement a Java program to calculate the factorial of a number
using loops.

Aim: To implement a Java program to calculate the factorial of a number using loops.

Objective: The objective of this program is to calculate the factorial of a non-negative


integer provided by the user using an iterative approach (loops) in Java. The factorial of a
number 'n' (denoted as n!) is the product of all positive integers less than or equal to 'n'.

Flowchart:

Source code :

public class Factorial {

public static void main(String[] args)

{ int num = 10;


long factorial = 1;
for(int i = 1; i <= num; ++i)
{
// factorial = factorial * i;
factorial *= i;
}
[Link]("Factorial of %d = %d", num, factorial);
}
}

Output :

Conclusion:
This program effectively calculates the factorial of a non-negative integer using a for loop,
demonstrating a fundamental iterative approach in Java programming. The use of long for the
factorial variable is crucial for handling larger input numbers and preventing integer overflow.
2. Problem Statement: Write a Java program to demonstrate all control flow statements (if-
else, switch, for, while, do-while).

Aim: To Write a Java program to demonstrate all control flow statements (if-else,
switch, for, while, do-while).

Objective: To illustrate the functionality and usage of Java's control flow statements: if-
else, switch, for, while, and do-while, demonstrating how they alter the sequential execution
of a program based on conditions or for repetitive tasks.

Source code :

public class ControlFlowDemo {

public static void main(String[] args) {

// 1. if-else statement
int number = 10;
if (number > 0) {
[Link]("if-else: The number is positive.");
} else {
[Link]("if-else: The number is not positive.");
}

// 2. switch statement
char grade = 'B';
switch (grade) {

case 'A':
[Link]("switch: Excellent!");
break;
case 'B':
[Link]("switch: Good!");
break;
case 'C':
[Link]("switch: Pass.");
break;
default:
[Link]("switch: Needs improvement.");
}
// 3. for loop
[Link]("for loop: Counting from 1 to 5:");
for (int i = 1; i <= 5; i++) {
[Link](i);
}

// 4. while loop
[Link]("while loop: Counting down from 3:");
int count = 3;
while (count > 0) {
[Link](count);
count--;
}

// 5. do-while loop
[Link]("do-while loop: Executing at least once:");
int i = 0;
do {
[Link]("Iteration " + i);
i++;
} while (i < 2);
}
}
Output :

Conclusion: The do-while loop in Java provides a powerful tool for executing a block of
code repeatedly with the guarantee of at least one execution. Understanding its syntax and
behavior, along with careful consideration of initialization, condition checks, and
modifications within the loop, can help in effectively utilizing this control flow statement.
3. Problem Statement: Write a program to demonstrate the use of constructors.

Aim: The aim is to demonstrate the fundamental concept of constructors in Java,


including their purpose in initializing objects, how to define them, and the distinction
between default and parameterized constructors.

Objective: The objective is to demonstrate the creation and use of both default (no-
argument) and parameterized constructors in Java, illustrating how they initialize object
states upon instantiation.

Source code :

class Car {
String model;
int year;

// Default Constructor
public Car() {
[Link] = "Unknown";
[Link] = 0;
[Link]("Default constructor called: Initializing with default values.");
}

// Parameterized Constructor
public Car(String model, int year)
{ [Link] = model;
[Link] = year;
[Link]("Parameterized constructor called: Initializing with provided values.");
}

public void displayCarDetails() {


[Link]("Car Model: " + model + ", Year: " + year);
}

public static void main(String[] args) {


[Link]("Creating car1 using default constructor:");
Car car1 = new Car(); // Calls the default constructor
[Link]();

[Link]("\nCreating car2 using parameterized constructor:");


Car car2 = new Car("Toyota Camry", 2023); // Calls the parameterized constructor
[Link]();
}
}
Output :

Conclusion:
Constructors in Java are special methods used for initializing objects. They are invoked automatically when an
object is created using the new keyword. Default constructors, either implicitly provided by the compiler or
explicitly defined without arguments, initialize object fields with default values. Parameterized constructors
allow for the initialization of object fields with specific values passed during object creation, offering flexibility
in setting up object states. The demonstration illustrates how both types of constructors facilitate controlled and
predictable object initialization in Java programs
4. Problem Statement: Write a program to create a class Bank Account with methods to deposit,
withdraw, and check balance.

Aim: Write a Java program to create a class known as "BankAccount" with methods
called deposit() and withdraw(). Create a subclass called SavingsAccount that
overrides the withdraw() method to prevent withdrawals if the account balance falls
below one hundred.

Objective: The objective is to demonstrate the fundamental principles of Object-Oriented


Programming (OOP) in Java by creating a BankAccount class. This class will encapsulate
bank account data (balance) and provide methods for common banking operations:
depositing funds, withdrawing funds, and checking the current balance.

Flowchart:
Source code :

// [Link]
// Parent class BankAccount

// Declare the BankAccount class


public class BankAccount {
// Private field to store the account number
private String accountNumber;

// Private field to store the balance


private double balance;

// Constructor to initialize account number and balance


public BankAccount(String accountNumber, double balance)
{ [Link] = accountNumber;
[Link] = balance;
}

// Method to deposit an amount into the


account public void deposit(double amount)
{
// Increase the balance by the deposit amount
balance += amount;
}

// Method to withdraw an amount from the


account public void withdraw(double amount)
{
// Check if the balance is sufficient for the
withdrawal if (balance >= amount) {
// Decrease the balance by the withdrawal amount
balance -= amount;
} else {
// Print a message if the balance is insufficient
[Link]("Insufficient balance");
}
}

// Method to get the current


balance public double
getBalance() {
// Return the current balance
return balance;
}
}
// [Link]
// Child class SavingsAccount

// Declare the SavingsAccount class, inheriting from BankAccount


public class SavingsAccount extends BankAccount {
// Constructor to initialize account number and balance
public SavingsAccount(String accountNumber, double balance) {
// Call the parent class constructor
super(accountNumber, balance);
}

// Override the withdraw method from the parent class


@Override
public void withdraw(double amount) {
// Check if the withdrawal would cause the balance to drop below
$100 if (getBalance() - amount < 100) {
// Print a message if the minimum balance requirement is not
met [Link]("Minimum balance of $100
required!");
} else {
// Call the parent class withdraw method
[Link](amount);
}
}
}
// [Link]
// Main class

// Define the Main


class public class
Main {
// Main method, entry point of the program
public static void main(String[] args) {
// Print message to indicate creation of a BankAccount object
[Link]("Create a Bank Account object (A/c No. BA1234) with initial balance of
$500:");
// Create a BankAccount object (A/c No. "BA1234") with initial balance of $500
BankAccount BA1234 = new BankAccount("BA1234", 500);

// Print message to indicate deposit action


[Link]("Deposit $1000 into account BA1234:");
// Deposit $1000 into account BA1234
[Link](1000);
// Print the new balance after deposit
[Link]("New balance after depositing $1000: $" + [Link]());

// Print message to indicate withdrawal action


[Link]("Withdraw $600 from account BA1234:");
// Withdraw $600 from account BA1234
[Link](600);
// Print the new balance after withdrawal
[Link]("New balance after withdrawing $600: $" + [Link]());

// Print message to indicate creation of a SavingsAccount object


[Link]("\nCreate a SavingsAccount object (A/c No. SA1234) with initial balance of
$450:");
// Create a SavingsAccount object (A/c No. "SA1234") with initial balance of $450
SavingsAccount SA1234 = new SavingsAccount("SA1234", 450);

// Withdraw $300 from SA1234


[Link](300);
// Print the balance after attempting to withdraw $300
[Link]("Balance after trying to withdraw $300: $" + [Link]());

// Print message to indicate creation of another SavingsAccount object [Link]("\


nCreate a SavingsAccount object (A/c No. SA1000) with initial balance of
$300:");
// Create a SavingsAccount object (A/c No. "SA1000") with initial balance of $300
SavingsAccount SA1000 = new SavingsAccount("SA1000", 300);

// Print message to indicate withdrawal action


[Link]("Try to withdraw $250 from SA1000!");
// Withdraw $250 from SA1000 (balance falls below $100)
[Link](250);
// Print the balance after attempting to withdraw $250
[Link]("Balance after trying to withdraw $250: $" + [Link]());
}
}
Output :

Conclusion:
This program successfully demonstrates the creation of a BankAccount class in Java,
illustrating key OOP concepts such as encapsulation through private variables and public
methods. It provides functional methods for depositing, withdrawing, and checking the
balance, along with basic input validation to ensure realistic banking
operations. The main method serves as a test bed, showcasing the usage of these methods and
their expected outcomes.
5. Problem Statement: Demonstrate multilevel inheritance using a Person → Student → Graduate
hierarchy

Aim: The aim is to demonstrate how a logical hierarchy can be built using multilevel inheritance,
allowing for code reuse and the creation of specialized classes from more general ones.

Objective: To implement a class structure where Student inherits


from Person and Graduate inherits from Student, showcasing the flow of properties from the
parent to the child in a chained manner.

Source code :

class Person
{ String
name; int
age;

// Constructor for Person


Person(String name, int age)
{
[Link] = name;
[Link] = age;
}

public void talk() {


[Link]("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
class Student extends Person {
int studentId;

// Constructor for Student, calling parent constructor with `super()`


Student(String name, int age, int studentId) {
super(name, age);
[Link] = studentId;
}

// Method specific to Student


public void enroll() {
[Link](name + " with ID " + studentId + " is enrolling in courses.");
}
// Overriding the talk() method from the Person class
@Override
public void talk() {
[Link]("As a student, my name is " + name + ", I am " + age + " years old, and my
ID is " + studentId + ".");

class Graduate extends Student {


String thesisTitle;

// Constructor for Graduate, calling parent constructor with


`super()` Graduate(String name, int age, int studentId, String
thesisTitle) {
super(name, age, studentId);
[Link] = thesisTitle;
}

// Method specific to Graduate


public void defendThesis() {
[Link](name + " is defending the thesis titled: '" + thesisTitle + "'.");
}

// Overriding the talk() method from the Student


class @Override
public void talk() {
[Link]("As a graduate, my name is " + name + ", I am " + age + " years old, and
my thesis is on " + thesisTitle + ".");
}
}
public class Main {
public static void main(String[] args) {
[Link]("--- Demonstrating Multilevel Inheritance ---");

// Create an object of the Graduate class


Graduate gradStudent = new Graduate("Alice", 25, 1001, "Object-Oriented Programming");

[Link]("\nCalling methods from the Graduate object:");

// Call the method from the Graduate


class
[Link]();

// Call the method from the Student class


(inherited) [Link]();

// Call the overridden talk() method. The Graduate version is


executed. [Link]();
}
}
Output :

Conclusion:
This example effectively demonstrates multilevel inheritance in Java. The Graduate class, being
the final child in the hierarchy, successfully inherits properties and behavior from both the
Student and Person classes.
6. Problem Statement: Create a Java application that demonstrates run-time polymorphism with
overriding and interfaces.

Aim: To illustrate run-time polymorphism in Java by leveraging method overriding


within an inheritance hierarchy and by implementing a common interface across
different classes.

Objective:
To understand how method overriding enables different behaviors for a common method
across related classes and how interfaces enforce a contract for polymorphic behavior,
allowing for flexible and extensible code.

Source code :
// Define an interface for common animal behavior
interface Animal {
void makeSound();
}

// Implement the Animal interface in a concrete class


class Dog implements Animal {
@Override
public void makeSound()
{ [Link]("Dog barks: Woof
woof!");
}

public void fetch() {


[Link]("Dog fetches the ball.");
}
}

// Implement the Animal interface in another concrete class


class Cat implements Animal {
@Override
public void makeSound() {
[Link]("Cat meows: Meow meow!");
}

public void scratch() {


[Link]("Cat scratches the furniture.");
}
}
// Demonstrate run-time polymorphism
public class PolymorphismDemo {
public static void main(String[] args) {
// Declare a reference of the interface type
Animal myAnimal;

// Assign a Dog object to the Animal reference


myAnimal = new Dog();
[Link](); // Calls Dog's makeSound() - run-time polymorphism

// Assign a Cat object to the Animal reference


myAnimal = new Cat();
[Link](); // Calls Cat's makeSound() - run-time polymorphism

// You can also use polymorphism with an array of interface types


Animal[] animals = new Animal[2];
animals[0] = new Dog();
animals[1] = new Cat();

[Link]("\nIterating through an array of animals:");


for (Animal animal : animals) {
[Link](); // Each call invokes the appropriate overridden method
}
}
}
Output :

Conclusion:
The application demonstrates runtime polymorphism because the specific method that is
executed is determined at runtime, not at compile time. Both Circle and Square objects are
referenced by the same Shape type variable (myShape), but the Java Virtual Machine (JVM)
correctly invokes the draw() method belonging to the actual object type during execution. This
behavior shows how an interface can provide a single, consistent entry point to a group of
classes that implement it, allowing for flexible and extensible code.
7. Problem Statement: Create a Java program that throws user-defined exceptions for invalid
age input.

Aim: The aim is to develop a Java program that demonstrates the concept of user-
defined exceptions. The program should validate a user's age and throw a custom
exception, InvalidAgeException, if the age is considered invalid (e.g., negative or
zero).

Objective:
Define a new exception class by extending the built-in Exception class. Implement a
method that takes an integer age as input and checks if it is a valid, positive number.
Use the throw keyword to manually create and throw an InvalidAgeException if the
input is [Link] a try-catch block to handle the custom exception gracefully and
display a custom error message to the user.

Source code :
// Custom exception for an invalid age
public class InvalidAgeException extends Exception {
// Constructor that accepts a message
public InvalidAgeException(String message) {
super(message); // Call the constructor of the parent Exception class
}
}
import [Link];

public class AgeValidator {

// Method to check the age and throw a custom exception if invalid


public static void checkAge(int age) throws InvalidAgeException {
if (age <= 0) {
// Throw the user-defined InvalidAgeException
throw new InvalidAgeException("Error: The age cannot be negative or zero.");
}
[Link]("Success: Age validated successfully. Age is " + age);
}

public static void main(String[] args)


{ Scanner scanner = new
Scanner([Link]);

try {
[Link]("Enter your age:
"); int age = [Link]();
checkAge(age);
} catch (InvalidAgeException e) {
// Catch and handle the custom exception
[Link]("Exception Caught: " + [Link]());
} catch ([Link] e) {
// Handle cases where the input is not a valid integer
[Link]("Exception Caught: Invalid input. Please enter a valid integer.");
} finally {
[Link]();
[Link]("Program finished.");
}
}
}

Output :

Conclusion:
This program successfully demonstrates how to create and use a user-defined exception in
Java. By creating a custom InvalidAgeException, the code becomes more readable and
expressive, clearly communicating the specific business rule violation (age must be positive).
This approach improves the application's robustness by separating the business logic from
the error-handling code and providing specific, user-friendly feedback when an invalid age is
entered
8. Problem Statement: 8. Create a program that handles multiple exceptions in a single block and
logs errors into a file.

Aim:
The aim is to create a Java program that demonstrates effective exception handling by catching
multiple specific exceptions within a single catch block. The program will simulate various
error scenarios, and when an exception occurs, it will log the error details to a file using a try-
with-resources statement to ensure the log file is always closed automatically.
Objective:
To implement a try-catch block that can handle different types of exceptions using
the multi-catch syntax (ExceptionType1 | ExceptionType2 | ... e) introduced in Java 7.
To create custom methods that intentionally throw different types of exceptions, such
as ArithmeticException and ArrayIndexOutOfBoundsException, to test the multi-catch
[Link] incorporate a try-with-resources statement to handle the file I/O operations
for logging, ensuring that the FileWriter resource is properly managed and closed
without
needing a finally [Link] capture the stack trace and relevant error information from the
caught exception and write it to a dedicated log file.

Source code :

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MultiExceptionLogger {

private static final String LOG_FILE = "[Link]";


private static final DateTimeFormatter formatter = [Link]("yyyy-MM-dd
HH:mm:ss");

public static void main(String[] args) {


[Link]("Program started. Attempting to generate and log exceptions.");

// Simulate different scenarios in the same try block


try {
// Scenario 1: Cause an ArrayIndexOutOfBoundsException [Link]("\
nExecuting scenario 1: Accessing an invalid array index."); int[] numbers = new
int[5];
accessArray(numbers, 10); // This will cause an exception

// The following code will not be reached if the first exception is thrown
// Scenario 2: Cause an ArithmeticException [Link]("\
nExecuting scenario 2: Attempting to divide by zero."); int result =
divide(10, 0);
[Link]("Result of division: " + result);
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
// A single catch block to handle both exceptions
logErrorToFile(e);
} catch (Exception e) {
// Catch any other unexpected exceptions
logErrorToFile(e);
}
[Link]("\nProgram finished. Check the '" + LOG_FILE + "' file for error details.");
}
public static void accessArray(int[] arr, int index) {
[Link]("Attempting to access index " + index + " of an array of size " + [Link]);
int value = arr[index];
[Link]("Value at index " + index + ": " + value);
}
public static int divide(int a, int b)
{ [Link]("Attempting to divide " + a + " by " + b);
return a / b;
}
private static void logErrorToFile(Exception e) {
try (PrintWriter writer = new PrintWriter(new FileWriter(LOG_FILE, true)))
{ [Link](" ");
[Link]("Logged at: " + [Link]().format(formatter));
[Link]("Exception Type: " + [Link]().getName());
[Link]("Message: " + [Link]());
[Link]("Stack Trace:");
[Link](writer);
[Link](" ");
[Link]("An error occurred. Details have been logged to " + LOG_FILE);
} catch (IOException ioException) {
[Link]("Failed to write to log file: " + [Link]());
}
}
}
Output :

Conclusion:
This program effectively demonstrates how to handle multiple, specific exceptions in a single,
consolidated catch block using the multi-catch feature of Java. By separating the exception
handling logic from the main application flow, the code becomes cleaner and more readable.
The use of try-with-resources for the FileWriter streamlines the logging process by
automatically managing the resource, preventing potential resource leaks. This approach ensures
that all relevant error information, including the stack trace, is persistently logged to a file,
which is critical for debugging and monitoring application health.
9. Problem Statement: Create multiple threads that print even and odd numbers using Thread and
Runnable.

Aim: The primary aim is to use the Runnable interface and Thread class in Java to
achieve synchronized output of even and odd numbers from two separate threads.

Objective:
The objective is to demonstrate inter-thread communication and synchronization in Java by
creating two threads: one for printing even numbers and one for printing odd numbers. This
process illustrates the controlled and alternating access to a shared resource (the counter) by
multiple threads, ensuring the numbers are printed in sequential order.

Flowchart:

Source code :

class Printer {
private volatile boolean isOddTurn = true;
private int count = 1;
private final int max;
private final Object lock = new Object();

public Printer(int max)


{ [Link] = max;
}
public void printOdd()
{ synchronized (lock) {
while (count <= max)
{ if (isOddTurn) {
[Link]("Odd: " + count);
count++;
isOddTurn = false;
[Link]();
} else
{ try {
[Link]();
} catch (InterruptedException e) {
[Link]().interrupt();

}
}
}
}
}
public void printEven() {
synchronized (lock) {
while (count <= max)
{ if (!isOddTurn) {
[Link]("Even: " + count);
count++;
isOddTurn = true;
[Link]();
} else
{ try {
[Link]();
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
}
}
}
}
class OddNumberRunnable implements Runnable
{ private final Printer printer;

public OddNumberRunnable(Printer printer)


{ [Link] = printer;
}

@Override
public void run() {
[Link]();
}
}
class EvenNumberRunnable implements Runnable
{ private final Printer printer;

public EvenNumberRunnable(Printer printer)


{ [Link] = printer;
}

@Override
public void run() {
[Link]();
}
}
public class ThreadEvenOdd {
public static void main(String[] args) throws InterruptedException
{ Printer sharedPrinter = new Printer(10);

Runnable oddTask = new OddNumberRunnable(sharedPrinter);


Runnable evenTask = new EvenNumberRunnable(sharedPrinter);

Thread oddThread = new Thread(oddTask, "OddThread");


Thread evenThread = new Thread(evenTask, "EvenThread");

[Link]();
[Link]();

[Link]();
[Link]();
[Link]("Printing finished.");
}
}

Output

Conclusion:
This program effectively demonstrates inter-thread communication using
the wait() and notify() methods on a shared lock object. By synchronizing access to a shared
counter variable, we were able to coordinate two separate threads to print odd and even
numbers in a guaranteed, sequential order. This approach is fundamental to designing robust
concurrent applications where shared data must be accessed and modified safely.
10. Problem Statement: Develop a chat application using Java Socket programming (basic one-to-
one).

Aim: The aim is to facilitate direct communication between two users (a client and a
server) over a network, enabling them to send and receive text messages in a simple,
command-line based interface.

Objective: The objective is to develop a basic one-to-one chat application using Java
Socket programming, demonstrating fundamental client-server communication and
real-time message exchange.

Flowchart:

Source code :

import [Link].*;
import [Link].*;

public class ChatServer {


public static void main(String[] args) {
int port = 12345; // Port number for the server
try (ServerSocket serverSocket = new ServerSocket(port))
{ [Link]("Server listening on port " + port);

Socket clientSocket = [Link]();


[Link]("Client connected: " + [Link]().getHostAddress());

BufferedReader in = new BufferedReader(new InputStreamReader([Link]())); PrintWriter


out = new PrintWriter([Link](), true); // true for auto-flush

new Thread(() -> {


try (BufferedReader consoleReader = new BufferedReader(new InputStreamReader([Link])))
{ String serverMessage;
while ((serverMessage = [Link]()) != null)
{ [Link]("Server: " + serverMessage);
}
} catch (IOException e) {
[Link]("Server sending error: " + [Link]());
}
}).start();

// Server's receiving thread String


clientMessage;
while ((clientMessage = [Link]()) != null)
{ [Link]("Client: " + clientMessage);
}

} catch (IOException e) {
[Link]("Server error: " + [Link]());
}
}
}

Output :

Conclusion: This project successfully demonstrates the implementation of a basic one-to-one


chat application using Java Socket programming. It highlights the core principles of client-
server architecture, including establishing connections, managing input/output streams for
data exchange, and handling real-time communication between two distinct programs. While
a simple command-line interface is used, the underlying socket communication forms the
foundation for more complex networked applications.
11. Problem Statement: 11. Build a JDBC program to perform CRUD operation on all student
records from a database. aim, conclusion, objective, flow diagram, output..

Aim: To develop a JDBC program in Java to perform CRUD (Create, Read,


Update, Delete) operations on student records stored in a database.

Objective: To understand how to establish a database connection using [Link]


perform basic CRUD operations using SQL queries from [Link] manage student
records dynamically using prepared statements. To demonstrate interaction between
Java applications and relational databases.

Flowchart:
Source code :

import [Link].*;
import
[Link];

public class StudentCRUD {


public static void main(String[] args)
{ Scanner sc = new
Scanner([Link]);

try {
// Load Driver
[Link]("[Link]");

// Connect to DB (Change DB name, user, password as needed)


Connection con = [Link](
"jdbc:mysql://localhost:3306/studentdb", "root", "password");

while (true) {
[Link]("\n---- Student CRUD Menu----");
[Link]("1. Insert Student");
[Link]("2. Display Students");
[Link]("3. Update Student");
[Link]("4. Delete Student");
[Link]("5. Exit");
[Link]("Enter choice: ");
int choice = [Link]();

switch (choice)
{ case 1: // Insert
[Link]("Enter Roll No: ");
int rno = [Link]();
[Link]("Enter Name: ");
String name = [Link]();

[Link]("Enter Marks: ");


int marks = [Link]();

PreparedStatement pst1 = [Link]("INSERT INTO student VALUES (?,?,?)");


[Link](1, rno);
[Link](2, name);
[Link](3, marks);
[Link]();
[Link]("Student Inserted Successfully!");
break;
case 2: // Display
Statement st = [Link]();
ResultSet rs = [Link]("SELECT * FROM student"); [Link]("\nRollNo\
tName\tMarks");
while ([Link]()) {
[Link]([Link](1) + "\t" + [Link](2) + "\t" + [Link](3));
}
break;

case 3: // Update
[Link]("Enter Roll No to Update:
"); int urno = [Link]();
[Link]("Enter New Marks: ");
int newMarks = [Link]();

PreparedStatement pst2 = [Link]("UPDATE student SET marks=?


WHERE rollno=?");
[Link](1, newMarks);
[Link](2, urno);
int updated = [Link]();
if (updated > 0)
[Link]("Record Updated Successfully!");
else
[Link]("Student Not Found!");
break;

case 4: // Delete
[Link]("Enter Roll No to Delete: ");
int drno = [Link]();

PreparedStatement pst3 = [Link]("DELETE FROM student WHERE rollno=?");


[Link](1, drno);
int deleted = [Link]();
if (deleted > 0)
[Link]("Record Deleted Successfully!");
else
[Link]("Student Not Found!");
break;

case 5:
[Link]();
[Link]();
[Link]("Exiting Program...");
[Link](0);
break;
default:
[Link]("Invalid Choice!");
}
}
} catch (Exception e) {
[Link]();
}
}
}

Output :
---- Student CRUD Menu ----
1. Insert Student
2. Display Students
3. Update Student
4. Delete Student
5. Exit
Enter choice: 1
Enter Roll No: 101
Enter Name: Raj
Enter Marks: 85
Student Inserted Successfully! ---- Student CRUD Menu ----
Enter choice: 2
RollNo Name Marks
101 Raj
85 ---- Student CRUD Menu ----
Enter choice: 3
Enter Roll No to Update: 101
Enter New Marks: 90
Record Updated Successfully! ---- Student CRUD Menu ----
Enter choice: 4
Enter Roll No to Delete: 101
Record Deleted Successfully!

Conclusion: The program successfully demonstrates CRUD operations using [Link]


shows how Java can interact with relational databases (MySQL) through SQL [Link]
enhances the understanding of database handling in real-time applications.
12. Problem Statement: 12. Build a swing application to display user details using JLabel,
JTextField, and JButton.

Aim:To write a Java program using Collections Framework that stores employee names,
removes duplicates, and displays them in sorted order.

Objective:
To use Collection classes in Java (HashSet, TreeSet, ArrayList). To understand how to
remove duplicates using Set. To display employee names in alphabetical order using sorting.

Flowchart:

Start Program

Input employee
names in list

Store in HashSet
(removes dups)

Convert to TreeSet
(sorts names)

Display sorted
names

End Program

Source code :

import [Link].*;

public class EmployeeTraining {


public static void main(String[] args) {
// Step 1: Create a list of employees (with duplicates)
List<String> employees = [Link](
"Rahul", "Sneha", "Amit", "Rahul", "Priya", "Sneha", "Kiran"
);

// Step 2: Remove duplicates using HashSet


Set<String> uniqueEmployees = new HashSet<>(employees);

// Step 3: Sort names alphabetically using TreeSet


Set<String> sortedEmployees = new TreeSet<>(uniqueEmployees);
// Step 4: Display result

[Link]("Employees who attended training (unique & sorted):");


for (String name : sortedEmployees) {
[Link](name);
}
}
}

Output :

Conclusion:
HashSet was used to remove duplicate employee names.
TreeSet was used to store and display names in alphabetical order.
This demonstrates the power of the Java Collections Framework in handling real-world
problems like

You might also like