GURU TEGH BAHADUR INSTITUTE OF
TECHNOLOGY
Advance Java Lab
Submitted To:
Dr. Amandeep Kaur
Name: Madho Singh Nagi
Branch: IT-1 (ML & AI)
Enrolment Number: 05513203121
Index
S. No Title Date Sign.
Experiment 1
Aim: WAP in java to show dynamic polymorphism.
Code:
package DynamicPoly;
class Sample
{
public void display()
{
[Link]("Overridden Method");
}
}
public class Demo extends Sample
{
public void display()
{
[Link]("Overriding Method");
}
public static void main(String args[])
{
Sample obj = new Demo();
[Link]();
[Link]("By: Madho Singh (055)");
}}
Output:
Experiment 2
Aim: WAP in java to demonstrate multi implementation using
interfaces.
Code:
package MultiImp;
interface HumanSleep {
void sleep();
}
interface HumanHappy {
void happy();
}
class Human implements HumanSleep, HumanHappy {
public void sleep() {
[Link]("Human is sleeping");
}
public void happy() {
[Link]("Human is Happy");
}
}
public class Demo {
public static void main(String args[]) {
Human a = new Human();
[Link]();
[Link]();
[Link]("By: Madho Singh (055)");
}}
Output:
Experiment 3
Aim: WAP in java to make use of extends and implements in a
program.
Code:
package Extimp;
interface Shape {
double calculateArea();
}
class GeometricShape {
protected String name;
public GeometricShape(String name) {
[Link] = name;
}
public void display() {
[Link]("This is a " + name);
}
}
class Circle extends GeometricShape implements Shape {
private double radius;
public Circle(String name, double radius) {
super(name);
[Link] = radius;
}
@Override
public double calculateArea() {
return 3.14 * radius * radius;
}
}
class Rectangle extends GeometricShape implements Shape {
private double length;
private double width;
public Rectangle(String name, double length, double width) {
super(name);
[Link] = length;
[Link] = width;
}
public double calculateArea() {
return length * width;
}
}
public class Main {
public static void main(String[] args) {
Circle circle = new Circle("Circle", 7);
[Link]();
[Link]("Area of Circle: " + [Link]());
Rectangle rectangle = new Rectangle("Rectangle", 8, 14);
[Link]();
[Link]("Area of Rectangle: " + [Link]());
[Link]("By: Madho Singh (055)");
}
}
Output:
Experiment 4
Aim: WAP in java to make use of all 5 keywords of exception
handling.
Code:
package Excep;
import [Link];
public class ExceptionHandle {
public static void main(String[] args) {
try {
int result = divide(10, 0);
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("An arithmetic exception occurred: " + [Link]());
} finally {
[Link]("Finally block executed.");
}
try {
int[] arr = new int[5];
[Link]("Value at index 10: " + arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("An array index out of bounds exception occurred: " +
[Link]());
} finally {
[Link]("Finally block executed.");
}
try {
methodWithThrows();
} catch (IOException e) {
[Link]([Link]());
[Link]("By: Madho Singh (055)");
}
}
public static int divide(int num, int denom) {
if (denom == 0) {
throw new ArithmeticException("Division by zero");
}
return num / denom;
}
public static void methodWithThrows() throws IOException {
throw new IOException("An IO Exception occurred in methodWithThrows");
}
}
Output:
Experiment 5
Aim: WAP in java to generate your own exception in case age is less
than 18 declaring not eligible to vote.
Code:
package Age;
import [Link].*;
import [Link].*;
class InvalidAgeException extends Exception
{
InvalidAgeException (String message)
{
super(message);
}
}
class Main
{
public static void main(String[] a) throws InvalidAgeException {
int age;
Scanner in = new Scanner([Link]);
try {
[Link](" ENTER AGE.");
age = [Link]();
if (age < 18)
throw new InvalidAgeException("YOU ARE NOT ELIGIBLE TO VOTE");
else
[Link]("YOU ARE ELIGIBLE TO VOTE");
}
catch(InvalidAgeException e)
{
[Link]("CAUGHT AN EXCEPTION");
[Link]([Link]());
}
[Link]("By: Madho Singh (055)");
}
}
Output:
Experiment 6
Aim: WAP in java to implement producer and consumer problem by
implementing Runnable Interface.
Code:
package produce;
import [Link];
public class Main {
public static void main(String[] args)
throws InterruptedException
{
final PC pc = new PC();
Thread t1 = new Thread(new Runnable() {
public void run()
{
try {
[Link]();
}
catch (InterruptedException e) {
[Link]();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run()
{
try {
[Link]();
}
catch (InterruptedException e) {
[Link]();
}
}
});
[Link]();
[Link]();
[Link]();
[Link]();
}
public static class PC {
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;
public void produce() throws InterruptedException
{
int value = 0;
while (true) {
synchronized (this)
{
while ([Link]() == capacity)
wait();
[Link]("Producer produced-" + value);
[Link](value++);
notify();
[Link](1000);
}
}
}
public void consume() throws InterruptedException
{
while (true) {
synchronized (this)
{
while ([Link]() == 0)
wait();
int val = [Link]();
[Link]("Consumer consumed-" + val);
notify();
[Link](1000);
}
}
}
}
}Output:
Experiment 7
Aim: WAP in java to implement producer and consumer problem by
extending Thread class.
Code:
package consume;
public class Main {
public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
[Link]();
[Link]();
}
}
class CubbyHole {
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
} catch (InterruptedException e) {}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) { }
}
contents = value;
available = true;
notifyAll();
}
}
class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
[Link] = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = [Link]();
[Link]("Consumer " + [Link] + " got: " + value);
}
}
}
class Producer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c, int number) {
cubbyhole = c;
[Link] = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
[Link](i);
[Link]("Producer " + [Link] + " put: " + i);
try {
sleep((int)([Link]() * 100));
} catch (InterruptedException e) { }
}
}
}
Output:
Experiment 8
Aim: WAP in java to implement Reader Writer problem using
Threads.
Code:
package read;
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 {
public void run() {
try {
[Link]();
readCount++;
if (readCount == 1) {
[Link]();
}
[Link]();
[Link]("Thread "+[Link]().getName() + " is READING");
[Link](1500);
[Link]("Thread "+[Link]().getName() + " has FINISHED
READING");
[Link]();
readCount--;
if(readCount == 0) {
[Link]();
}
[Link]();
} catch (InterruptedException e) {
[Link]([Link]());
}
}
}
static class Write implements Runnable {
public void run() {
try {
[Link]();
[Link]("Thread "+[Link]().getName() + " is WRITING");
[Link](2500);
[Link]("Thread "+[Link]().getName() + " has finished
WRITING");
[Link]();
} catch (InterruptedException e) {
[Link]([Link]());
}
}
}
public static void main(String[] args) throws Exception {
Read read = new Read();
Write write = new Write();
Thread t1 = new Thread(read);
[Link]("thread1");
Thread t2 = new Thread(read);
[Link]("thread2");
Thread t3 = new Thread(write);
[Link]("thread3");
Thread t4 = new Thread(read);
[Link]("thread4");
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output:
Experiment 9
Aim: WAP in java to obtain Host Name and IP Address
Code:
package inet;
import [Link].*;
public class Main{
public static void main(String[] args){
try{
InetAddress ip=[Link]("[Link]");
[Link]("Host Name: "+[Link]());
[Link]("IP Address: "+[Link]());
}catch(Exception e)
{
[Link](e);
}
[Link]("By: Madho Singh (055)");
}
}
Output:
Experiment 10
Aim: WAP in java to Establish connection between client and server
Code:
Server:
package Socket;
import [Link].*;
import [Link].*;
public class Server {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(1234);
Socket s=[Link]();
DataInputStream dis=new DataInputStream([Link]());
String str=(String)[Link]();
[Link]("message= "+str);
[Link]();
}catch(Exception e){[Link](e);}
}
}
Client:
package Socket;
import [Link].*;
import [Link].*;
public class Client {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",1234);
DataOutputStream dout = new DataOutputStream([Link]());
[Link]("Hello Server");
[Link]();
[Link]();
[Link]();
}catch(Exception e){[Link](e);}
}
}
Output:
Experiment 11
Aim: WAP in java to establish connection between client and server
and print factorial.
Code:
Server:
package fact;
import [Link].*;
public class Server{
public static void main(String ar[]){
try{
DatagramSocket s = new DatagramSocket(1234);
while ( true ) {
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
[Link]( packet );
String message = new String([Link](), 0, 0, [Link]());
int res=1;
int ms=[Link](message);
for(int i=1;i<=ms;i++) res=res*i;
String str1=res+" ";
[Link]( "Factorial of " + message + " is " + str1);
}
}
catch(Exception e){
}
}
Client:
package fact;
import [Link].*;
import [Link].*;
public class Client{
public static void main(String ar[]) {
int myPort = 1234;
try {
DatagramSocket ds = new DatagramSocket();
DatagramPacket pack;
InetAddress addr = [Link]();
BufferedReader b=new BufferedReader (new InputStreamReader([Link]));
{
[Link]("Enter the number to find factorial : ");
String message=[Link]();
byte [] data = new byte [ [Link]() ];
[Link](0, [Link], data, 0);
pack = new DatagramPacket(data, [Link], addr, myPort);
[Link]( pack );
}
}
catch ( IOException e )
{
[Link]( e );
}
}
}
Output:
Experiment 12
Aim: WAP in java to create a UDP server that listens for datagrams
on a specific port
Code:
Server:
package UDP;
import [Link];
import [Link];
public class UdpServer {
public static void main (String[] args){
try{
DatagramSocket serverSocket = new DatagramSocket(9876);
[Link]("UDP Server litening on 9876");
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData,
[Link]);
[Link](receivePacket);
String message = new String([Link](),0,[Link]());
[Link]("Received mesage: "+ message);
[Link]();
}catch (Exception e){
[Link]();
}
}
}
Client:
package UDP;
import [Link];
import [Link];
import [Link];
public class UdpClient {
public static void main(String[] args){
try{
DatagramSocket clientSocket = new DatagramSocket();
InetAddress serverAddress = [Link]("localhost");
byte[] sendData = "Hello from UDP client!".getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,
[Link],serverAddress,9876);
[Link](sendPacket);
[Link]();
}catch (Exception e){
[Link]();
}
}
}
Output:
Experiment 13
Aim: WAP in java to create a UDP server that listens for datagrams
on a specific port
Code:
Server:
package Multi;
import [Link].*;
import [Link].*;
class Server {
public static void main(String[] args)
{
ServerSocket server = null;
try {
server = new ServerSocket(1234);
[Link](true);
while (true) {
Socket client = [Link]();
[Link]("New client connected"
+ [Link]()
.getHostAddress());
ClientHandler clientSock
= new ClientHandler(client);
new Thread(clientSock).start();
}
}
catch (IOException e) {
[Link]();
}
finally {
if (server != null) {
try {
[Link]();
}
catch (IOException e) {
[Link]();
}
}
}
}
private static class ClientHandler implements Runnable {
private final Socket clientSocket;
public ClientHandler(Socket socket)
{
[Link] = socket;
}
public void run()
{
PrintWriter out = null;
BufferedReader in = null;
try {
out = new PrintWriter(
[Link](), true);
in = new BufferedReader(
new InputStreamReader(
[Link]()));
String line;
while ((line = [Link]()) != null) {
[Link](
" Sent from the client: %s\n",
line);
[Link](line);
}
}
catch (IOException e) {
[Link]();
}
finally {
try {
if (out != null) {
[Link]();
}
if (in != null) {
[Link]();
[Link]();
}
}
catch (IOException e) {
[Link]();
}
}
}
}
}
Client:
package Multi;
import [Link].*;
import [Link].*;
import [Link].*;
class Client {
public static void main(String[] args)
{
try (Socket socket = new Socket("localhost", 1234)) {
PrintWriter out = new PrintWriter(
[Link](), true);
BufferedReader in
= new BufferedReader(new InputStreamReader(
[Link]()));
Scanner sc = new Scanner([Link]);
String line = null;
while (!"exit".equalsIgnoreCase(line)) {
line = [Link]();
[Link](line);
[Link]();
[Link]("Server replied "
+ [Link]());
}
[Link]();
}
catch (IOException e) {
[Link]();
}
}
}
Experiment 14
Aim: WAP in java to implement a file transfer system where the
client sends a file to the server
Code:
Server:
package FTP;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Server {
public static void main(String[] args){
try{
ServerSocket serverSocket = new ServerSocket(1212);
[Link]("Server litening on port 1212...");
Socket clientSocket = [Link]();
[Link]("Connection Established!");
InputStream inputStream = [Link]();
FileOutputStream fileOutputStream = new FileOutputStream("received_file.txt");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = [Link](buffer)) != 1){
[Link](buffer,0,bytesRead);
}
[Link]("File received Succesfully !");
[Link]();
[Link]();
}
catch (IOException e){
[Link]();
}
}
}
Client:
package FTP;
import [Link];
import [Link];
import [Link];
import [Link];
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 1212);
[Link]("Connection established! ");
OutputStream outputStream = [Link]();
FileInputStream fileInputStream = new FileInputStream("file_to_send.txt");
byte[] buffer = new byte[1212];
int bytesRead;
while ((bytesRead = [Link](buffer)) != -1) {
[Link](buffer, 0, bytesRead);
}
[Link]("File sent successfully!");
[Link]();
[Link]();
;
} catch (IOException e) {
[Link]();
}
}
}
Output: