[Go to site: main page, start]

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

Advanced Java Programming Lab

The document outlines the Advanced Java Programming Lab course at Maharaja Agrasen Institute of Technology, detailing the vision and mission of the institute, along with a comprehensive index of practical experiments. Each experiment includes aims, theory, algorithms, code examples, outputs, and viva questions to assess understanding. The practicals cover various Java programming concepts such as thread synchronization, client-server applications, GUI design, JDBC, third-party libraries, and object serialization.

Uploaded by

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

Advanced Java Programming Lab

The document outlines the Advanced Java Programming Lab course at Maharaja Agrasen Institute of Technology, detailing the vision and mission of the institute, along with a comprehensive index of practical experiments. Each experiment includes aims, theory, algorithms, code examples, outputs, and viva questions to assess understanding. The practicals cover various Java programming concepts such as thread synchronization, client-server applications, GUI design, JDBC, third-party libraries, and object serialization.

Uploaded by

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

ADVANCED JAVA PROGRAMMING LAB

OAE417P

Faculty Name: Student Name: JATIN JAIN


Dr. Anshu Khurana Roll No: 20214811922
Semester: 7th
Batch: 2

Department of Artificial Intelligence Data Science


Maharaja Agrasen Institute of Technology, PSP area,
Sector-22, Rohini, New Delhi -110085

2025-2026
Rubrics Evaluation
MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY

VISION

To nurture young minds in a learning environment of high academic value and imbibe spiritual and ethical values
with technological and management competence.

MISSION

The Institute shall endeavor to incorporate the following basic missions in the teaching methodology:
Engineering Hardware – Software Symbiosis

Practical exercises in all Engineering and Management disciplines shall be carried out by Hardware equipment as
well as the related software enabling deeper understanding of basic concepts and encouraging inquisitive nature.
Life – Long Learning

The Institute strives to match technological advancements and encourage students to keep updating their
knowledge for enhancing their skills and inculcating their habit of continuous learning.
Liberalization and Globalization

The Institute endeavors to enhance technical and management skills of students so that they are intellectually
capable and competent professionals with Industrial Aptitude to face the challenges of globalization.
Diversification

The Engineering, Technology and Management disciplines have diverse fields of studies with different attributes.
The aim is to create a synergy of the above attributes by encouraging analytical thinking.
Digitization of Learning Processes

The Institute provides seamless opportunities for innovative learning in all Engineering and Management
disciplines through digitization of learning processes using analysis, synthesis, simulation, graphics, tutorials and
related tools to create a platform for multi- disciplinary approach.
Entrepreneurship

The Institute strives to develop potential Engineers and Managers by enhancing their skills and research capabilities
so that they become successfully entrepreneurs and responsible citizens.
INDEX

Experiment Date Experiment Name Marks (0-3) Total Signature


No. Mark
s (15)

R1 R2 R3 R4 R5

1. Write a java program of thread


synchronization, inter-thread
communication, and thread
pooling

2. Implement a client-server
application using Java's
networking APIs

3. Design a calculator, a simple


text editor, or a graphical
game with user interaction
and visual components.
Explore event handling,
layout managers, and UI
design principles
4. Implement functionalities like
data retrieval, insertion,
deletion, and updating records.
Explore concepts like JDBC,
SQL queries, and database
transactions.
5. Utilize third-party libraries or
frameworks in Java
programming. Choose a
popular library (e.g., Apache
Commons, Gson, Log4j) and
develop programs that
showcase its features and
functionality
6. Write a java program to
writes objects to a file in a
serialized format and then
reads and reconstructs the
objects from the file
7. Write a java program that uses
reflection to inspect and
modify the behavior of objects
based on user input or external
configuration
8. Implement generic methods to
perform operations like
sorting, searching, or filtering
on generic collections
9. Design custom annotations
and use them in a Java
program to provide additional
metadata and define behaviour
10. Write a java program to
Integrate Java with native code
by using the JNI (with native
libraries written in C/C++)
PRACTICAL – 1
AIM - Write a java program of thread synchronization, inter-thread communication, and
thread pooling.

THEORY -

ALGORITHM -
CODE

import [Link];
import [Link];

// 1. Create a task that implements Runnable


class Task implements Runnable {
private String taskName;

public Task(String name) {


[Link] = name;
}

@Override
public void run() {
[Link]("Task '" + taskName + "' is running on thread: "
+ [Link]().getName());
try {
[Link](1000); // Simulate work
} catch (InterruptedException e) {
[Link]();
}
[Link]("Task '" + taskName + "' is complete.");
}
}

public class ThreadPoolExample {


public static void main(String[] args) {
// 3. Create a pool of 2 threads
ExecutorService pool = [Link](2);

// 4. Create 5 tasks
Runnable task1 = new Task("A");
Runnable task2 = new Task("B");
Runnable task3 = new Task("C");
Runnable task4 = new Task("D");
Runnable task5 = new Task("E");

// 5. Submit tasks to the pool


[Link](task1);
[Link](task2);
[Link](task3);
[Link](task4);
[Link](task5);

// 7. Shut down the pool


[Link]();
}
}

OUTPUT
Task 'A' is running on thread: pool-1-thread-1
Task 'B' is running on thread: pool-1-thread-2
Task 'A' is complete.
Task 'C' is running on thread: pool-1-thread-1
Task 'B' is complete.
Task 'D' is running on thread: pool-1-thread-2
Task 'C' is complete.
Task 'E' is running on thread: pool-1-thread-1
Task 'D' is complete.
Task 'E' is complete.

VIVA - VOCE

1. Q: What is a thread pool?

A: A collection of pre-started, reusable threads that can execute submitted tasks.

2. Q: Why use a thread pool?

A: It's more efficient and avoids the high cost of creating and destroying new threads.

3. Q: What problem does synchronized solve?

A: It prevents data corruption (race conditions) when multiple threads access shared
data.

4. Q: How do you submit a task to an ExecutorService?

A: By calling the execute(Runnable task) method.

5. Q: What does wait() do?

A: It makes a thread pause its execution and release its lock until another thread
notifies it.
PRACTICAL – 2
AIM - Implement a client-server application using Java's networking APIs.
THEORY –

ALGORITHM –
CODE –
// [Link]
import [Link].*;
import [Link].*;

public class Server {


public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
[Link]("Server is waiting for client...");

Socket clientSocket = [Link](); // Waits for


connection
[Link]("Client connected!");

DataOutputStream out = new


DataOutputStream([Link]());
[Link]("Hello from Server!");

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

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

public class Client {


public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8080); // Connect to server

DataInputStream in = new DataInputStream([Link]());


String message = [Link]();
[Link]("Server says: " + message);

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

OUTPUT
// Terminal 1 (Run Server first):
Server is waiting for client...
Client connected!

// Terminal 2 (Run Client second):


Server says: Hello from Server!

VIVA - VOCE

1. Q: What is a socket?

A: An endpoint of a two-way communication link between two programs on the


network.
2. Q: Which class listens for connections on the server?

A: ServerSocket.

3. Q: Which class does the client use to connect?

A: Socket.

4. Q: What does "localhost" mean?

A: It's a hostname that means "this computer" (IP address [Link]).

5. Q: What does the accept() method do?

A: It blocks the program and waits until a client connects to the server.
PRACTICAL – 3
AIM - .Design a calculator, a simple text editor, or a graphical game with user interaction and
visual components. Explore event handling, layout managers, and UI design principles.

THEORY –

ALGORITHM -
CODE –
import [Link].*;
import [Link].*;
import [Link].*;

public class SimpleCalculator extends JFrame {


JTextField num1Field, num2Field;
JButton addButton;
JLabel resultLabel;

public SimpleCalculator() {
setTitle("Simple Adder");
setLayout(new FlowLayout());

num1Field = new JTextField(5);


num2Field = new JTextField(5);
addButton = new JButton("+");
resultLabel = new JLabel("Result: ?");

add(num1Field);
add(new JLabel("+"));
add(num2Field);
add(addButton);
add(resultLabel);

// 5. Add the action listener


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int num1 = [Link]([Link]());
int num2 = [Link]([Link]());
int sum = num1 + num2;
[Link]("Result: " + sum);
} catch (NumberFormatException ex) {
[Link]("Error: Invalid number");
}
}
});

// 7. Set frame properties


setSize(400, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[] args) {


new SimpleCalculator();
}
}
OUTPUT –

VIVA – VOCE –

1. Q: What is a JFrame?

A: The main window object for a GUI application.

