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() {
System.out.println("This food can be eaten.");
}
}
// SINGLE INHERITANCE: One class inherits from another //
class Fruit extends Food {
void taste() {
System.out.println("Fruits are generally sweet or sour.");
}
}
// MULTILEVEL INHERITANCE: Inheriting from an already inherited class//
class Mango extends Fruit {
void mangoType() {
System.out.println("Mangoes are tropical fruits.");
}
}
// HIERARCHICAL INHERITANCE: Multiple classes inheriting from a single parent class//
class Vegetable extends Food { void cook() {
System.out.println("Vegetables can be cooked or eaten raw.");
}
}
class Meat extends Food { void proteinContent() {
System.out.println("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() {
System.out.println("Chili is very spicy.");
}
public void isOrganic() {
System.out.println("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(); apple.eat(); apple.taste();
System.out.println();
// Multilevel Inheritance//
Mango alphonso = new Mango(); alphonso.eat();
alphonso.taste(); alphonso.mangoType();
System.out.println();
// Hierarchical Inheritance//
Vegetable carrot = new Vegetable(); carrot.eat();
carrot.cook();
Meat chicken = new Meat(); chicken.eat(); chicken.proteinContent();
System.out.println();
// Multiple Inheritance via Interfaces// Chili redChili = new Chili(); redChili.spiceLevel();
redChili.isOrganic();
System.out.println("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); this.amount = 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");
}
System.out.println("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);
}
System.out.println("Withdrawing $" + amount + " successful. Remaining balance: $" +
(balance - amount));
}
// Main method to test our custom exceptions
public static void main(String[] args) {
// Testing InvalidAgeException
System.out.println("Testing Age Validation:"); try {
validateAge(25); // Valid age
validateAge(-5); //Will throw exception
} catch (InvalidAgeException e) {
System.out.println("Caught exception: " + e.getMessage());
}
try {
validateAge(150); // Will throw exception
} catch (InvalidAgeException e) {
System.out.println("Caught exception: " + e.getMessage());
}
// Testing InsufficientBalanceException
System.out.println("\nTesting Balance Withdrawal:"); double accountBalance = 1000.0;
try {
withdrawMoney(accountBalance, 500.0); // Valid withdrawal
withdrawMoney(accountBalance, 1500.0); //Will throw exception
} catch (InsufficientBalanceException e) { System.out.println("Caught exception: " +
e.getMessage());
System.out.println("Attempted to withdraw: $" + e.getAmount());
}
System.out.println("\nProgram completed successfully!");
System.out.println("Anant jain");
}}
Output:
Lab 2 (i) : Reader - Writer Problem :
Source code:
import java.util.concurrent.Semaphore;
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
readLock.acquire(); readCount++;
if (readCount == 1) { // First reader locks the write access
writeLock.acquire();
}
readLock.release();
// Reading section
System.out.println("Thread " + Thread.currentThread().getName() + " is READING");
Thread.sleep(1500);
System.out.println("Thread " + Thread.currentThread().getName() + " has FINISHED
READING");
// Releasing read lock
readLock.acquire(); readCount--;
if (readCount == 0) { // Last reader releases the write lock
writeLock.release();
}
readLock.release();
} catch (InterruptedException e) { e.printStackTrace();
}
}
}
static class Write implements Runnable { @Override
public void run() { try {
// Acquire write lock (Exclusive Access)
writeLock.acquire();
System.out.println("Thread " + Thread.currentThread().getName() + " is WRITING");
Thread.sleep(2500);
System.out.println("Thread " + Thread.currentThread().getName() + " has FINISHED
WRITING");
writeLock.release();
} catch (InterruptedException e) { e.printStackTrace();
}
}
}
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
t1.start();
t3.start();
t2.start();
t4.start();
System.out.println("ANANT JAIN");
}
}
Output:
Lab 2 (ii) : Producer=Consumer problem :
Source code:
import java.util.LinkedList;
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));
producerThread.start(); consumerThread.start();
System.out.println("Anant jain");
}
}
class Buffer {
private LinkedList<Integer> items; private int capacity;
public Buffer(int capacity) { this.items = new LinkedList<>(); this.capacity = capacity;
}
public void produce(int item) throws InterruptedException { synchronized (this) {
while (items.size() == capacity) { wait(); // Wait if the buffer is full
}
items.add(item); System.out.println("Produced: " + item);
notify(); // Notify consumers that an item is available
}
}
public int consume() throws InterruptedException { synchronized (this) {
while (items.isEmpty()) {
wait(); // Wait if the buffer is empty
}
int item = items.removeFirst(); System.out.println("Consumed: " + item);
notify(); // Notify producers that there's space in the buffer
return item;
}
}
}
class Producer implements Runnable { private Buffer;
public Producer(Buffer buffer) { this.buffer = buffer;
}
@Override public void run() {
try {
for (int i = 1; i <= 5; i++) { buffer.produce(i);
Thread.sleep(1000); // Simulate some work
}
} catch (InterruptedException e) { Thread.currentThread().interrupt();
}
}
}
class Consumer implements Runnable {
private Buffer;
public Consumer(Buffer buffer) {
this.buffer = buffer;
}
@Override public void run() {
try {
for (int i = 0; i < 5; i++) {
buffer.consume();
Thread.sleep(1000); // Simulate some work
}
} catch (InterruptedException e) { Thread.currentThread().interrupt();
}
}
}
Output:
Lab 2 (iii) : Dining Philosopher’s Problem :
Source code:
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadLocalRandom; 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 {
mutex.acquire();
}
catch (Exception e) { e.printStackTrace(System.out);
}
}
void release() { mutex.release();
}
boolean isFree() {
return mutex.availablePermits() > 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(){
System.out.println("Hi! I'm philosopher #" + number);
while (true) { leftFork.grab();
System.out.println("Philosopher #" + number + " grabs left fork."); rightFork.grab();
System.out.println("Philosopher #" + number + " grabs right fork."); eat();
leftFork.release();
System.out.println("Philosopher #" + number + " releases left fork."); rightFork.release();
System.out.println("Philosopher #" + number + " releases right fork.");
}
}
void eat() { try {
int sleepTime = ThreadLocalRandom.current().nextInt(0, 1000);
System.out.println("Philosopher #" + " eats for " + sleepTime); Thread.sleep(sleepTime);
}
catch (Exception e) { e.printStackTrace(System.out);
}
}
public static void main(String argv[]) { System.out.println("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
Thread.sleep(1000);
// check for deadlock
boolean deadlock = true; for (Fork f : forks) {
if (f.isFree()) { deadlock = false; break;
}
}
if (deadlock) { Thread.sleep(1000);
System.out.println("Hurray! There is a deadlock!"); break;
}
}
catch (Exception e) { e.printStackTrace(System.out);
}
}
System.out.println("Bye!");
System.out.println("Anant jain");
System.exit(0);
}
}
Output:
Lab 3 (i) : Create an applet with the use of Graphic class :
Source code:
import java.applet.Applet; import java.awt.Color; import java.awt.Graphics;
/*
<applet code="SimpleGraphicsApplet.class" width="400" height="300">
</applet>
*/
public class SimpleGraphicsApplet extends Applet {
// Initialize the applet
public void init() {
setBackground(Color.white);
}
// Paint method to draw on the applet
public void paint(Graphics g) {
// Set color and draw a rectangle
g.setColor(Color.blue); g.fillRect(50, 50, 100, 80);
// Draw an oval
g.setColor(Color.red); g.fillOval(200, 50, 100, 80);
// Draw a line
g.setColor(Color.green); g.drawLine(50, 200, 300, 200);
// Add some text
g.setColor(Color.black);
g.drawString("Simple Graphics Applet Example", 100, 250);
System.out.println("Anant jain");
}
Output:
Lab 3 (ii) : Build a customized Marque using Applet
programming :
Source code:
import java.applet.Applet; import java.awt.Color; import java.awt.Font; import
java.awt.Graphics;
import java.awt.event.MouseEvent; import java.awt.event.MouseListener;
/*
<applet code="MarqueeScreensaver.class" 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 = Color.BLUE; private long lastColorChange = 0;
public void init() {
width = getSize().width; height = getSize().height;
message = name + " - " + enrollmentNumber; setBackground(Color.BLACK);
font = new Font("Arial", Font.BOLD, 24);
// Add mouse listener to pause/resume on click
addMouseListener(this);
// Start the thread
thread = new Thread(this); thread.start();
}
public void run() { while(true) {
if(running) {
// Change position
x_pos += (2 * direction);
// Get approximate text width for bouncing calculation
textWidth = message.length() * 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)(Math.random() * (height - 150));
// Change color after bouncing
long now = System.currentTimeMillis();
if (now - lastColorChange > 1000) { // Change color at most once per
textColor = new Color( (int)(Math.random() * 255),
(int)(Math.random() * 255),
(int)(Math.random() * 255)
);
lastColorChange = now;
}
}
}
repaint(); try {
Thread.sleep(10); // Control animation speed
} catch(InterruptedException e) { e.printStackTrace();
}
}
}
public void paint(Graphics g) {
// Clear the screen
g.setColor(Color.BLACK); g.fillRect(0, 0, width, height);
// Draw the text
g.setFont(font); g.setColor(textColor);
g.drawString(message, x_pos, y_pos);
// Draw instructions
g.setFont(new Font("Arial", Font.PLAIN, 12)); g.setColor(Color.WHITE);
g.drawString("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); thread.start();
}
}
public void stop() { thread = null;
}
}
Output:
Lab 4 (i) : Demonstrate Single connection using Socket
programming
Source code:
Server:
import java.io.*; import java.net.*;
public class Server {
public static void main(String[] args) { int port = 5000; // Port number
try (ServerSocket serverSocket = new ServerSocket(port)) { System.out.println("Server is
running and waiting for a client...");
try (Socket socket = serverSocket.accept()) { System.out.println("Client connected: " +
socket.getInetAddress());
// Input and Output streams
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
// Read message from client
String clientMessage = input.readLine(); System.out.println("Client says: " +
clientMessage);
// Send response to client
output.println("Hello from Server!");
} catch (IOException e) {
System.out.println("Connection error: " + e.getMessage());
}
} catch (IOException e) {
System.out.println("Could not start server: " + e.getMessage());
}
}}
Client :
import java.io.*; import java.net.*;
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(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true)) {
// Send message to server
output.println("Hello from Client!");
// Read response from server
String serverMessage = input.readLine(); System.out.println("Server says: " +
serverMessage);
} catch (IOException e) {
System.out.println("Client error: " + e.getMessage()); } } }
Output:
Lab 4 (ii) : Demonstrate Bidirectional connection using
Socket programming: Client to server & server to client
Source code:
Server:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) { int port = 5000; // Port number
try (ServerSocket serverSocket = new ServerSocket(port)) { System.out.println("Server is
running and waiting for a client...");
try (Socket socket = serverSocket.accept()) { System.out.println("Client connected: " +
socket.getInetAddress());
// Input and Output streams
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true); BufferedReader
consoleInput = new BufferedReader(new
InputStreamReader(System.in));
String clientMessage, serverMessage;
// Continuous chat loop
while (true) {
// Read message from client
clientMessage = input.readLine();
if (clientMessage == null || clientMessage.equalsIgnoreCase("bye"))
{
System.out.println("Client disconnected."); break;
}
System.out.println("Client: " + clientMessage);
// Get server response
System.out.print("Server: "); serverMessage = consoleInput.readLine();
output.println(serverMessage);
if (serverMessage.equalsIgnoreCase("bye")) { System.out.println("Closing connection...");
break;
}}
} catch (IOException e) {
System.out.println("Connection error: " + e.getMessage());
}
} catch (IOException e) {
System.out.println("Could not start server: " + e.getMessage());}}}
Client:
import java.io.*;
import java.net.*;
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(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true); BufferedReader
consoleInput = new BufferedReader(new
InputStreamReader(System.in))) { String clientMessage, serverMessage;
// Continuous chat loop //
while (true) {
// Get client message from console
System.out.print("Client: "); clientMessage = consoleInput.readLine();
output.println(clientMessage);
if (clientMessage.equalsIgnoreCase("bye")) { System.out.println("Closing connection...");
break;
}
// Read server response
serverMessage = input.readLine();
if (serverMessage == null || serverMessage.equalsIgnoreCase("bye")) {
System.out.println("Server disconnected.");
break;
}
System.out.println("Server: " + serverMessage);}
} catch (IOException e) {
System.out.println("Client error: " + e.getMessage()); }}}
Output:
Lab 5 (i) :Creating URL object and display its properties
Source code:
import java.net.URL;
import java.net.MalformedURLException;
public class URLDemo {
public static void main(String[] args) { try {
// Create a URL object
URL url = new
URL("https://www.example.com:8080/docs/index.html?name=value#section");
// Display URL properties
System.out.println("Original URL: " + url.toString());
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("Port: " + url.getPort());
System.out.println("Default Port: " + url.getDefaultPort()); System.out.println("Path: " +
url.getPath()); System.out.println("Query: " + url.getQuery());
System.out.println("Reference/Fragment: " + url.getRef()); System.out.println("Authority: "
+ url.getAuthority()); System.out.println("File: " + url.getFile());
System.out.println("Anant jain");
} catch (MalformedURLException e) { System.out.println("Invalid URL: " +
e.getMessage()); }}}
Output:
Lab 5 (ii) : Opening URL connection & Reading data from
URL :
Source code:
import java.io.*; import java.net.*;
public class URLReader {
public static void main(String[] args) {
String urlString = "https://jsonplaceholder.typicode.com/posts/1"; // API endpoint
try {
// Create URL object
URL url = new URL(urlString);
// Open connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET"); // Using GET request
// Get the response code
int responseCode = connection.getResponseCode(); System.out.println("Response Code: " +
responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // Success
// Read data from the URL
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
String line;
StringBuilder content = new StringBuilder();
while ((line = reader.readLine()) != null) { content.append(line).append("\n");
}
reader.close();
// Print the JSON content received from the URL
System.out.println("JSON Data from URL:\n" + content);
System.out.println("Anant jain");
} else {
System.out.println("Failed to fetch data. HTTP Response Code: " + responseCode);
}
// Close connection
connection.disconnect();
} catch (MalformedURLException e) { System.out.println("Invalid URL: " +
e.getMessage());
} catch (IOException e) {
System.out.println("Error reading from URL: " + e.getMessage()); }}}
Output:
Lab 5 (iii) : Using HTTP URL connection for HTTP request
Source code:
import java.io.*;
import java.net.*;
public class HttpRequestExample { public static void main(String[] args) {
String urlString = "https://jsonplaceholder.typicode.com/posts/1"; // API endpoint
try {
// Create a URL object
URL url = new URL(urlString);
// Open HTTP connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET"); // Set request type as GET
connection.setRequestProperty("User-Agent", "Mozilla/5.0"); // Set request header
// Get response code
int responseCode = connection.getResponseCode(); System.out.println("Response Code: " +
responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // Success
// Read response
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) { response.append(line).append("\n");
}
reader.close();
// Print response
System.out.println("Response from Server:\n" + response);
System.out.println("Anant jain");
} else {
System.out.println("Request failed. HTTP Response Code: " + responseCode);
}
// Close connection connection.disconnect();
} catch (MalformedURLException e) { System.out.println("Invalid URL: " +
e.getMessage());
} catch (IOException e) {
System.out.println("Error in HTTP request: " + e.getMessage()); }}}
Output:
Lab 5 (iv) : Making a HTTP post request
Source code:
import java.io.*;
import java.net.*;
public class HttpPostExample {
public static void main(String[] args) {
String urlString = "https://jsonplaceholder.typicode.com/posts"; // 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) url.openConnection();
connection.setRequestMethod("POST"); // Set request type as POST
connection.setRequestProperty("Content-Type", "application/json; utf-8");
// Set headers
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true); // Enable writing to connection
// Write JSON data to request body
try (OutputStream os = connection.getOutputStream()) { byte[] input =
jsonInputString.getBytes("utf-8"); os.write(input, 0, input.length);
}
// Get response code
int responseCode = connection.getResponseCode(); System.out.println("Response Code: " +
responseCode);
// Read response from server
try (BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream(), "utf-8"))) {
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) { response.append(line).append("\n");
}
// Print response
System.out.println("Response from Server:\n" + response);
System.out.println("Anant jain");
}
// Close connection
connection.disconnect();
} catch (MalformedURLException e) { System.out.println("Invalid URL: " +
e.getMessage());
} catch (IOException e) {
System.out.println("Error in HTTP request: " + e.getMessage());}}}
Output:
Lab 5 (v) : Reading a file from URL connection :
Source code:
import java.io.*;
import java.net.*;
public class URLFileReader {
public static void main(String[] args) {
String fileUrl = "https://www.w3.org/TR/PNG/iso_8859-1.txt"; // URL of a text file
try {
// Create URL object
URL url = new URL(fileUrl);
// Open connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET"); // Use GET request
// Get response code
int responseCode = connection.getResponseCode(); System.out.println("Response Code: " +
responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // If response is successful
// Read file from URL
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
String line;
StringBuilder fileContent = new StringBuilder();
while ((line = reader.readLine()) != null) { fileContent.append(line).append("\n");
}
reader.close();
// Print file content
System.out.println("File Content from URL:\n" + fileContent);
System.out.println("Anant jain");
} else {
System.out.println("Failed to fetch file. HTTP Response Code: " + responseCode);
}
// Close connection
connection.disconnect();
} catch (MalformedURLException e) { System.out.println("Invalid URL: " +
e.getMessage());
} catch (IOException e) {
System.out.println("Error reading from URL: " + e.getMessage()); }}}
Output: