ADVANCED JAVA PROGRAMMING
LABORATORY MANUAL
MSC202P: Advanced Java Programming Lab
Teaching Hours : 04 Hours/Week
Credits: 02
Maximum Marks: 50 (Exam 35 + IA 15)
Duration of Exam: 03 Hours
_____________________________________________________________________
1. Design a simple calculator application using AWT/Swing components(JFrame,
JButton, JTextField) and handle arithmetic operations with event listeners.
Simple Java Swing Calculator
This application uses a JFrame to host a JTextField for the display and
several JButton components for input, organized via a GridLayout.
Program:
-------------
import [Link].*;
import [Link].*;
import [Link];
import [Link];
public class Calculator extends JFrame implements ActionListener {
private JTextField display;
private double firstOperand = 0;
private String operator = "";
private boolean startNewNumber = true;
public Calculator() {
setTitle("Simple Calculator");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Display field
display = new JTextField("0");
[Link](false);
[Link]([Link]);
[Link](new Font("Arial", [Link], 24));
add(display, [Link]);
// Buttons panel
JPanel panel = new JPanel();
[Link](new GridLayout(4, 4, 5, 5));
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"C", "0", "=", "+"
};
for (String text : buttons) {
JButton button = new JButton(text);
[Link](new Font("Arial", [Link], 18));
[Link](this);
[Link](button);
}
add(panel, [Link]);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String command = [Link]();
if ([Link](0) >= '0' && [Link](0) <= '9') {
if (startNewNumber) {
[Link](command);
startNewNumber = false;
} else {
[Link]([Link]() + command);
}
} else if ([Link]("C")) {
[Link]("0");
firstOperand = 0;
operator = "";
startNewNumber = true;
} else if ([Link]("=")) {
calculate([Link]([Link]()));
operator = "";
startNewNumber = true;
} else {
if (![Link]()) {
calculate([Link]([Link]()));
} else {
firstOperand = [Link]([Link]());
}
operator = command;
startNewNumber = true;
}
}
private void calculate(double secondOperand) {
switch (operator) {
case "+": firstOperand += secondOperand; break;
case "-": firstOperand -= secondOperand; break;
case "*": firstOperand *= secondOperand; break;
case "/":
if (secondOperand != 0) firstOperand /= secondOperand;
else [Link]("Error");
break;
}
if (![Link]().equals("Error")) {
[Link]([Link](firstOperand));
}
}
public static void main(String[] args) {
[Link](Calculator::new);
}
}
JFrame: Serves as the main window container.
JTextField: Displays calculation results and user input.
JButton: Represents digits and arithmetic operators.
ActionListener: The actionPerformed method handles clicks, updating
the state based on whether a number or an operator was pressed.
Application should be ready!
src/[Link] (169 lines)
[Link] (74 lines)
2. Create a student registration form using Swing components (JTextField,
JComboBox, JRadioButton, JCheckBox, JTable) and display the entered details
in a table.
Program:
------------
import [Link].*;
import [Link];
import [Link].*;
import [Link];
import [Link];
public class StudentRegistration extends JFrame {
private JTextField nameField, rollField;
private JComboBox<String> courseBox;
private JRadioButton maleBtn, femaleBtn;
private JCheckBox termsCheck;
private JTable studentTable;
private DefaultTableModel tableModel;
public StudentRegistration() {
// Frame Settings
setTitle("Student Registration Form");
setSize(700, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout(10, 10));
// Form Panel (Left Side)
JPanel formPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
[Link] = new Insets(5, 5, 5, 5);
[Link] = [Link];
// Name
[Link] = 0; [Link] = 0;
[Link](new JLabel("Name:"), gbc);
nameField = new JTextField(15);
[Link] = 1;
[Link](nameField, gbc);
// Roll Number
[Link] = 0; [Link] = 1;
[Link](new JLabel("Roll No:"), gbc);
rollField = new JTextField(15);
[Link] = 1;
[Link](rollField, gbc);
// Course (JComboBox)
[Link] = 0; [Link] = 2;
[Link](new JLabel("Course:"), gbc);
String[] courses = {"BSc CS", "MSc CS", "BCA", "MCA"};
courseBox = new JComboBox<>(courses);
[Link] = 1;
[Link](courseBox, gbc);
// Gender (JRadioButton)
[Link] = 0; [Link] = 3;
[Link](new JLabel("Gender:"), gbc);
maleBtn = new JRadioButton("Male");
femaleBtn = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
[Link](maleBtn);
[Link](femaleBtn);
JPanel genderPanel = new JPanel();
[Link](maleBtn);
[Link](femaleBtn);
[Link] = 1;
[Link](genderPanel, gbc);
// Terms (JCheckBox)
termsCheck = new JCheckBox("Accept Terms & Conditions");
[Link] = 0; [Link] = 4; [Link] = 2;
[Link](termsCheck, gbc);
// Submit Button
JButton submitBtn = new JButton("Submit");
[Link] = 0; [Link] = 5; [Link] = 2;
[Link](submitBtn, gbc);
// Table (Right Side)
String[] columns = {"Name", "Roll No", "Course", "Gender"};
tableModel = new DefaultTableModel(columns, 0);
studentTable = new JTable(tableModel);
JScrollPane scrollPane = new JScrollPane(studentTable);
// Add panels to frame
add(formPanel, [Link]);
add(scrollPane, [Link]);
// Action Listener
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if ([Link]()) {
String name = [Link]();
String roll = [Link]();
String course = (String) [Link]();
String gender = [Link]() ? "Male" :
([Link]() ? "Female" : "N/A");
if (![Link]() && ![Link]()) {
[Link](new Object[]{name, roll, course, gender});
// Clear fields
[Link]("");
[Link]("");
[Link]();
[Link](false);
} else {
[Link](null, "Please fill all fields!");
}
} else {
[Link](null, "Accept terms to
proceed.");
}
}
});
setVisible(true);
}
public static void main(String[] args) {
[Link](StudentRegistration::new);
}
}
_____________________________________________________________________
3. Write a program to demonstrate mouse and keyboard event handling
(MouseEvent, KeyEvent) with interactive output on the GUI.
Program:
------------
import [Link].*;
import [Link].*;
import [Link].*;
public class EventDemo extends JFrame implements MouseListener,
MouseMotionListener, KeyListener {
private JTextArea eventLog;
private JTextField keyInput;
private JPanel mousePanel;
private JLabel statusLabel;
public EventDemo() {
// Frame Setup
setTitle("Mouse & Keyboard Event Demo");
setSize(600, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// 1. Keyboard Input Field (Top)
keyInput = new JTextField();
[Link]([Link]("Type here for
Keyboard Events"));
[Link](this);
add(keyInput, [Link]);
// 2. Mouse Interaction Panel (Center)
mousePanel = new JPanel();
[Link]([Link]);
[Link]([Link]("Move/Click
Mouse here"));
[Link](this);
[Link](this);
add(mousePanel, [Link]);
// 3. Event Log (Bottom)
eventLog = new JTextArea(10, 40);
[Link](false);
JScrollPane scrollPane = new JScrollPane(eventLog);
[Link]([Link]("Event Log"));
add(scrollPane, [Link]);
// 4. Status Bar
statusLabel = new JLabel(" Action: None");
add(statusLabel, BorderLayout.PAGE_END);
}
private void log(String message) {
[Link](message + "\n");
[Link]([Link]().getLength());
}
// --- Keyboard Events ---
@Override
public void keyPressed(KeyEvent e) {
log("Key Pressed: " + [Link]([Link]()));
}
@Override
public void keyReleased(KeyEvent e) {
log("Key Released: " + [Link]([Link]()));
}
@Override
public void keyTyped(KeyEvent e) {
log("Key Typed: '" + [Link]() + "'");
}
// --- Mouse Click Events ---
@Override
public void mouseClicked(MouseEvent e) {
log("Mouse Clicked at (" + [Link]() + ", " + [Link]() + ") Counts: " +
[Link]());
[Link]([Link]);
}
@Override
public void mousePressed(MouseEvent e) {
log("Mouse Pressed at (" + [Link]() + ", " + [Link]() + ")");
}
@Override
public void mouseReleased(MouseEvent e) {
log("Mouse Released");
[Link]([Link]);
}
@Override
public void mouseEntered(MouseEvent e) {
[Link](" Action: Mouse entered interaction area");
}
@Override
public void mouseExited(MouseEvent e) {
[Link](" Action: Mouse exited interaction area");
}
// --- Mouse Motion Events ---
@Override
public void mouseMoved(MouseEvent e) {
[Link](" Mouse position: " + [Link]() + ", " + [Link]());
}
@Override
public void mouseDragged(MouseEvent e) {
log("Mouse Dragged to (" + [Link]() + ", " + [Link]() + ")");
}
public static void main(String[] args) {
[Link](() -> {
new EventDemo().setVisible(true);
});
}
}
4. Implement a tabbed interface (JTabbedPane) for managing multiple views
such as Profile, Courses, and Results using Swing.
Program:
------------
This code creates a professional, interactive application using JTabbedPane.
Each tab contains a unique layout to demonstrate how to manage distinct
views in a single window.
The Java Code
-------------------
import [Link].*;
import [Link].*;
public class TabbedInterfaceDemo extends JFrame {
public TabbedInterfaceDemo() {
// Frame Settings
setTitle("Student Management System");
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // Center the window
// Create the Tabbed Pane
JTabbedPane tabbedPane = new JTabbedPane();
// 1. Profile Tab
[Link]("Profile", createProfilePanel());
// 2. Courses Tab
[Link]("Courses", createCoursesPanel());
// 3. Results Tab
[Link]("Results", createResultsPanel());
// Add Tabbed Pane to Frame
add(tabbedPane);
}
// View for Student Profile
private JPanel createProfilePanel() {
JPanel panel = new JPanel(new GridLayout(4, 2, 10, 10));
[Link]([Link](20, 20, 20, 20));
[Link](new JLabel("Full Name:"));
[Link](new JTextField("John Doe"));
[Link](new JLabel("Roll Number:"));
[Link](new JTextField("MSc-IT-001"));
[Link](new JLabel("Email:"));
[Link](new JTextField("[Link]@[Link]"));
JButton updateBtn = new JButton("Update Profile");
[Link](new JLabel("")); // Empty space holder
[Link](updateBtn);
return panel;
}
// View for Available Courses
private JPanel createCoursesPanel() {
JPanel panel = new JPanel(new BorderLayout());
[Link]([Link](10, 10, 10, 10));
String[] courses = {"Advanced Java", "Cloud Computing", "Data Science",
"Cyber Security", "Mobile App Dev"};
JList<String> courseList = new JList<>(courses);
[Link](new JLabel("Select your Electives:"), [Link]);
[Link](new JScrollPane(courseList), [Link]);
[Link](new JButton("Enroll Now"), [Link]);
return panel;
}
// View for Semester Results
private JPanel createResultsPanel() {
JPanel panel = new JPanel(new BorderLayout());
String[] columns = {"Subject", "Marks", "Grade"};
Object[][] data = {
{"Java Programming", "92", "A+"},
{"Database Systems", "85", "A"},
{"Networking", "78", "B+"},
{"Algorithm Design", "88", "A"}
};
JTable resultTable = new JTable(data, columns);
[Link](new JScrollPane(resultTable), [Link]);
JLabel gpaLabel = new JLabel("Aggregate GPA: 3.85",
[Link]);
[Link](new Font("Arial", [Link], 14));
[Link](gpaLabel, [Link]);
return panel;
}
public static void main(String[] args) {
// Run UI in the Event Dispatch Thread
[Link](() -> {
new TabbedInterfaceDemo().setVisible(true);
});
}
}
How to execute this in Eclipse
1. Right-click on your src folder in Eclipse.
2. Select New > Class.
3. Name the class TabbedInterfaceDemo (exactly as written above).
4. Paste the code into the file.
5. Critically: If you see the "Module error" again, delete the module-
[Link] file from your src folder as we did before.
6. Click the Green Run Button.
What this program does:
JTabbedPane: Acts as the main container for switching between views.
Profile Tab: Uses a GridLayout to show a form with input fields.
Courses Tab: Uses a JList and BorderLayout to display a list of subjects.
Results Tab: Uses a JTable to display marks in a structured table format.
_______________________________________________________________
5. Develop a program that demonstrates multithreading by creating multiple
threads for printing odd/even numbers with proper synchronization.
Program:
------------
This program uses two threads—one for Odd numbers and one for Even
numbers. It uses the synchronized keyword with wait() and notifyAll() to
ensure the threads take turns and print the numbers in the correct sequence.
public class OddEvenThreads {
private int number = 1;
private int limit = 10;
// Method for the Odd thread
public void printOdd() {
synchronized (this) {
while (number <= limit) {
// If number is even, wait for the even thread to finish
if (number % 2 == 0) {
try {
wait();
} catch (InterruptedException e) {
[Link]();
}
} else {
[Link]("Odd Thread: " + number);
number++;
notifyAll(); // Wake up the even thread
}
}
}
}
// Method for the Even thread
public void printEven() {
synchronized (this) {
while (number <= limit) {
// If number is odd, wait for the odd thread to finish
if (number % 2 != 0) {
try {
wait();
} catch (InterruptedException e) {
[Link]();
}
} else {
[Link]("Even Thread: " + number);
number++;
notifyAll(); // Wake up the odd thread
}
}
}
}
public static void main(String[] args) {
OddEvenThreads resource = new OddEvenThreads();
// Create two threads
Thread oddThread = new Thread(() -> [Link]());
Thread evenThread = new Thread(() -> [Link]());
// Start the threads
[Link]();
[Link]();
}
}
How to execute this in Eclipse
1. Right-click on your src folder.
2. Select New > Class.
3. Name the class OddEvenThreads (exactly as written above).
4. Paste the code into the file and Save (Ctrl+S).
5. If you see an error about modules, delete the [Link] file in your
sidebar.
6. Click the Green Run Button.
How it works:
synchronized (this): This locks the object so only one thread can execute the
logic at a time.
wait(): If it's not the thread's turn (e.g., the Odd thread sees an even number),
it "sleeps" and releases the lock.
notifyAll(): After a thread prints its number, it "wakes up" the other thread so
it can check the condition again.
Sequence: This ensures the console output is perfectly ordered (1, 2, 3, 4, etc.)
even though two different threads are working.
________________________________________________________________
6. Implement a producer–consumer problem using inter-thread communication
(wait/notify).
Program:
------------
This program uses a shared buffer (a LinkedList) and two threads.
The Producer adds items to the list, and the Consumer removes them. If the
list is full, the Producer waits; if it is empty, the Consumer waits.
The Java Code
-------------------
import [Link];
public class ProducerConsumerDemo {
public static void main(String[] args) {
SharedBuffer buffer = new SharedBuffer(2); // Buffer capacity of 2
// Create Producer Thread
Thread producer = new Thread(() -> {
int value = 0;
try {
while (true) {
[Link](value++);
[Link](1000); // Produce every 1 second
}
} catch (InterruptedException e) {
[Link]();
}
});
// Create Consumer Thread
Thread consumer = new Thread(() -> {
try {
while (true) {
[Link]();
[Link](2000); // Consume every 2 seconds (slower)
}
} catch (InterruptedException e) {
[Link]();
}
});
[Link]();
[Link]();
}
}
class SharedBuffer {
private LinkedList<Integer> list = new LinkedList<>();
private int capacity;
public SharedBuffer(int capacity) {
[Link] = capacity;
}
// Producer method
public synchronized void produce(int value) throws InterruptedException {
while ([Link]() == capacity) {
[Link]("Buffer is FULL. Producer is waiting...");
wait(); // Wait for consumer to remove an item
}
[Link](value);
[Link]("Produced: " + value);
notify(); // Wake up the consumer
}
// Consumer method
public synchronized void consume() throws InterruptedException {
while ([Link]()) {
[Link]("Buffer is EMPTY. Consumer is waiting...");
wait(); // Wait for producer to add an item
}
int value = [Link]();
[Link]("Consumed: " + value);
notify(); // Wake up the producer
}
}
How to execute this in Eclipse
1. Right-click on your src folder.
2. Select New > Class.
3. Name it ProducerConsumerDemo.
4. Paste the code and Save.
5. If you see the "Module error", delete [Link] from your project
sidebar.
6. Click the Green Run Button.
Key Concepts Used:
synchronized: Ensures that only one thread (Producer or Consumer) can
access the buffer at any given time.
wait(): Forces the thread to give up the lock and sleep until another thread
calls notify().
notify(): Wakes up a thread that is waiting on the same object.
Infinite Loop: The while(true) loop keeps the process running so you can
observe the "Waiting" states in the console.
7. Write a program using Generics to create a type-safe stack/queue and
demonstrate push/pop operations.
Program:
------------
This program uses a Generic Class <T> to create a stack that can store any
data type (Integers, Strings, etc.) while ensuring type safety during compile
time.
The Java Code
-------------------
import [Link];
// Generic Stack Class
class GenericStack<T> {
private ArrayList<T> stackList = new ArrayList<>();
// Add an element to the top
public void push(T item) {
[Link](item);
[Link]("Pushed: " + item);
}
// Remove and return the top element
public T pop() {
if (isEmpty()) {
[Link]("Stack is empty!");
return null;
}
return [Link]([Link]() - 1);
}
// Check if stack is empty
public boolean isEmpty() {
return [Link]();
}
// Get the top element without removing it
public T peek() {
return [Link]([Link]() - 1);
}
}
public class GenericsDemo {
public static void main(String[] args) {
// 1. Demonstrate with Integers
[Link]("--- Integer Stack ---");
GenericStack<Integer> intStack = new GenericStack<>();
[Link](10);
[Link](20);
[Link](30);
[Link]("Popped item: " + [Link]());
[Link]("Current Top: " + [Link]());
[Link]("\n--- String Stack ---");
// 2. Demonstrate with Strings
GenericStack<String> stringStack = new GenericStack<>();
[Link]("Java");
[Link]("Generics");
[Link]("MSc-IT");
[Link]("Popped item: " + [Link]());
[Link]("Is empty? " + [Link]());
}
}
How to execute this in Eclipse
1. Right-click on your src folder.
2. Select New > Class.
3. Name the class GenericsDemo.
4. Paste the provided code.
5. Save (Ctrl+S) and click the Green Play/Run Button.
Key Features of this Program:
Type Safety: By using GenericStack<Integer>, the compiler will prevent you
from accidentally adding a String to the integer stack, preventing runtime
errors.
Code Reusability: You only wrote the logic for the Stack once, but you can use
it for any object type.
<T> Placeholder: The T stands for "Type". When you create the object
(e.g., new GenericStack<String>()), Java replaces all Ts
with String automatically.
8. Create a priority-based task scheduler using ExecutorService, Callable, and
Future classes.
Program:
------------
This program demonstrates how to schedule tasks with different priorities
using an ExecutorService. We use a PriorityBlockingQueue to ensure that tasks
with higher priority (lower numerical value) are executed before others.
The Java Code
---------------------
import [Link].*;
import [Link].*;
// 1. Define priorities
enum Priority {
HIGH(1), MEDIUM(2), LOW(3);
private final int level;
Priority(int level) { [Link] = level; }
public int getLevel() { return level; }
}
// 2. Custom Task that is both Callable and Comparable
class PriorityTask implements Callable<String>, Comparable<PriorityTask> {
private String taskLabel;
private Priority priority;
public PriorityTask(String taskLabel, Priority priority) {
[Link] = taskLabel;
[Link] = priority;
}
@Override
public String call() throws Exception {
// Simulate task execution
[Link](1000);
return "Finished " + taskLabel + " [Priority: " + priority + "]";
}
@Override
public int compareTo(PriorityTask other) {
// Lower numerical level means higher priority
return [Link]([Link](), [Link]());
}
}
public class PrioritySchedulerDemo {
public static void main(String[] args) throws InterruptedException,
ExecutionException {
// 3. Create a ThreadPool that uses a Priority Queue
// We use ThreadPoolExecutor directly to provide the
PriorityBlockingQueue
ExecutorService executor = new ThreadPoolExecutor(
2, // Core threads
2, // Max threads
0L, [Link],
new PriorityBlockingQueue<Runnable>()
);
List<Future<String>> results = new ArrayList<>();
[Link]("Submitting tasks in random order...");
// 4. Submit tasks with different priorities
[Link]([Link](new PriorityTask("Database Backup",
[Link])));
[Link]([Link](new PriorityTask("Email Notification",
[Link])));
[Link]([Link](new PriorityTask("Security Patch",
[Link])));
[Link]([Link](new PriorityTask("User Login",
[Link])));
// 5. Retrieve and print results using Future
for (Future<String> future : results) {
// .get() waits for the task to finish and returns the result
[Link]("Result: " + [Link]());
}
// Shut down the executor
[Link]();
}
}
How to execute this in Eclipse
1. Right-click on your src folder.
2. Select New > Class.
3. Name it PrioritySchedulerDemo.
4. Paste the code and Save.
5. Click the Green Run Button.
Key Concepts Explained:
Callable<String>: Unlike Runnable, a Callable can return a value (in this case, a
String) and throw exceptions.
Future<String>: This is a placeholder for the result. Since tasks run in the
background, [Link]() is used to wait for and "grab" the result once it's
ready.
PriorityBlockingQueue: This is the "brain" of the scheduler. It sorts tasks based
on their compareTo logic so the execution order follows priority instead of
submission time.
ThreadPoolExecutor: By default, [Link] uses a
standard FIFO (First-In-First-Out) queue. We manually created
a ThreadPoolExecutor so we could plug in our priority queue.
9. Write a program to perform file copy operation using byte and character
streams with buffered I/O.
Program:
------------
This program demonstrates two ways to copy files: Byte Streams (best for
images/videos/all files) and Character Streams (best for text files). Both
utilize Buffered I/O to make the process much faster.
The Java Code
-------------------
import [Link].*;
public class FileCopyDemo {
public static void main(String[] args) {
String sourceFile = "[Link]";
String byteCopyDest = "copy_byte.txt";
String charCopyDest = "copy_char.txt";
// Create a dummy file first to copy
createSampleFile(sourceFile);
// 1. Copy using Byte Streams (BufferedInputStream/OutputStream)
copyByByteStream(sourceFile, byteCopyDest);
// 2. Copy using Character Streams (BufferedReader/Writer)
copyByCharacterStream(sourceFile, charCopyDest);
[Link]("Processing Complete.");
}
// METHOD 1: Using Byte Streams (Handles any file type)
public static void copyByByteStream(String src, String dest) {
try (BufferedInputStream bis = new BufferedInputStream(new
FileInputStream(src));
BufferedOutputStream bos = new BufferedOutputStream(new
FileOutputStream(dest))) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = [Link](buffer)) != -1) {
[Link](buffer, 0, bytesRead);
}
[Link]("Success: File copied using Byte Streams.");
} catch (IOException e) {
[Link]("Byte Stream Error: " + [Link]());
}
}
// METHOD 2: Using Character Streams (Best for Text files)
public static void copyByCharacterStream(String src, String dest) {
try (BufferedReader reader = new BufferedReader(new FileReader(src));
BufferedWriter writer = new BufferedWriter(new FileWriter(dest))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
[Link](); // Maintain line breaks
}
[Link]("Success: File copied using Character Streams.");
} catch (IOException e) {
[Link]("Character Stream Error: " + [Link]());
}
}
// Helper method to create a source file for testing
private static void createSampleFile(String fileName) {
try (FileWriter fw = new FileWriter(fileName)) {
[Link]("Java File I/O Lab\nThis is a test file for copying.");
} catch (IOException e) {
[Link]();
}
}
}
How to execute this in Eclipse
1. Right-click on your src folder.
2. Select New > Class.
3. Name it FileCopyDemo.
4. Paste the code and Save.
5. Click the Green Run Button.
Key Concepts Explained:
Byte Streams (BufferedInputStream): Reads raw data byte-by-byte. It is
universal and can copy anything from a .jpg to a .exe.
Character Streams (BufferedReader): Reads data as 16-bit characters. It
understands text encoding and is efficient for text manipulation.
Buffered I/O: Instead of hitting the hard drive for every single byte or
character, buffering loads a large chunk (a "buffer") into memory at once,
which makes the program significantly faster.
Try-with-resources: The try ( ... ) syntax ensures that the files are automatically
closed even if an error occurs, preventing memory leaks.
10. Demonstrate serialization and deserialization of Employee objects (with
name, id, salary) to a file.
Program:
------------
This program demonstrates how to save the state of a Java object to a file
(Serialization) and how to reconstruct that object from the file later
(Deserialization).
The Java Code
-------------------
import [Link].*;
// 1. The class must implement Serializable to be saved to a file
class Employee implements Serializable {
private static final long serialVersionUID = 1L; // Recommended for version
control
private String name;
private int id;
private double salary;
public Employee(String name, int id, double salary) {
[Link] = name;
[Link] = id;
[Link] = salary;
}
@Override
public String toString() {
return "Employee [ID=" + id + ", Name=" + name + ", Salary=$" + salary +
"]";
}
}
public class SerializationDemo {
public static void main(String[] args) {
String filename = "[Link]";
Employee emp1 = new Employee("Alice Smith", 101, 75000.0);
// --- SERIALIZATION ---
try (ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream(filename))) {
[Link](emp1);
[Link]("Object has been serialized: " + emp1);
} catch (IOException e) {
[Link]("Serialization Error: " + [Link]());
}
// --- DESERIALIZATION ---
try (ObjectInputStream in = new ObjectInputStream(new
FileInputStream(filename))) {
Employee restoredEmp = (Employee) [Link]();
[Link]("Object has been deserialized: " + restoredEmp);
} catch (IOException | ClassNotFoundException e) {
[Link]("Deserialization Error: " + [Link]());
}
}
}
How to execute this in Eclipse
1. Right-click on your src folder.
2. Select New > Class.
3. Name the class SerializationDemo.
4. Paste the code and Save (Ctrl+S).
5. Click the Green Run Button.
Key Takeaways:
implements Serializable: This is a "marker interface." It tells Java that
the Employee class is allowed to be converted into a byte stream.
ObjectOutputStream: The tool used to write the actual object to the file.
ObjectInputStream: The tool used to read the byte stream and turn it back
into a Java object.
serialVersionUID: A unique ID for the class. If you change the class structure
(like adding a new field) later, this ID helps Java determine if the saved file is
still compatible with the current code.
File Extension: We used .ser, but technically you could use .txt or .dat; .ser is
the standard convention for serialized objects.
11. Build a client-server chat application using TCP sockets, where multiple
clients can send/receive messages from the server.
Program:
------------
12. Develop a JDBC application to insert, update, delete, and display records from
a student database using PreparedStatement.
Program:
------------
13. Write a program to demonstrate transaction management in JDBC with
commit and rollback operations.
Program:
------------
In a database, Transaction Management ensures that a group of operations
are treated as a single unit. Either all of them succeed (Commit), or if any one fails,
all of them are undone (Rollback).
This example simulates a Bank Transfer where money is deducted from one account
and added to another.
The Java Code
--------------------
import [Link].*;
public class JDBCTransactionDemo {
// Replace with your DB credentials/URL
static final String URL = "jdbc:mysql://localhost:3306/your_db_name";
static final String USER = "root";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
try {
// 1. Establish Connection
conn = [Link](URL, USER, PASS);
// 2. Disable Auto-Commit (This starts the transaction)
[Link](false);
// 3. Perform multiple operations
try (Statement stmt = [Link]()) {
// Operation A: Deduct money from Alice (Account 101)
[Link]("UPDATE accounts SET balance = balance - 500 WHERE
acc_id = 101");
[Link]("Step 1: 500 deducted from Alice.");
// SIMULATING AN ERROR (Uncomment the line below to test Rollback)
// int error = 10 / 0;
// Operation B: Add money to Bob (Account 102)
[Link]("UPDATE accounts SET balance = balance + 500 WHERE
acc_id = 102");
[Link]("Step 2: 500 added to Bob.");
// 4. If everything is successful, COMMIT changes
[Link]();
[Link]("Transaction Committed Successfully!");
} catch (Exception e) {
// 5. If ANY operation fails, ROLLBACK everything
[Link]("Error occurred! Rolling back changes...");
if (conn != null) {
[Link]();
}
}
} catch (SQLException e) {
[Link]();
} finally {
// 6. Restore default behavior and close connection
try {
if (conn != null) {
[Link](true);
[Link]();
}
} catch (SQLException se) {
[Link]();
}
}
}
}
How to execute this in Eclipse
1. Add Connector: Ensure you have the MySQL Connector (or your DB's JAR file)
added to your project's Build Path.
2. Setup Database: Run these SQL commands in your database first:
CREATE TABLE accounts (acc_id INT PRIMARY KEY, balance DECIMAL(10,2));
INSERT INTO accounts VALUES (101, 1000), (102, 1000);
3. Run the Java Class:
1. If you run it normally, it will commit.
2. To see Rollback in action, uncomment the line int error = 10 / 0;. Even
though Step 1 executes, none of the changes will be saved to the
database because the program crashes before the commit.
Key Methods Used:
setAutoCommit(false): By default, JDBC saves
every executeUpdate immediately. This line tells JDBC to "wait" until we say
so.
commit(): Permanently saves all changes made since setAutoCommit(false).
rollback(): Reverts the database to the state it was in before the transaction
started.
finally block: Crucial for closing connections and setting setAutoCommit back
to true for future operations.
14. Create a Servlet application that accepts student login credentials and
validates them against a database.
Program:
------------
15. Develop a JSP application for an online shopping cart using JSTL and Session
Management.
Program:
------------
Please Note:
Java programs 11, 12, 14, and 15 will be given and discussed after the completion and
execution of all the other programs according to the prescribed syllabus.