2. Q: What object do you use to "listen" for a button click?

A: An ActionListener.

3. Q: What is a LayoutManager?

A: An object that controls the size and position of components inside a container.

4. Q: How do you get text from a text box?

A: By calling the getText() method on the JTextField object.

5. Q: Which method of ActionListener contains the code to run on a click?

A: The actionPerformed(ActionEvent e) method.


PRACTICAL – 4
AIM - Implement functionalities like data retrieval, insertion, deletion, and updating records.
Explore concepts like JDBC, SQL queries, and database transactions.

THEORY –

ALGORITHM –
CODE –
import [Link];
import [Link];
import [Link];
import [Link];

public class JdbcExample {


public static void main(String[] args) {
// 1. H2 in-memory database URL
String jdbcUrl = "jdbc:h2:mem:testdb";

try (
// 2. Get connection
Connection conn = [Link](jdbcUrl, "sa",
"");
// 3. Create statement
Statement stmt = [Link]()
) {
// 4. Create a table
[Link]("CREATE TABLE Users (id INT, name VARCHAR(50))");

// 5. Insert data
[Link]("INSERT INTO Users VALUES (1, 'Alice')");
[Link]("INSERT INTO Users VALUES (2, 'Bob')");

// 6. Select data
ResultSet rs = [Link]("SELECT * FROM Users");
[Link]("Users in database:");

// 7. & 8. Process the results


while ([Link]()) {
[Link]("ID: " + [Link]("id") + ", Name: " +
[Link]("name"));
}
} catch (Exception e) {
[Link]();
}
// 9. Connection is auto-closed by try-with-resources
}
}

OUTPUT –
Users in database:
ID: 1, Name: Alice
ID: 2, Name: Bob

VIVA – VOCE -

1. Q: What does JDBC stand for?

A: Java Database Connectivity.

2. Q: What is the first step before connecting?

A: Loading the database-specific JDBC Driver. (Note: Modern JDBCs auto-load).


3. Q: What class do you use to get a connection?

A: DriverManager.

4. Q: What object is used to run an SQL query?

A: A Statement or PreparedStatement.

5. Q: What object holds the data returned from a SELECT query?

A: A ResultSet.
PRACTICAL – 5
AIM - Utilize third-party libraries or frameworks in Java programming. Choose a popular library
(e.g., Apache Commons, Gson, Log4j) and develop programs that showcase its features and
functionality.

THEORY –

ALGORITHM –
CODE –
import [Link];

// 2. A simple POJO class


class Student {
private String name;
private int age;
private String major;

public Student(String name, int age, String major) {


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

@Override
public String toString() {
return "Name: " + name + ", Age: " + age + ", Major: " + major;
}
}

public class GsonExample {


public static void main(String[] args) {
// 3. Create a Gson object
Gson gson = new Gson();

// 4. Serialization (Java Object -> JSON)


Student student1 = new Student("Eve", 21, "Physics");
String jsonString = [Link](student1);
[Link]("Serialized JSON: " + jsonString);

// 5. Deserialization (JSON -> Java Object)


String newJson =
"{\"name\":\"David\",\"age\":22,\"major\":\"CS\"}";
Student student2 = [Link](newJson, [Link]);
[Link]("Deserialized Object: " + student2);
}
}

OUTPUT –
Serialized JSON: {"name":"Eve","age":21,"major":"Physics"}
Deserialized Object: Name: David, Age: 22, Major: CS

VIVA - VOCE

1. Q: What is a third-party library?

A: Reusable code (a .jar file) written by someone else that you add to your project.

2. Q: What is JSON?
A: A lightweight, text-based format for data exchange.

3. Q: What is Gson used for?

A: To convert Java objects to JSON strings and vice-versa.

4. Q: What is "serialization" (in this context)?

A: The process of converting a Java object into a JSON string.

5. Q: What is "deserialization"?

A: The process of creating a Java object from a JSON string.


PRACTICAL – 6
AIM - Write a java program to writes objects to a file in a serialized format and then reads and
reconstructs the objects from the file.

THEORY

ALGORITHM
CODE –
import [Link].*;

// 1. Class must implement Serializable


class Student implements Serializable {
private static final long serialVersionUID = 1L; // Version control
int id;
String name;

public Student(int id, String name) {


[Link] = id;
[Link] = name;
}

@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
}

public class SerializationExample {


public static void main(String[] args) {
Student s1 = new Student(101, "Alice");

// 2. Serialization
try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("[Link]"))) {
[Link](s1);
[Link]("Object has been serialized: " + s1);
} catch (IOException e) {
[Link]();
}

// 3. Deserialization
try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("[Link]"))) {
Student s2 = (Student) [Link](); // Read and cast
[Link]("Object has been deserialized: " + s2);
} catch (IOException | ClassNotFoundException e) {
[Link]();
}
}
}

