Advanced Java Programming (CIE-306T ) - Practical File
Submitted to: Submitted by:
Dr. Amandeep Kaur Anant jain
Dept. of Information Technology IT-FSD 06013203122
Index
S. No Practical Date Sign
Lab 1:(i) Demonstrate all different types of Inheritance :
Source code:
// Base class
class Food { void eat() {
[Link]("This food can be eaten.");
}
}
// SINGLE INHERITANCE: One class inherits from another //
class Fruit extends Food {
void taste() {
[Link]("Fruits are generally sweet or sour.");
}
}
// MULTILEVEL INHERITANCE: Inheriting from an already inherited class//
class Mango extends Fruit {
void mangoType() {
[Link]("Mangoes are tropical fruits.");
}
}
// HIERARCHICAL INHERITANCE: Multiple classes inheriting from a single parent class//
class Vegetable extends Food { void cook() {
[Link]("Vegetables can be cooked or eaten raw.");
}
}
class Meat extends Food { void proteinContent() {
[Link]("Meat is rich in protein.");
}
}
// MULTIPLE INHERITANCE (via INTERFACES): Java does not support multiple class
inheritance, but it supports multiple interfaces//
interface Spicy { void spiceLevel();
}
interface Organic { void isOrganic();
}
class Chili implements Spicy, Organic { public void spiceLevel() {
[Link]("Chili is very spicy.");
}
public void isOrganic() {
[Link]("This chili is organically grown.");
}
}
// MAIN METHOD TO DEMONSTRATE FUNCTIONALITY//
public class InheritanceDemo {
public static void main(String[] args) {
// Single Inheritance// Fruit apple = new Fruit(); [Link](); [Link]();
[Link]();
// Multilevel Inheritance//
Mango alphonso = new Mango(); [Link]();
[Link](); [Link]();
[Link]();
// Hierarchical Inheritance//
Vegetable carrot = new Vegetable(); [Link]();
[Link]();
Meat chicken = new Meat(); [Link](); [Link]();
[Link]();
// Multiple Inheritance via Interfaces// Chili redChili = new Chili(); [Link]();
[Link]();
[Link]("ANANT JAIN");
}}
Output:
Lab 1:(ii) Demonstrate User defined exception handling :
Source code:
// A custom exception class that extends Exception
class InvalidAgeException extends Exception {
// Constructor without parameters
public InvalidAgeException() {
super("Age is not valid!");
}
// Constructor with message parameter
public InvalidAgeException(String message) { super(message);
}
}
// Another custom exception for demonstration
class InsufficientBalanceException extends Exception { private double amount;
public InsufficientBalanceException(double amount) { super("Insufficient balance: Cannot
withdraw " + amount); [Link] = amount;
}
public double getAmount() { return amount;
}
}
// Main class to demonstrate the use of custom exceptions
public class UserDefinedExceptionsDemo {
// Method that throws our custom exception
public static void validateAge(int age) throws InvalidAgeException { if (age < 0) {
throw new InvalidAgeException("Age cannot be negative");
} else if (age > 120) {
throw new InvalidAgeException("Age seems too high");
}
[Link]("Age " + age + " is valid");
}
// Another method that throws our second custom exception
public static void withdrawMoney(double balance, double amount) throws
InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException(amount);
}
[Link]("Withdrawing $" + amount + " successful. Remaining balance: $" +
(balance - amount));
}
// Main method to test our custom exceptions
public static void main(String[] args) {
// Testing InvalidAgeException
[Link]("Testing Age Validation:"); try {
validateAge(25); // Valid age
validateAge(-5); //Will throw exception
} catch (InvalidAgeException e) {
[Link]("Caught exception: " + [Link]());
}
try {
validateAge(150); // Will throw exception
} catch (InvalidAgeException e) {
[Link]("Caught exception: " + [Link]());
}
// Testing InsufficientBalanceException
[Link]("\nTesting Balance Withdrawal:"); double accountBalance = 1000.0;
try {
withdrawMoney(accountBalance, 500.0); // Valid withdrawal
withdrawMoney(accountBalance, 1500.0); //Will throw exception
} catch (InsufficientBalanceException e) { [Link]("Caught exception: " +
[Link]());
[Link]("Attempted to withdraw: $" + [Link]());
}
[Link]("\nProgram completed successfully!");
[Link]("Anant jain");
}}
Output:
Lab 2 (i) : Reader - Writer Problem :
Source code:
import [Link];
class ReaderWritersProblem {
static Semaphore readLock = new Semaphore(1);
static Semaphore writeLock = new Semaphore(1);
static int readCount = 0;
static class Read implements Runnable { @Override
public void run() { try {
// Acquire read lock
[Link](); readCount++;
if (readCount == 1) { // First reader locks the write access
[Link]();
}
[Link]();
// Reading section
[Link]("Thread " + [Link]().getName() + " is READING");
[Link](1500);
[Link]("Thread " + [Link]().getName() + " has FINISHED
READING");
// Releasing read lock
[Link](); readCount--;
if (readCount == 0) { // Last reader releases the write lock
[Link]();
}
[Link]();
} catch (InterruptedException e) { [Link]();
}
}
}
static class Write implements Runnable { @Override
public void run() { try {
// Acquire write lock (Exclusive Access)
[Link]();
[Link]("Thread " + [Link]().getName() + " is WRITING");
[Link](2500);
[Link]("Thread " + [Link]().getName() + " has FINISHED
WRITING");
[Link]();
} catch (InterruptedException e) { [Link]();
}
}
}
public static void main(String[] args) { Read = new Read();
Write = new Write();
Thread t1 = new Thread(read, "Reader1"); Thread t2 = new Thread(read, "Reader2");
Thread t3 = new Thread(write, "Writer1"); Thread t4 = new Thread(read, "Reader3");
// Start threads
[Link]();
[Link]();
[Link]();
[Link]();
[Link]("ANANT JAIN");
}
}
Output:
Lab 2 (ii) : Producer=Consumer problem :
Source code:
import [Link];
public class ProducerConsumer { public static void main(String[] args) {
Buffer = new Buffer(5); // Create a buffer with a size of 5
Thread producerThread = new Thread(new Producer(buffer)); Thread consumerThread =
new Thread(new Consumer(buffer));
[Link](); [Link]();
[Link]("Anant jain");
}
}
class Buffer {
private LinkedList<Integer> items; private int capacity;
public Buffer(int capacity) { [Link] = new LinkedList<>(); [Link] = capacity;
}
public void produce(int item) throws InterruptedException { synchronized (this) {
while ([Link]() == capacity) { wait(); // Wait if the buffer is full
}
[Link](item); [Link]("Produced: " + item);
notify(); // Notify consumers that an item is available
}
}
public int consume() throws InterruptedException { synchronized (this) {
while ([Link]()) {
wait(); // Wait if the buffer is empty
}
int item = [Link](); [Link]("Consumed: " + item);
notify(); // Notify producers that there's space in the buffer
return item;
}
}
}
class Producer implements Runnable { private Buffer;
public Producer(Buffer buffer) { [Link] = buffer;
}
@Override public void run() {
try {
for (int i = 1; i <= 5; i++) { [Link](i);
[Link](1000); // Simulate some work
}
} catch (InterruptedException e) { [Link]().interrupt();
}
}
}
class Consumer implements Runnable {
private Buffer;
public Consumer(Buffer buffer) {
[Link] = buffer;
}
@Override public void run() {
try {
for (int i = 0; i < 5; i++) {
[Link]();
[Link](1000); // Simulate some work
}
} catch (InterruptedException e) { [Link]().interrupt();
}
}
}
Output:
Lab 2 (iii) : Dining Philosopher’s Problem :
Source code:
import [Link];
import [Link]; public class DiningPhilosophers {
static int philosophersNumber = 5;
static Philosopher philosophers[] = new Philosopher[philosophersNumber]; static Fork
forks[] = new Fork[philosophersNumber];
static class Fork {
public Semaphore mutex = new Semaphore(1); void grab() {
try {
[Link]();
}
catch (Exception e) { [Link]([Link]);
}
}
void release() { [Link]();
}
boolean isFree() {
return [Link]() > 0;
}
static class Philosopher extends Thread {
public int number; public Fork leftFork; public Fork rightFork;
Philosopher(int num, Fork left, Fork right) { number = num;
leftFork = left; rightFork = right;
}
public void run(){
[Link]("Hi! I'm philosopher #" + number);
while (true) { [Link]();
[Link]("Philosopher #" + number + " grabs left fork."); [Link]();
[Link]("Philosopher #" + number + " grabs right fork."); eat();
[Link]();
[Link]("Philosopher #" + number + " releases left fork."); [Link]();
[Link]("Philosopher #" + number + " releases right fork.");
}
}
void eat() { try {
int sleepTime = [Link]().nextInt(0, 1000);
[Link]("Philosopher #" + " eats for " + sleepTime); [Link](sleepTime);
}
catch (Exception e) { [Link]([Link]);
}
}
public static void main(String argv[]) { [Link]("Dining philosophers problem.");
for (int i = 0; i < philosophersNumber; i++) { forks[i] = new Fork();
}
for (int i = 0; i < philosophersNumber; i++) {
philosophers[i] = new Philosopher(i, forks[i], forks[(i + 1) % philosophersNumber]);
philosophers[i].start();
while (true) { try {
// sleep 1 sec
[Link](1000);
// check for deadlock
boolean deadlock = true; for (Fork f : forks) {
if ([Link]()) { deadlock = false; break;
}
}
if (deadlock) { [Link](1000);
[Link]("Hurray! There is a deadlock!"); break;
}
}
catch (Exception e) { [Link]([Link]);
}
}
[Link]("Bye!");
[Link]("Anant jain");
[Link](0);
}
}
Output:
Lab 3 (i) : Create an applet with the use of Graphic class :
Source code:
import [Link]; import [Link]; import [Link];
/*
<applet code="[Link]" width="400" height="300">
</applet>
*/
public class SimpleGraphicsApplet extends Applet {
// Initialize the applet
public void init() {
setBackground([Link]);
}
// Paint method to draw on the applet
public void paint(Graphics g) {
// Set color and draw a rectangle
[Link]([Link]); [Link](50, 50, 100, 80);
// Draw an oval
[Link]([Link]); [Link](200, 50, 100, 80);
// Draw a line
[Link]([Link]); [Link](50, 200, 300, 200);
// Add some text
[Link]([Link]);
[Link]("Simple Graphics Applet Example", 100, 250);
[Link]("Anant jain");
}
Output:
Lab 3 (ii) : Build a customized Marque using Applet
programming :
Source code:
import [Link]; import [Link]; import [Link]; import
[Link];
import [Link]; import [Link];
/*
<applet code="[Link]" width="600" height="400">
</applet>
*/
public class MarqueeScreensaver extends Applet implements Runnable, MouseListener {
private Thread thread;
private String name = "Anant Jain";
private String enrollmentNumber = "06013203122"; private String message;
private int x_pos = 0; private int y_pos = 200;
private int direction = 1; // 1 for right, -1 for left
private boolean running = true;
private int width, height; private Font font; private int textWidth;
private Color textColor = [Link]; private long lastColorChange = 0;
public void init() {
width = getSize().width; height = getSize().height;
message = name + " - " + enrollmentNumber; setBackground([Link]);
font = new Font("Arial", [Link], 24);
// Add mouse listener to pause/resume on click
addMouseListener(this);
// Start the thread
thread = new Thread(this); [Link]();
}
public void run() { while(true) {
if(running) {
// Change position
x_pos += (2 * direction);
// Get approximate text width for bouncing calculation
textWidth = [Link]() * 15;
// Change direction if hitting the walls
if(x_pos > width || x_pos < -textWidth) {
direction *= -1;
// Also bounce vertically a bit
y_pos = 100 + (int)([Link]() * (height - 150));
// Change color after bouncing
long now = [Link]();
if (now - lastColorChange > 1000) { // Change color at most once per
textColor = new Color( (int)([Link]() * 255),
(int)([Link]() * 255),
(int)([Link]() * 255)
);
lastColorChange = now;
}
}
}
repaint(); try {
[Link](10); // Control animation speed
} catch(InterruptedException e) { [Link]();
}
}
}
public void paint(Graphics g) {
// Clear the screen
[Link]([Link]); [Link](0, 0, width, height);
// Draw the text
[Link](font); [Link](textColor);
[Link](message, x_pos, y_pos);
// Draw instructions
[Link](new Font("Arial", [Link], 12)); [Link]([Link]);
[Link]("Click to pause/resume", 10, height - 10);
}
// Mouse event handling
public void mouseClicked(MouseEvent e) { running = !running; // Toggle running state
}
public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {}
// Handle applet lifecycle
public void start() {
if (thread == null) {
thread = new Thread(this); [Link]();
}
}
public void stop() { thread = null;
}
}
Output:
Lab 4 (i) : Demonstrate Single connection using Socket
programming
Source code:
Server:
import [Link].*; import [Link].*;
public class Server {
public static void main(String[] args) { int port = 5000; // Port number
try (ServerSocket serverSocket = new ServerSocket(port)) { [Link]("Server is
running and waiting for a client...");
try (Socket socket = [Link]()) { [Link]("Client connected: " +
[Link]());
// Input and Output streams
BufferedReader input = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter output = new PrintWriter([Link](), true);
// Read message from client
String clientMessage = [Link](); [Link]("Client says: " +
clientMessage);
// Send response to client
[Link]("Hello from Server!");
} catch (IOException e) {
[Link]("Connection error: " + [Link]());
}
} catch (IOException e) {
[Link]("Could not start server: " + [Link]());
}
}}
Client :
import [Link].*; import [Link].*;
public class Client {
public static void main(String[] args) { String serverAddress = "localhost";
int port = 5000; // Must match server port
try (Socket socket = new Socket(serverAddress, port); BufferedReader input = new
BufferedReader(new
InputStreamReader([Link]()));
PrintWriter output = new PrintWriter([Link](), true)) {
// Send message to server
[Link]("Hello from Client!");
// Read response from server
String serverMessage = [Link](); [Link]("Server says: " +
serverMessage);
} catch (IOException e) {
[Link]("Client error: " + [Link]()); } } }
Output:
Lab 4 (ii) : Demonstrate Bidirectional connection using
Socket programming: Client to server & server to client
Source code:
Server:
import [Link].*;
import [Link].*;
public class Server {
public static void main(String[] args) { int port = 5000; // Port number
try (ServerSocket serverSocket = new ServerSocket(port)) { [Link]("Server is
running and waiting for a client...");
try (Socket socket = [Link]()) { [Link]("Client connected: " +
[Link]());
// Input and Output streams
BufferedReader input = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter output = new PrintWriter([Link](), true); BufferedReader
consoleInput = new BufferedReader(new
InputStreamReader([Link]));
String clientMessage, serverMessage;
// Continuous chat loop
while (true) {
// Read message from client
clientMessage = [Link]();
if (clientMessage == null || [Link]("bye"))
{
[Link]("Client disconnected."); break;
}
[Link]("Client: " + clientMessage);
// Get server response
[Link]("Server: "); serverMessage = [Link]();
[Link](serverMessage);
if ([Link]("bye")) { [Link]("Closing connection...");
break;
}}
} catch (IOException e) {
[Link]("Connection error: " + [Link]());
}
} catch (IOException e) {
[Link]("Could not start server: " + [Link]());}}}
Client:
import [Link].*;
import [Link].*;
public class Client {
public static void main(String[] args) { String serverAddress = "localhost";
int port = 5000; // Must match server port
try (Socket socket = new Socket(serverAddress, port); BufferedReader input = new
BufferedReader(new
InputStreamReader([Link]()));
PrintWriter output = new PrintWriter([Link](), true); BufferedReader
consoleInput = new BufferedReader(new
InputStreamReader([Link]))) { String clientMessage, serverMessage;
// Continuous chat loop //
while (true) {
// Get client message from console
[Link]("Client: "); clientMessage = [Link]();
[Link](clientMessage);
if ([Link]("bye")) { [Link]("Closing connection...");
break;
}
// Read server response
serverMessage = [Link]();
if (serverMessage == null || [Link]("bye")) {
[Link]("Server disconnected.");
break;
}
[Link]("Server: " + serverMessage);}
} catch (IOException e) {
[Link]("Client error: " + [Link]()); }}}
Output:
Lab 5 (i) :Creating URL object and display its properties
Source code:
import [Link];
import [Link];
public class URLDemo {
public static void main(String[] args) { try {
// Create a URL object
URL url = new
URL("[Link]
// Display URL properties
[Link]("Original URL: " + [Link]());
[Link]("Protocol: " + [Link]());
[Link]("Host: " + [Link]());
[Link]("Port: " + [Link]());
[Link]("Default Port: " + [Link]()); [Link]("Path: " +
[Link]()); [Link]("Query: " + [Link]());
[Link]("Reference/Fragment: " + [Link]()); [Link]("Authority: "
+ [Link]()); [Link]("File: " + [Link]());
[Link]("Anant jain");
} catch (MalformedURLException e) { [Link]("Invalid URL: " +
[Link]()); }}}
Output:
Lab 5 (ii) : Opening URL connection & Reading data from
URL :
Source code:
import [Link].*; import [Link].*;
public class URLReader {
public static void main(String[] args) {
String urlString = "[Link] // API endpoint
try {
// Create URL object
URL url = new URL(urlString);
// Open connection
HttpURLConnection connection = (HttpURLConnection) [Link]();
[Link]("GET"); // Using GET request
// Get the response code
int responseCode = [Link](); [Link]("Response Code: " +
responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // Success
// Read data from the URL
BufferedReader reader = new BufferedReader(new
InputStreamReader([Link]()));
String line;
StringBuilder content = new StringBuilder();
while ((line = [Link]()) != null) { [Link](line).append("\n");
}
[Link]();
// Print the JSON content received from the URL
[Link]("JSON Data from URL:\n" + content);
[Link]("Anant jain");
} else {
[Link]("Failed to fetch data. HTTP Response Code: " + responseCode);
}
// Close connection
[Link]();
} catch (MalformedURLException e) { [Link]("Invalid URL: " +
[Link]());
} catch (IOException e) {
[Link]("Error reading from URL: " + [Link]()); }}}
Output:
Lab 5 (iii) : Using HTTP URL connection for HTTP request
Source code:
import [Link].*;
import [Link].*;
public class HttpRequestExample { public static void main(String[] args) {
String urlString = "[Link] // API endpoint
try {
// Create a URL object
URL url = new URL(urlString);
// Open HTTP connection
HttpURLConnection connection = (HttpURLConnection) [Link]();
[Link]("GET"); // Set request type as GET
[Link]("User-Agent", "Mozilla/5.0"); // Set request header
// Get response code
int responseCode = [Link](); [Link]("Response Code: " +
responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // Success
// Read response
BufferedReader reader = new BufferedReader(new
InputStreamReader([Link]()));
String line;
StringBuilder response = new StringBuilder();
while ((line = [Link]()) != null) { [Link](line).append("\n");
}
[Link]();
// Print response
[Link]("Response from Server:\n" + response);
[Link]("Anant jain");
} else {
[Link]("Request failed. HTTP Response Code: " + responseCode);
}
// Close connection [Link]();
} catch (MalformedURLException e) { [Link]("Invalid URL: " +
[Link]());
} catch (IOException e) {
[Link]("Error in HTTP request: " + [Link]()); }}}
Output:
Lab 5 (iv) : Making a HTTP post request
Source code:
import [Link].*;
import [Link].*;
public class HttpPostExample {
public static void main(String[] args) {
String urlString = "[Link] // API endpoint
String jsonInputString = "{ \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1 }"; // JSON data
to send //
try {
// Create a URL object
URL url = new URL(urlString);
// Open HTTP connection
HttpURLConnection connection = (HttpURLConnection) [Link]();
[Link]("POST"); // Set request type as POST
[Link]("Content-Type", "application/json; utf-8");
// Set headers
[Link]("Accept", "application/json");
[Link](true); // Enable writing to connection
// Write JSON data to request body
try (OutputStream os = [Link]()) { byte[] input =
[Link]("utf-8"); [Link](input, 0, [Link]);
}
// Get response code
int responseCode = [Link](); [Link]("Response Code: " +
responseCode);
// Read response from server
try (BufferedReader reader = new BufferedReader(new
InputStreamReader([Link](), "utf-8"))) {
String line;
StringBuilder response = new StringBuilder();
while ((line = [Link]()) != null) { [Link](line).append("\n");
}
// Print response
[Link]("Response from Server:\n" + response);
[Link]("Anant jain");
}
// Close connection
[Link]();
} catch (MalformedURLException e) { [Link]("Invalid URL: " +
[Link]());
} catch (IOException e) {
[Link]("Error in HTTP request: " + [Link]());}}}
Output:
Lab 5 (v) : Reading a file from URL connection :
Source code:
import [Link].*;
import [Link].*;
public class URLFileReader {
public static void main(String[] args) {
String fileUrl = "[Link] // URL of a text file
try {
// Create URL object
URL url = new URL(fileUrl);
// Open connection
HttpURLConnection connection = (HttpURLConnection) [Link]();
[Link]("GET"); // Use GET request
// Get response code
int responseCode = [Link](); [Link]("Response Code: " +
responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // If response is successful
// Read file from URL
BufferedReader reader = new BufferedReader(new
InputStreamReader([Link]()));
String line;
StringBuilder fileContent = new StringBuilder();
while ((line = [Link]()) != null) { [Link](line).append("\n");
}
[Link]();
// Print file content
[Link]("File Content from URL:\n" + fileContent);
[Link]("Anant jain");
} else {
[Link]("Failed to fetch file. HTTP Response Code: " + responseCode);
}
// Close connection
[Link]();
} catch (MalformedURLException e) { [Link]("Invalid URL: " +
[Link]());
} catch (IOException e) {
[Link]("Error reading from URL: " + [Link]()); }}}
Output: