[Go to site: main page, start]

0% found this document useful (0 votes)
4 views24 pages

Java Lab Manual Rungta

The Java Programming Lab Manual for Rungta University outlines various experiments for B.Tech Computer Science students, covering topics such as console input, constructors, object counting, interfaces, access modifiers, and exception handling. Each experiment includes objectives, theoretical concepts, program code, expected outputs, and viva questions to reinforce learning. The manual serves as a comprehensive guide for practical Java programming skills in the academic year 2024-25.

Uploaded by

shayarigazak
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)
4 views24 pages

Java Lab Manual Rungta

The Java Programming Lab Manual for Rungta University outlines various experiments for B.Tech Computer Science students, covering topics such as console input, constructors, object counting, interfaces, access modifiers, and exception handling. Each experiment includes objectives, theoretical concepts, program code, expected outputs, and viva questions to reinforce learning. The manual serves as a comprehensive guide for practical Java programming skills in the academic year 2024-25.

Uploaded by

shayarigazak
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 Programming Lab Manual | Rungta University Prof.

Bhumika Dewangan

RUNGTA UNIVERSITY
Department of Computer Science & Engineering

JAVA PROGRAMMING
Laboratory Manual

Prepared by
Prof. Bhumika Dewangan
Department of Computer Science & Engineering

[Link] (Computer Science & Engineering)


Academic Year 2024-25

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

Experiment : Index

Exp Experiment Title Sign


No.
1 Employee Details using Console Input (Arrays & Objects)

2 Use of 'this' keyword – Default & Parameterized Constructors

3 Object Count and Finalization with Unique IDs

4 Shape Interface with Circle and Triangle (Polymorphism)

5 Access Modifiers (default, protected, public, private)

6 Checked and Unchecked Exceptions (Built-in & User-defined)

7 String Class Methods

8 Multithreading with Thread Synchronization using join()

9 Deadlock Between Threads and its Solution

10 File Handling – Merging [Link] and [Link] into [Link]

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

Experiment 1: Employee Details using Console Input

Aim Write a program in Java to read from console employee details of 5


employees (Name, Department, Age, Salary) and print them.

Concepts Classes, Objects, Arrays, Scanner class, Console I/O

Theory
In Java, we use classes to model real-world entities. The Scanner class ([Link]) reads
input from the console ([Link]). An array of objects can store multiple instances of a class. We
iterate using a for loop to input and display data for each employee.

Program Code
📄 [Link]

import [Link];

class Employee {
String name;
String department;
int age;
double salary;
}

public class EmployeeDetails {


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

// ---- INPUT ----


for (int i = 0; i < 5; i++) {
emp[i] = new Employee();
[Link]("\n--- Enter details for Employee " + (i + 1) + "
---");
[Link]("Name : ");
emp[i].name = [Link]();
[Link]("Department : ");
emp[i].department = [Link]();
[Link]("Age : ");
emp[i].age = [Link]();
[Link]("Salary : ");
emp[i].salary = [Link]();
[Link](); // consume newline
}

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

// ---- OUTPUT ----


[Link]("\n========== Employee Details ==========");
[Link]("%-15s %-15s %-5s %-10s%n",
"Name", "Department", "Age", "Salary");
[Link]("--------------------------------------");
for (int i = 0; i < 5; i++) {
[Link]("%-15s %-15s %-5d %-10.2f%n",
emp[i].name, emp[i].department,
emp[i].age, emp[i].salary);
}
[Link]();
}
}

Expected Output
--- Enter details for Employee 1 ---
Name : Alice
Department : IT
Age : 28
Salary : 55000
...

========== Employee Details ==========


Name Department Age Salary
----------------------------------------------
Alice IT 28 55000.00
Bob HR 32 48000.00
Charlie Finance 45 72000.00
Diana Marketing 29 51000.00
Eve IT 35 63000.00

Viva Questions
1. What is the role of Scanner class in Java?
2. How is an array of objects different from a primitive array?
3. What happens if nextInt() is not followed by nextLine()?

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

Experiment 2: Use of 'this' Keyword

Aim Demonstrate the use of 'this' keyword to call default and


parameterized constructors.

Concepts Constructors, Constructor Chaining, this() call, this reference

