0% found this document useful (0 votes)
2 views

Java File

The document outlines the Advanced Java Programming Lab course at Maharaja Agrasen Institute of Technology, detailing the vision and mission of the Computer Science & Engineering Department. It includes lab assessment rubrics, a lab index with various programming tasks, and specific aims and code examples for each program related to Java programming concepts such as multithreading, socket programming, and exception handling. Additionally, it provides installation instructions for Eclipse IDE and Tomcat server configuration.

Uploaded by

Piyush Mittal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java File

The document outlines the Advanced Java Programming Lab course at Maharaja Agrasen Institute of Technology, detailing the vision and mission of the Computer Science & Engineering Department. It includes lab assessment rubrics, a lab index with various programming tasks, and specific aims and code examples for each program related to Java programming concepts such as multithreading, socket programming, and exception handling. Additionally, it provides installation instructions for Eclipse IDE and Tomcat server configuration.

Uploaded by

Piyush Mittal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

ADVANCED JAVA PROGRAMMING LAB

(CIE-306P)

Faculty Name: Student Name: PIYUSH MITTAL

Ms. Zameer Fatima Roll No: 35396402722

(ASSISTANT PROFESSOR) Semester: 6


Group: 6AIML3C

Maharaja Agrasen Institute of Technology, PSP Area,

Sector – 22, Rohini, New Delhi -110085


MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY
COMPUTER SCIENCE & ENGINEERING DEPARTMENT

VISION
"To attain global excellence through education, innovation, research, and work ethics in
the field of Computer Science and engineering with the commitment to serve humanity."

MISSION
M1: To lead in the advancement of computer science and engineering through
internationally recognized research and education.
M2 To prepare students for full and ethical participation in a diverse society and
encourage lifelong learning.
M3 To foster development of problem solving and communication skills as an integral
component of the profession.
M4 To impart knowledge, skills and cultivate an environment supporting incubation,
product development, technology transfer, capacity building and entrepreneurship in the
field of computer science and engineering.
M5 To encourage faculty, student’s networking with alumni, industry, institutions, and
other stakeholders for collective engagement.
Rubrics for Lab Assessment:
Rubrics 10 Marks POs and PSOs Covered

0 Marks 1 Marks 2 Marks PO PSO

R1 Is able to identify and No Partially Completely PO1, PO2 PSO1,


define the objective of PSO2
the given problem?

R2 Is proposed No Partially Completely PO1,PO2, PSO1,


design/procedure/algor PO3 PSO2
ithm solves the
problem?

R3 Has the understanding No Partially Completely PO1,PO3, PSO1,


of the PO5 PSO2
tool/programming
language to implement
the proposed solution?

R4 Are the result(s) No Partially Completely PO2,PO4, PSO2


verified using sufficient PO5
test data to support the
conclusions?

R5 Individuality of No Partially Completely PO8, PO12 PSO1,


submission? PSO3
LAB INDEX

S.No Experiment Date R1 R2 R3 R4 R5 Faculty


Signature

2M 2M 2M 2M 2M

1 Program 1: Introduction to Eclipse IDE

- 1.1: Eclipse IDE for Enterprise Java


and Web Developers

2 Program 2: Basic Java Programming and


Multithreading

- 2.1: Write a program in java to


concatenate two strings using the
command line.
- 2.2: Implement Producer-Consumer
problem using multithreading.
- 2.3: Illustrate Deadlock in
Multithreading.

3 Program 3 : Socket Programming

- 3.1: Write a java program to


demonstrate the concept of socket
programming.
- 3.2: Implement Datagram UDP
socket programming in java

4 Program 4 : Java Beans

- 4.1: Write a program to demonstrate


the use of Java Beans.
- 4.2: Write a program in java to
demonstrate encapsulation in java
beans.
Program-1.1

AIM: Introduction to Eclipse IDE for Enterprise Java Developers and Web Developers.

Eclipse IDE stands out as a popular open-source and free Integrated Development Environment (IDE),
particularly favored by both enterprise Java and web developers. Its extensive features streamline coding,
debugging, and testing processes. The IDE's extensibility, robust community support, and a vast plugin
ecosystem make it a staple in the enterprise domain.

For enterprise Java development, which often involves constructing large-scale applications using
frameworks like Spring, Hibernate, and Java EE (Jakarta EE), Eclipse IDE offers a suite of powerful
tools and seamless integrations:

1. Java Development Tools (JDT): These provide the core functionalities for Java development,
encompassing a code editor, compiler, debugger, and refactoring capabilities. JDT supports Java
SE (Standard Edition), making it suitable for developing standalone applications, libraries, and
command-line tools.

2. Enterprise Java Frameworks: Eclipse exhibits excellent integration with Java EE (Jakarta EE)
frameworks, empowering developers to build enterprise-grade applications such as web
applications, microservices, and backend systems. Furthermore, dedicated plugins for frameworks
like Spring, Hibernate, and JavaFX offer advanced features like intelligent code completion,
real-time validation, and deployment utilities.

3. Maven & Gradle Integration: Recognizing the importance of dependency management in


modern enterprise Java projects, Eclipse seamlessly supports build tools like Maven and Gradle.
Developers can directly import Maven/Gradle projects into Eclipse and manage their
dependencies effortlessly.

4. Server Integration: Eclipse facilitates straightforward integration with various application


servers (e.g., Apache Tomcat, JBoss, WebLogic), enabling developers to deploy and run
enterprise applications directly from the IDE. Managing servers, deploying applications, and
monitoring logs become convenient tasks within Eclipse.

5. Database Tools: Eclipse incorporates database management tools that allow developers to
connect to, query, and modify databases without leaving the IDE. This feature proves invaluable
for enterprise applications that rely on persistent data storage.

Beyond enterprise Java development, Eclipse IDE also provides a strong foundation for web
development, assisting developers in creating dynamic and responsive websites, single-page applications
(SPAs), and REST APIs:

1. HTML, CSS, and JavaScript Editing: Eclipse offers comprehensive support for editing core
web technologies like HTML, CSS, and JavaScript, complete with syntax highlighting, code
completion, and error detection. The IDE's capabilities extend to supporting modern front-end
frameworks such as Angular, React, and Vue.js through plugins or additional tooling.
2. Web Framework Support: Eclipse integrates seamlessly with popular Java-based web
frameworks like Spring MVC, JavaServer Faces (JSF), and JavaServer Pages (JSP). Moreover, it
provides integration with contemporary web development tools like Node.js, npm, and Yeoman,
enabling the creation of cutting-edge front-end applications.

Here are the steps to install Eclipse IDE for Enterprise Java and Web Developers:

Step 1: Download and Install JDK

● Open your web browser and search for "JDK download."


● Navigate to the oracle.com link and download the latest JDK version compatible with your
system configuration.
● Run the downloaded executable to install the JDK on your system.

Step 2: Install Eclipse IDE

● After successfully installing the JDK, proceed to download the Eclipse IDE.
● Run the downloaded Eclipse installer file.
Step 3: Choose Installation Package

● In the installer, select the option "Eclipse IDE For Enterprise Java and Web Developers."

Step 4: Initiate Installation

● On the subsequent screen, click the "Install" button.


● Accept the terms and conditions to begin the installation process, which may take some time.

Step 5: Launch Eclipse

● Once the installation is complete, click the "LAUNCH" button.


● You will be greeted with the Welcome screen of your newly installed Eclipse IDE for Enterprise
Java and Web Development.
To configure Tomcat and JDK in Eclipse IDE, follow these steps:

1. Download and Install Tomcat

● Visit the Apache Tomcat website and download the latest version of Tomcat.
● Extract the downloaded archive to a directory on your computer.

2. Set Up the JDK in Eclipse

● Ensure that the JDK is installed on your system. If not, download and install it as described in the
installation steps.
● In Eclipse, navigate to Window > Preferences.
● In the Preferences dialog, expand the Java section and select Installed JREs.
● Click the Add button, choose Standard VM, and click Next.
● In the JRE home field, browse to the directory where you installed the JDK. Click Finish.
● Ensure the newly added JDK is selected as the default JRE.

3. Configure Tomcat in Eclipse

● Open Eclipse IDE.


● Go to the Servers view (Window > Show View > Servers if it's not visible).
● In the Servers view, right-click and select New > Server.
● Choose Apache Tomcat from the list of server types and select the specific version you
downloaded.
● In the Tomcat Installation Directory field, browse to the folder where you extracted Tomcat.
● Click Next. Ensure the correct JDK (not just the JRE) is selected for the server configuration if
it's not already set.
● Click Finish to complete the Tomcat server setup in Eclipse.

4. Run Your Web Application on Tomcat

● To run a web application, right-click on your project in the Project Explorer.


● Select Run As > Run on Server.
● Eclipse will start the configured Tomcat server and deploy your application to it.

5. Check Server Configuration

● If you need to modify Tomcat's settings, you can right-click on the Tomcat server in the Servers
view and select Properties.

6. Deploy a Dynamic Web Project

● When working with dynamic web projects, ensure the "Dynamic Web Project" nature is enabled
for your project. You can create a new one via File > New > Dynamic Web Project and then
deploy it to your configured Tomcat server.
Program-1.2

Aim:- Write a program in java to concatenate two strings using command line.

Code:-

public class Main {


public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Please provide two strings as command-line
arguments.");
} else {
String str1 = args[0];
String str2 = args[1];
String result = str1 + str2;
System.out.println("Concatenated String: " + result);
}
}
}

Output:
Program-1.3

Aim:- Create a class Box that uses a parameterized constructor to initialize the dimensions
of a box. The dimensions of the Box are width, height, depth. The class should have a
method that can return the volume of the box. Create an object of the Box class and test
the functionalities.(Inheritance)

Code:-

package week1_1;

class Box {
double width;
double height;
double depth;
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;}
double volume() {
return width * height * depth;}}

class ColoredBox extends Box {


String color;
ColoredBox(double width, double height, double depth, String color) {
super(width, height, depth);
this.color = color;}
void displayColor() {
System.out.println("The color of the box is: " + color);}}
public class Main { // Changed 'main' to 'Main' to follow Java conventions
public static void main(String[] args) {
Box box1 = new Box(4.0, 5.0, 6.0);
System.out.println("Volume of the box: " + box1.volume());

ColoredBox box2 = new ColoredBox(3.0, 4.0, 5.0, "Red");


System.out.println("Volume of the colored box: " + box2.volume());
box2.displayColor();}}

Output:
Program-1.4

Aim:- Create a base class Fruit which has name ,taste and size as its attributes. A method
called eat() is created which describes the name of the fruit and its taste. Inherit the same
in 2 other class Apple and Orange and override the eat() method to represent each fruit
taste. (Method overriding)

Code:-

package week1_1;

class Fruit {
String name, taste, size;
Fruit(String n, String t, String s) { name = n; taste = t; size = s;
}
void eat() { System.out.println("The " + name + " tastes " + taste +
"."); }
}

class Apple extends Fruit {


Apple() { super("Apple", "sweet", "medium"); }
void eat() { System.out.println("The Apple is sweet and crunchy."); }
}

class Orange extends Fruit {


Orange() { super("Orange", "tangy", "medium"); }
void eat() { System.out.println("The Orange is tangy and juicy."); }
}

public class Main {


public static void main(String[] args) {
new Apple().eat();
new Orange().eat();
}
}

Output:
Program – 1.5

Aim:- Write a program to create a class named shape. It should contain 2 methods-
draw() and erase() which should print “Drawing Shape” and “Erasing Shape” respectively.
For this class we have three subclasses- Circle, Triangle and Square and each class
overrides the parent class functions- draw () and erase (). The draw() method should print
“Drawing Circle”, “Drawing Triangle”, “Drawing Square” respectively. The erase()
method should print “Erasing Circle”, “Erasing Triangle”, “Erasing Square” respectively.
Create objects of Circle, Triangle and Square in the following way and observe the
polymorphic nature of the class by calling draw() and erase() method using each object.
Shape c=new Circle(); Shape t=new Triangle(); Shape s=new Square(); (Polymorphism)

Code:-