OUTPUT
Object has been serialized: Student [id=101, name=Alice]
Object has been deserialized: Student [id=101, name=Alice]

VIVA - VOCE

1. Q: What is serialization?

A: The process of converting a Java object into a byte stream.

2. Q: What interface must a class implement to be serializable?


A: The [Link] marker interface.

3. Q: Which class is used to write an object to a file?

A: ObjectOutputStream.

4. Q: Which class is used to read an object from a file?

A: ObjectInputStream.

5. Q: What does the transient keyword do to a field?

A: It prevents that field from being serialized (saved).


PRACTICAL – 7
AIM - Write a java program that uses reflection to inspect and modify the behavior of objects
based on user input or external configuration.

THEORY –

ALGORITHM –
CODE –
import [Link];
import [Link];

class Person {
private String name = "Default Name";

private void showName() {


[Link]("My name is " + [Link]);
}
}

public class ReflectionExample {


public static void main(String[] args) {
try {
Person p = new Person();
Class<?> personClass = [Link]();

// 1. Access and modify a private field


Field nameField = [Link]("name");
[Link](true); // Break encapsulation
[Link](p, "Alice (Modified)");

// 2. Access and invoke a private method


Method showNameMethod =
[Link]("showName");
[Link](true); // Break encapsulation
[Link](p);

} catch (Exception e) {
[Link]();
}
}
}
OUTPUT –
My name is Alice (Modified)

VIVA - VOCE

1. Q: What is Reflection in Java?

A: An API to inspect and modify classes, methods, and fields at runtime.

2. Q: How do you get the Class object from an instance obj?

A: By calling [Link]().

3. Q: How can you access a private field using reflection?

A: By calling [Link](true) on the Field object.

4. Q: Which method do you use to call a method by its name?

A: The invoke() method on the Method object.


5. Q: What are two drawbacks of using reflection?

A: It is slower than direct access and breaks encapsulation (privacy).


PRACTICAL – 8
AIM - Implement generic methods to perform operations like sorting, searching, or filtering on
generic collections.

THEORY –

ALGORITHM –
CODE –
import [Link];
import [Link];

public class GenericMethodExample {

// 2. A generic method
public static <T> void printList(List<T> list) {
[Link]("List contains: [");
for (T element : list) {
[Link](element + " ");
}
[Link]("]");
}

public static void main(String[] args) {


// 5. Create two lists of different types
List<Integer> intList = [Link](1, 2, 3, 4, 5);
List<String> stringList = [Link]("Apple", "Banana",
"Cherry");

// 6. Call the generic method with an Integer list


[Link]("Calling printList with Integers:");
printList(intList);

// 7. Call the generic method with a String list


[Link]("\nCalling printList with Strings:");
printList(stringList);
}
}

OUTPUT –
Calling printList with Integers:
List contains: [1 2 3 4 5 ]

Calling printList with Strings:


List contains: [Apple Banana Cherry ]

VIVA – VOCE -

1. Q: What is the main benefit of generics?

A: They provide compile-time type safety and avoid runtime ClassCastExceptions.

2. Q: What does <T> represent in a generic method?

A: It's a "type parameter," which is a placeholder for a real type (like String).

3. Q: Where is the type parameter <T> declared in a generic method?

A: Before the method's return type (e.g., public static <T> void...).

4. Q: Can you use primitive types (like int) with generics?


A: No, you must use their corresponding wrapper classes (like Integer).

5. Q: Can one generic method work for both List<String> and List<Integer>?

A: Yes, that is its primary purpose.


PRACTICAL – 9
AIM - Design custom annotations and use them in a Java program to provide additional metadata
and define behavior.

THEORY –

ALGORITHM –
CODE –
import [Link].*;
import [Link];