Theory
The 'this' keyword in Java refers to the current object. It can be used to: (a) refer to instance
variables, (b) call another constructor of the same class using this(), and (c) pass current object
as a parameter. Constructor chaining via this() must be the first statement in a constructor.

Program Code
📄 [Link]

public class ThisKeywordDemo {


int id;
String name;
double salary;

// Default Constructor
ThisKeywordDemo() {
this(101, "Unknown", 0.0); // calls parameterized constructor
[Link]("Default constructor called.");
}

// Parameterized Constructor
ThisKeywordDemo(int id, String name, double salary) {
[Link] = id; // 'this' distinguishes field from param
[Link] = name;
[Link] = salary;
[Link]("Parameterized constructor called.");
}

void display() {
[Link]("ID: " + [Link] +
" Name: " + [Link] +
" Salary: " + [Link]);
}

public static void main(String[] args) {


[Link]("--- Creating object with default constructor ---");
ThisKeywordDemo e1 = new ThisKeywordDemo();
[Link]();

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

[Link]("\n--- Creating object with parameterized constructor


---");
ThisKeywordDemo e2 = new ThisKeywordDemo(102, "Alice", 75000);
[Link]();
}
}

Expected Output
--- Creating object with default constructor ---
Parameterized constructor called.
Default constructor called.
ID: 101 Name: Unknown Salary: 0.0

--- Creating object with parameterized constructor ---


Parameterized constructor called.
ID: 102 Name: Alice Salary: 75000.0

Viva Questions
1. Why must this() be the first statement in a constructor?
2. Can we use this() and super() together in the same constructor?
3. What is constructor chaining?

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

Experiment 3: Object Count and Finalization with Unique IDs

Aim Display count of objects created and finalized, with unique IDs
assigned at creation and displayed during finalization.

Concepts Static variables, Constructors, finalize() method, Garbage Collection

Theory
A static variable is shared across all instances. It can be used as a counter for tracking object
creation. The finalize() method is called by the Garbage Collector before reclaiming an object's
memory. Each object can be given a unique ID using a static counter incremented at creation
time.

Program Code
📄 [Link]

public class ObjectCounter {


private static int createdCount = 0;
private static int finalizedCount = 0;
private int objectId;

// Constructor – assigns unique ID and increments count


ObjectCounter() {
createdCount++;
objectId = createdCount;
[Link]("Object created -> ID: " + objectId +
" | Total created: " + createdCount);
}

// Called by Garbage Collector before reclaiming memory


@Override
protected void finalize() throws Throwable {
finalizedCount++;
[Link]("Object finalized -> ID: " + objectId +
" | Total finalized: " + finalizedCount);
[Link]();
}

public static void main(String[] args) throws InterruptedException {


ObjectCounter o1 = new ObjectCounter();
ObjectCounter o2 = new ObjectCounter();
ObjectCounter o3 = new ObjectCounter();

// Make o1 and o2 eligible for GC

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

o1 = null;
o2 = null;

[Link](); // Request GC
[Link](1000); // Wait for GC to run

[Link]("\n--- Summary ---");


[Link]("Objects created : " + createdCount);
[Link]("Objects finalized: " + finalizedCount);
}
}

Expected Output
Object created -> ID: 1 | Total created: 1
Object created -> ID: 2 | Total created: 2
Object created -> ID: 3 | Total created: 3
Object finalized -> ID: 1 | Total finalized: 1
Object finalized -> ID: 2 | Total finalized: 2

--- Summary ---


Objects created : 3
Objects finalized: 2

Viva Questions
1. Is finalize() guaranteed to run? Explain.
2. Difference between static and instance variables?
3. What is garbage collection? How does [Link]() work?

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

Experiment 4: Shape Interface – Circle and Triangle

Aim Create a Shape interface with area() method. Derive Circle and
Triangle. Use Shape reference for polymorphism. Take user input.

Concepts Interfaces, Polymorphism, Abstract methods, Runtime binding, User


Input

Theory
An interface in Java is a fully abstract type – it declares methods without implementations.
Classes implementing an interface must provide the method body. A reference of interface type
can hold any implementing class object, enabling runtime polymorphism. Area of Circle = π × r²
and Area of Triangle = 0.5 × base × height.

Program Code
📄 [Link]

import [Link];

interface Shape {
double area(); // abstract method
}

class Circle implements Shape {


double radius;

Circle(double radius) {
[Link] = radius;
}

@Override
public double area() {
return [Link] * radius * radius;
}
}

class Triangle implements Shape {


double base, height;

Triangle(double base, double height) {


[Link] = base;
[Link] = height;
}

@Override

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

public double area() {


return 0.5 * base * height;
}
}

public class ShapeDemo {


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

[Link]("Enter radius of Circle : ");


double r = [Link]();

[Link]("Enter base of Triangle : ");


double b = [Link]();
[Link]("Enter height of Triangle : ");
double h = [Link]();

Shape circle = new Circle(r);


Shape triangle = new Triangle(b, h);

[Link]("%nArea of Circle = %.4f%n", [Link]());


[Link]("Area of Triangle = %.4f%n", [Link]());
[Link]();
}
}

Expected Output
Enter radius of Circle : 5
Enter base of Triangle : 8
Enter height of Triangle : 6

Area of Circle = 78.5398


Area of Triangle = 24.0000

Viva Questions
1. What is the difference between an interface and an abstract class?
2. Can an interface have a constructor? Why?
3. What is runtime polymorphism?

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

Experiment 5: Access Modifiers in Java

Aim Demonstrate effects of access modifiers (default, protected, public,


private) with/without inheritance, within and outside a package.

Concepts Access Modifiers, Inheritance, Packages, Encapsulation

Theory
Java has four access levels: private (same class only), default/package-private (same package),
protected (same package + subclasses), public (everywhere). The table below summarises
accessibility:

Modifier Same Class Same Package Subclass (diff Other Package


pkg)

private ✔ ✘ ✘ ✘

default ✔ ✔ ✘ ✘

protected ✔ ✔ ✔ ✘

public ✔ ✔ ✔ ✔

Program Code
📄 Package: mypackage → [Link] + [Link] | Package: other →
[Link]

// File 1: mypackage/[Link]
package mypackage;

public class AccessDemo {


private int pvt = 10; // private
int def = 20; // default (package-private)
protected int prot = 30; // protected
public int pub = 40; // public

public void show() {


// All accessible within same class
[Link]("Private : " + pvt);
[Link]("Default : " + def);
[Link]("Protected : " + prot);
[Link]("Public : " + pub);
}
}

// File 2: mypackage/[Link] (same package, inheritance)

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

package mypackage;

public class Child extends AccessDemo {


public void display() {
// pvt NOT accessible (private)
[Link]("Default : " + def); // OK
[Link]("Protected : " + prot); // OK
[Link]("Public : " + pub); // OK
}
}

// File 3: other/[Link] (different package, no inheritance)


package other;
import [Link];

public class OutsideAccess {


public static void main(String[] args) {
AccessDemo obj = new AccessDemo();
// Only public is accessible
[Link]("Public : " + [Link]);
// [Link], [Link], [Link] all cause compile errors
}
}

Expected Output
-- [Link]() --
Private : 10
Default : 20
Protected : 30
Public : 40

-- [Link]() (same package) --


Default : 20
Protected : 30
Public : 40

-- OutsideAccess (different package) --


Public : 40

Viva Questions
1. What is the default access modifier in Java?
2. Can a subclass in a different package access protected members?
3. Why is encapsulation important in OOP?

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

Experiment 6: Checked and Unchecked Exceptions

Aim Show inbuilt and user-defined checked and unchecked exceptions.

Concepts Exception Hierarchy, Checked vs Unchecked, throws, throw, Custom


Exceptions

Theory
Exceptions in Java are categorized as: (a) Checked Exceptions – subclasses of Exception (not
RuntimeException), must be declared or handled (e.g. IOException, SQLException). (b)
Unchecked Exceptions – subclasses of RuntimeException, need not be declared (e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException).
User-defined exceptions extend Exception (checked) or RuntimeException (unchecked).

Program Code
📄 [Link]

import [Link].*;

// ---- User-defined CHECKED exception ----


class InsufficientFundsException extends Exception {
InsufficientFundsException(String message) {
super(message);
}
}

// ---- User-defined UNCHECKED exception ----


class NegativeAgeException extends RuntimeException {
NegativeAgeException(String message) {
super(message);
}
}