package week1_1;
class Shape {
void draw() { System.out.println("Drawing Shape"); }
void erase() { System.out.println("Erasing Shape"); }}
class Circle extends Shape {
void draw() { System.out.println("Drawing Circle"); }
void erase() { System.out.println("Erasing Circle"); }}
class Triangle extends Shape {
void draw() { System.out.println("Drawing Triangle"); }
void erase() { System.out.println("Erasing Triangle"); }}
class Square extends Shape {
void draw() { System.out.println("Drawing Square"); }
void erase() { System.out.println("Erasing Square"); }}
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Circle(), new Triangle(), new Square() };
for (Shape shape : shapes) {
shape.draw();
shape.erase();}}}

Output :
Program – 1.6

Aim:- Write a Program to take care of Number Format Exception if user enters values
other than integer for calculating average marks of 2 students. The name of the students
and marks in 3 subjects are taken from the user while executing the program. In the same
Program write your own Exception classes to take care of Negative values and values out
of range (i.e. other than in the range of 0-100) (Exception Handling)

Code:-

package week1_1;

import java.util.Scanner;

class NegativeMarksException extends Exception {


NegativeMarksException(String message) { super(message); }}

class MarksOutOfRangeException extends Exception {


MarksOutOfRangeException(String message) { super(message); }}

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name1 = getName(sc, "first"), name2 = getName(sc, "second");
int[] marks1 = getMarks(sc, name1);
int[] marks2 = getMarks(sc, name2);

System.out.printf("Average marks of %s: %.2f%n", name1,


average(marks1));
System.out.printf("Average marks of %s: %.2f%n", name2,
average(marks2));
sc.close();}

private static String getName(Scanner sc, String order) {


System.out.print("Enter name of " + order + " student: ");
return sc.nextLine();}

private static int[] getMarks(Scanner sc, String name) {


int[] marks = new int[3];
while (true) {
try {
System.out.print("Enter marks for " + name + "
(3 subjects): ");
for (int i = 0; i < 3; i++) marks[i] =
Integer.parseInt(sc.next());
validate(marks);
break;
} catch (NumberFormatException e) {
System.out.println("Invalid input! Please enter
integers.");
sc.nextLine(); // clear buffer
} catch (Exception e) {
System.out.println(e.getMessage());}
}
return marks;}

private static void validate(int... marks) throws


NegativeMarksException, MarksOutOfRangeException {
for (int m : marks) {
if (m < 0) throw new NegativeMarksException("Marks cannot be
negative.");
if (m > 100) throw new MarksOutOfRangeException("Marks must be
between 0 and 100.");}}

private static double average(int[] marks) {


return (marks[0] + marks[1] + marks[2]) / 3.0;}}

Output:-
Program – 2.1

AIM: Write a Java Program to demonstrate the concept of multi-threading.

Code:

package project1;
class MyThread extends Thread {
private final String name;
MyThread(String name) {
this.name = name;}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + " - iteration: " + i);
try {Thread.sleep(500);}
catch (InterruptedException e) {
System.out.println(name + " interrupted");}}
System.out.println(name + " finished.");}}
public class MultiThreadingExample {
public static void main(String[] args) {
Thread t1 = new MyThread("Thread 1");
Thread t2 = new MyThread("Thread 2");
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
System.out.println("All threads completed.");
}}
Output :
Program – 2.2

AIM: Implement Producer-Consumer problem using multithreading.

Code:

package project1;
import java.util.*;
class PC {
LinkedList<Integer> list = new LinkedList<>(); int cap = 2;
public void produce() throws InterruptedException {
int val = 0;
while (true) {
synchronized (this) {
while (list.size() == cap) wait();
System.out.println("Produced-" + val);
list.add(val++); notifyAll(); Thread.sleep(1000);}}}

public void consume() throws InterruptedException {


while (true) {
synchronized (this) {
while (list.isEmpty()) wait();
System.out.println("Consumed-" + list.removeFirst());
notifyAll(); Thread.sleep(1000);}}}}

public class ProducerConsumer {


public static void main(String[] args) {
PC pc = new PC();
new Thread(() -> { try { pc.produce(); } catch (Exception e) {}
}).start();
new Thread(() -> { try { pc.consume(); } catch (Exception e) {}
}).start();}}
Output :
Program – 2.3

AIM: Illustrate Deadlock in Multithreading.

Code:

package project1;

public class Main {


private static final Object r1 = new Object();
private static final Object r2 = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
synchronized (r1) {
System.out.println("Thread 1: Locked r1");
sleep(100);
System.out.println("Thread 1: Waiting for r2");
synchronized (r2) {
System.out.println("Thread 1: Locked r2");}}});

Thread t2 = new Thread(() -> {


synchronized (r2) {
System.out.println("Thread 2: Locked r2");
sleep(100);
System.out.println("Thread 2: Waiting for r1");
synchronized (r1) {
System.out.println("Thread 2: Locked r1");}}});
t1.start();
t2.start();
}
private static void sleep(int ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) {
Thread.currentThread().interrupt(); }
}
}
Output :
Program – 3.1

AIM: Write a java program to demonstrate the concept of socket programming.

Code:

Server Program (Server.java)


import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(1234);
System.out.println("Server is listening on port 1234...");
Socket socket = serverSocket.accept();
System.out.println("New client connected!");
DataInputStream inputStream = new
DataInputStream(socket.getInputStream());
DataOutputStream outputStream = new
DataOutputStream(socket.getOutputStream());
String message = inputStream.readUTF();
System.out.println("Received from client: " + message);
outputStream.writeUTF("Hello from the server!");
inputStream.close();
outputStream.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Client program (Client.java)


import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 1234);
DataInputStream inputStream = new
DataInputStream(socket.getInputStream());
DataOutputStream outputStream = new
DataOutputStream(socket.getOutputStream());
outputStream.writeUTF("Hello from the client!");
String response = inputStream.readUTF();
System.out.println("Received from server: " + response);
inputStream.close();
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output :
Program – 3.2

AIM: Implement Datagram UDP socket programming in java

Code:

Server Program (UDPEchoServer.java)


import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(1234);
System.out.println("Server is listening on port 1234...");
Socket socket = serverSocket.accept();
System.out.println("New client connected!");
DataInputStream inputStream = new
DataInputStream(socket.getInputStream());
DataOutputStream outputStream = new
DataOutputStream(socket.getOutputStream());
String message = inputStream.readUTF();
System.out.println("Received from client: " + message);
outputStream.writeUTF("Hello from the server!");
inputStream.close();
outputStream.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Client program (UDPEchoClient.java)


import java.net.*;
public class UDPEchoClient {
public static void main(String[] args) {
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
InetAddress serverAddr = InetAddress.getByName("localhost");
int port = 9876;
String msg = "Hello from UDP client!";

byte[] sendData = msg.getBytes();


DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, serverAddr, port);
socket.send(sendPacket);
System.out.println("Sent to server: " + msg);

byte[] receiveData = new byte[1024];


DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
socket.receive(receivePacket);

String response = new String(receivePacket.getData(), 0,


receivePacket.getLength());
System.out.println("Received from server: " + response);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (socket != null && !socket.isClosed()) socket.close();
}
}
}
Output :
Program – 4.1

AIM: Write a program to demonstrate the use of Java Beans.

Code:

Person.java
import java.io.Serializable;
public class Person implements Serializable {
private String name;
private int age;
public Person() {}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public void displayPersonDetails() {
System.out.println("Name: " + getName());
System.out.println("Age: " + getAge());
}
}
JavaBeanTest.java
public class JavaBeanTest {
public static void main(String[] args) {
Person person = new Person();
person.setName("John Doe");
person.setAge(30);
person.displayPersonDetails();
}
}
Output :
Program – 4.2

AIM: Write a program in java to demonstrate encapsulation in java beans.

Code:

Student.java
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private int age;
private String grade;
public Student() {}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) {
if (age > 0) this.age = age;
else System.out.println("Age must be positive!");}
public String getGrade() { return grade; }
public void setGrade(String grade) { this.grade = grade; }
public void displayStudentDetails() {
System.out.println("Student Name: " + getName());
System.out.println("Student Age: " + getAge());
System.out.println("Student Grade: " + getGrade());}}
EncapsulationTest.java
public class EncapsulationTest {
public static void main(String[] args) {
Student student = new Student();
student.setName("Alice");
student.setAge(20);
student.setGrade("A");
student.displayStudentDetails();
student.setAge(-5); // Will print warning}}
Output :

You might also like