// 1. & 2. Define the custom annotation


@Retention([Link])
@Target([Link])
@interface MyTest {
}

// 3. Create a class and use the annotation


class TestClass {
@MyTest
public void runTest1() {
[Link](" - Executing Test 1");
}

public void doNothing() {


[Link](" - Doing nothing");
}

@MyTest
public void runTest2() {
[Link](" - Executing Test 2");
}
}

public class AnnotationRunner {


public static void main(String[] args) throws Exception {
TestClass testObj = new TestClass();
Class<?> objClass = [Link]();

// 5. & 6. Loop through all methods


for (Method method : [Link]()) {
// 7. Check if the annotation is present
if ([Link]([Link])) {
// 8. Invoke the annotated method
[Link]("Found @MyTest on: " +
[Link]());
[Link](testObj);
}
}
}
}

OUTPUT –
Found @MyTest on: runTest1
- Executing Test 1
Found @MyTest on: runTest2
- Executing Test 2

VIVA - VOCE

1. Q: How do you define a custom annotation?


A: By using the @interface keyword.

2. Q: What does @Retention([Link]) do?

A: It makes the annotation available to be read at runtime using reflection.

3. Q: What does @Target([Link]) do?

A: It specifies that this annotation can only be placed on methods.

4. Q: What API is used to read annotations at runtime?

A: The Java Reflection API.

5. Q: Which method checks if an element has an annotation?

A: isAnnotationPresent([Link]).
PRACTICAL – 10
AIM - Write a java program to Integrate Java with native code by using the JNI (with native
libraries written in C/C++).

THEORY –

ALGORITHM –
CODE –
// 1. [Link]
public class NativeMethods {
// 1. Declare the native method
public native void greet();

// 2. Load the native library


static {
// 'natlib' maps to '[Link]' on Linux or '[Link]' on
Windows
[Link]("natlib");
}

public static void main(String[] args) {


// 7. Call the native method
new NativeMethods().greet();
}
}

// 5. NativeMethods.c (The C implementation)


#include <jni.h>
#include <stdio.h>
#include "NativeMethods.h" // The header file generated by javac -h

JNIEXPORT void JNICALL Java_NativeMethods_greet(JNIEnv *env, jobject obj) {


printf("Hello from C! The native method was called.\n");
return;
}
OUTPUT

Output (After C code is compiled and Java is run)

Hello from C! The native method was called.

VIVA – VOCE
1. Q: What does JNI stand for?
A: Java Native Interface.

2. Q: What is the main purpose of JNI?

A: To allow Java code to call (or be called by) native C/C++ code.

3. Q: What Java keyword marks a method as being implemented in native code?

A: The native keyword.

4. Q: How do you load the native library in your Java code?

A: By calling [Link]("libraryName") inside a static block.

5. Q: What command generates the C/C++ header file from your Java class?

A: javac -h . [Link].
PRACTICAL – 11
AIM - Implement functional programming concepts and solve problems related to data
manipulation, filtering, or mapping.

THEORY –

ALGORITHM –
CODE –
import [Link];
import [Link];

public class StreamExample {


public static void main(String[] args) {
// 1. Create a list
List<String> names = [Link]("Alice", "Bob", "Charlie",
"David", "Eve");

[Link]("Names with more than 4 letters, in


uppercase:");

// 2, 3, 4, 5. Create a stream pipeline


[Link]() // 2. Get stream
.filter(name -> [Link]() > 4) // 3. Intermediate:
filter
.map(name -> [Link]()) // 4. Intermediate:
transform
.forEach(name -> [Link](name)); // 5. Terminal:
consume
}
}

OUTPUT –
Names with more than 4 letters, in uppercase:
ALICE
CHARLIE
DAVID

VIVA – VOCE -

1. Q: What is a Stream in Java? A: A sequence of elements from a source that supports


functional-style operations.
2. Q: What is a "pipeline" in the Stream API? A: A chain of intermediate operations
followed by one terminal operation.
3. Q: What is an "intermediate operation"? A: A "lazy" operation that returns a new
stream (e.g., filter(), map()).
4. Q: What is a "terminal operation"? A: An "eager" operation that starts the stream and
produces a result (e.g., forEach(), collect()).
5. Q: What is the difference between filter() and map()? A: filter() removes
elements, while map() transforms them.

You might also like