public class ExceptionDemo {

// --- Checked: user-defined ---


static void withdraw(double balance, double amount)
throws InsufficientFundsException {
if (amount > balance)
throw new InsufficientFundsException(
"Balance: " + balance + " Requested: " + amount);
[Link]("Withdrawal successful. Remaining: " + (balance -
amount));
}

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

// --- Unchecked: user-defined ---


static void setAge(int age) {
if (age < 0)
throw new NegativeAgeException("Age cannot be negative: " + age);
[Link]("Age set to: " + age);
}

public static void main(String[] args) {


// 1. Inbuilt UNCHECKED: ArithmeticException
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
[Link]("[Unchecked-Inbuilt] " + [Link]());
}

// 2. Inbuilt UNCHECKED: ArrayIndexOutOfBoundsException


try {
int[] arr = new int[3];
[Link](arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("[Unchecked-Inbuilt] " + [Link]());
}

// 3. Inbuilt CHECKED: FileNotFoundException


try {
FileReader f = new FileReader("[Link]");
} catch (FileNotFoundException e) {
[Link]("[Checked-Inbuilt] " + [Link]());
}

// 4. User-defined CHECKED
try {
withdraw(5000, 7000);
} catch (InsufficientFundsException e) {
[Link]("[Checked-UserDefined] " + [Link]());
}

// 5. User-defined UNCHECKED
try {
setAge(-5);
} catch (NegativeAgeException e) {
[Link]("[Unchecked-UserDefined] " + [Link]());
}
}
}

Expected Output
[Unchecked-Inbuilt] / by zero
[Unchecked-Inbuilt] Index 5 out of bounds for length 3
[Checked-Inbuilt] [Link] (No such file or directory)

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

[Checked-UserDefined] Balance: 5000.0 Requested: 7000.0


[Unchecked-UserDefined] Age cannot be negative: -5

Viva Questions
1. What is the difference between throw and throws?
2. What class does a user-defined checked exception extend?
3. Give two examples each of checked and unchecked exceptions.

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

Experiment 7: String Class Methods

Aim Demonstrate various member methods of the String class in Java.

Concepts String class, Immutability, String pool, String methods

Theory
String is a final, immutable class in [Link] package. Strings are stored in the String Constant
Pool. Any modification creates a new String object. Key methods include: length(), charAt(),
substring(), indexOf(), toUpperCase(), toLowerCase(), trim(), replace(), equals(), contains(),
split(), compareTo(), and valueOf().

Program Code
📄 [Link]

public class StringMethodsDemo {


public static void main(String[] args) {
String s = " Hello, Java World! ";
String t = "Hello, Java World!";

[Link]("Original : '" + s + "'");


[Link]("trim() : '" + [Link]() + "'");

String str = [Link]();


[Link]("length() : " + [Link]());
[Link]("charAt(7) : " + [Link](7));
[Link]("indexOf('J') : " + [Link]('J'));
[Link]("substring(7) : " + [Link](7));
[Link]("substring(7,11): " + [Link](7, 11));
[Link]("toUpperCase() : " + [Link]());
[Link]("toLowerCase() : " + [Link]());
[Link]("replace(Java,Python): " + [Link]("Java",
"Python"));
[Link]("contains(World): " + [Link]("World"));
[Link]("startsWith(Hello): " + [Link]("Hello"));
[Link]("endsWith(!) : " + [Link]("!"));
[Link]("equals(t) : " + [Link](t));
[Link]("equalsIgnoreCase: " +
[Link]([Link]()));
[Link]("compareTo() : " + [Link](t));

// split demo
String csv = "Alice,Bob,Charlie,Diana";
String[] parts = [Link](",");

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

[Link]("split(',') : ");
for (String p : parts) [Link]("[" + p + "] ");
[Link]();

// valueOf demo
[Link]("valueOf(42) : " + [Link](42));
[Link]("concat() : " + [Link](" Rocks!"));
[Link]("isEmpty() : " + "".isEmpty());
[Link]("toCharArray() len: " + [Link]().length);
}
}

Expected Output
Original : ' Hello, Java World! '
trim() : 'Hello, Java World!'
length() : 18
charAt(7) : J
indexOf('J') : 7
substring(7) : Java World!
substring(7,11): Java
toUpperCase() : HELLO, JAVA WORLD!
toLowerCase() : hello, java world!
replace(Java,Python): Hello, Python World!
contains(World): true
startsWith(Hello): true
endsWith(!) : true
equals(t) : true
equalsIgnoreCase: true
compareTo() : 0
split(',') : [Alice] [Bob] [Charlie] [Diana]
valueOf(42) : 42
concat() : Hello, Java World! Rocks!
isEmpty() : true
toCharArray() len: 18

Viva Questions
1. Why is String immutable in Java?
2. What is the difference between == and equals() for Strings?
3. What is the String Constant Pool?

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

Experiment 8: Multithreading with join()

Aim Create two threads T1 (prints 1-10) and T2 (prints A-J). T2 starts first;
T1 starts only after T2 finishes using join().

Concepts Thread class, Runnable, start(), join(), Thread scheduling

Theory
In Java, threads are created by extending Thread class or implementing Runnable. The join()
method makes the calling thread wait until the thread on which join() is called completes. Here,
the main thread calls [Link]() before starting t1, ensuring T2 always finishes before T1 begins.

Program Code
📄 [Link]

public class ThreadJoinDemo {

// Thread T1: prints numbers 1 to 10


static class T1 extends Thread {
@Override
public void run() {
[Link]("T1 started.");
for (int i = 1; i <= 10; i++) {
[Link]("T1: " + i + " ");
try { [Link](100); }
catch (InterruptedException e) { [Link](); }
}
[Link]("\nT1 finished.");
}
}

// Thread T2: prints characters A to J


static class T2 extends Thread {
@Override
public void run() {
[Link]("T2 started.");
for (char c = 'A'; c <= 'J'; c++) {
[Link]("T2: " + c + " ");
try { [Link](100); }
catch (InterruptedException e) { [Link](); }
}
[Link]("\nT2 finished.");
}
}

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

public static void main(String[] args) throws InterruptedException {


T1 t1 = new T1();
T2 t2 = new T2();

[Link]("Main: Starting T2 first.");


[Link](); // T2 starts
[Link](); // Main (and T1) waits for T2 to finish

[Link]("Main: T2 done. Now starting T1.");


[Link](); // T1 starts only after T2 is done
[Link]();

[Link]("Main: Both threads finished.");


}
}

Expected Output
Main: Starting T2 first.
T2 started.
T2: A T2: B T2: C T2: D T2: E
T2: F T2: G T2: H T2: I T2: J
T2 finished.
Main: T2 done. Now starting T1.
T1 started.
T1: 1 T1: 2 T1: 3 T1: 4 T1: 5
T1: 6 T1: 7 T1: 8 T1: 9 T1: 10
T1 finished.
Main: Both threads finished.

Viva Questions
1. What is the difference between start() and run()?
2. What does join() do? Where is it called from?
3. What are the states of a thread in Java?

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

Experiment 9: Deadlock Between Threads and Solution

Aim Demonstrate how deadlock occurs between threads and provide a


solution.

Concepts Deadlock, synchronized, Lock ordering, Resource starvation

Theory
A DEADLOCK occurs when two or more threads are blocked forever, each waiting for a resource
held by the other. Deadlock requires four conditions: Mutual Exclusion, Hold-and-Wait, No
Preemption, Circular Wait. Solution: Use consistent lock ordering across all threads to break
Circular Wait.

Part A – Deadlock Demonstration


📄 [Link]

public class DeadlockDemo {


static final Object LOCK_A = new Object();
static final Object LOCK_B = new Object();

static class Thread1 extends Thread {


public void run() {
synchronized (LOCK_A) {
[Link]("Thread1: Holding LOCK_A, waiting for
LOCK_B...");
try { [Link](100); } catch (InterruptedException e) {}
synchronized (LOCK_B) { // <-- waits forever
[Link]("Thread1: Acquired both locks!");
}
}
}
}

static class Thread2 extends Thread {


public void run() {
synchronized (LOCK_B) {
[Link]("Thread2: Holding LOCK_B, waiting for
LOCK_A...");
try { [Link](100); } catch (InterruptedException e) {}
synchronized (LOCK_A) { // <-- waits forever
[Link]("Thread2: Acquired both locks!");
}
}
}

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

public static void main(String[] args) {


new Thread1().start();
new Thread2().start();
// Program will HANG here – deadlock!
}
}

Part A Output (Deadlock – program hangs)


Thread1: Holding LOCK_A, waiting for LOCK_B...
Thread2: Holding LOCK_B, waiting for LOCK_A...
[Program hangs – both threads wait forever]

Part B – Deadlock Solution (Consistent Lock Ordering)


📄 [Link]

public class DeadlockSolution {


static final Object LOCK_A = new Object();
static final Object LOCK_B = new Object();

// FIX: Both threads acquire locks in SAME order: A then B


static class Thread1 extends Thread {
public void run() {
synchronized (LOCK_A) { // A first
[Link]("Thread1: Holding LOCK_A...");
try { [Link](100); } catch (InterruptedException e) {}
synchronized (LOCK_B) { // then B
[Link]("Thread1: Holding LOCK_A + LOCK_B");
}
}
}
}

static class Thread2 extends Thread {


public void run() {
synchronized (LOCK_A) { // A first (same order!)
[Link]("Thread2: Holding LOCK_A...");
try { [Link](100); } catch (InterruptedException e) {}
synchronized (LOCK_B) { // then B
[Link]("Thread2: Holding LOCK_A + LOCK_B");
}
}
}
}

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

public static void main(String[] args) throws InterruptedException {


Thread t1 = new Thread1();
Thread t2 = new Thread2();
[Link](); [Link]();
[Link](); [Link]();
[Link]("Both threads completed – no deadlock!");
}
}

Part B Output (Solution)


Thread1: Holding LOCK_A...
Thread1: Holding LOCK_A + LOCK_B
Thread2: Holding LOCK_A...
Thread2: Holding LOCK_A + LOCK_B
Both threads completed – no deadlock!

Viva Questions
1. What are the four necessary conditions for a deadlock?
2. How does consistent lock ordering prevent deadlock?
3. What is livelock? How is it different from deadlock?

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

Experiment 10: File Handling – Merging Text Files

Aim Merge contents of [Link] and [Link] into [Link]; T1 content appears
first.

Concepts File I/O, BufferedReader, FileWriter, FileReader, try-with-resources

Theory
Java's [Link] package provides classes for file operations. FileReader/FileWriter handle
character-based I/O. BufferedReader wraps FileReader for efficient reading line-by-line. FileWriter
in append mode (true) adds content to an existing file. try-with-resources ensures streams are
automatically closed.

Program Code
📄 [Link] (also creates [Link] and [Link] for demonstration)

import [Link].*;

public class MergeFiles {

// Utility: write sample content to a file


static void createFile(String fileName, String content) throws IOException {
try (FileWriter fw = new FileWriter(fileName)) {
[Link](content);
}
[Link](fileName + " created.");
}

// Utility: append file source contents into destination


static void appendFile(String source, String destination) throws IOException
{
try (BufferedReader br = new BufferedReader(new FileReader(source));
FileWriter fw = new FileWriter(destination, true)) { // append mode
String line;
while ((line = [Link]()) != null) {
[Link](line + [Link]());
}
}
}

public static void main(String[] args) {


try {
// Step 1: Create sample source files
createFile("[Link]",

Department of CSE | Rungta University Page


Java Programming Lab Manual | Rungta University Prof. Bhumika Dewangan

"Line 1 from T1\nLine 2 from T1\nLine 3 from T1\n");


createFile("[Link]",
"Line 1 from T2\nLine 2 from T2\nLine 3 from T2\n");

// Step 2: Delete [Link] if exists to start fresh


new File("[Link]").delete();

// Step 3: Append T1 then T2 into T3


appendFile("[Link]", "[Link]");
appendFile("[Link]", "[Link]");
[Link]("Merge complete. Contents of [Link]:");

// Step 4: Display [Link]


try (BufferedReader br = new BufferedReader(new
FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null)
[Link](line);
}

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

Expected Output
[Link] created.
[Link] created.
Merge complete. Contents of [Link]:
Line 1 from T1
Line 2 from T1
Line 3 from T1
Line 1 from T2
Line 2 from T2
Line 3 from T2

Viva Questions
1. What is the difference between FileWriter and BufferedWriter?
2. What does try-with-resources do?
3. How do you open a file in append mode?

Department of CSE | Rungta University Page

You might also like