Java Madho

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

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()
{
System.out.println("Overridden Method");
}
}
public class Demo extends Sample
{
public void display()
{
System.out.println("Overriding Method");
}
public static void main(String args[])
{
Sample obj = new Demo();
obj.display();
System.out.println("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() {
System.out.println("Human is sleeping");
}
public void happy() {
System.out.println("Human is Happy");
}
}
public class Demo {
public static void main(String args[]) {
Human a = new Human();
a.sleep();
a.happy();
System.out.println("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) {

this.name = name;
}
public void display() {
System.out.println("This is a " + name);
}

}
class Circle extends GeometricShape implements Shape {
private double radius;
public Circle(String name, double radius) {
super(name);

this.radius = 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);
this.length = length;
this.width = width;
}
public double calculateArea() {

return length * width;


}
}
public class Main {
public static void main(String[] args) {

Circle circle = new Circle("Circle", 7);


circle.display();
System.out.println("Area of Circle: " + circle.calculateArea());
Rectangle rectangle = new Rectangle("Rectangle", 8, 14);
rectangle.display();

System.out.println("Area of Rectangle: " + rectangle.calculateArea());


System.out.println("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 java.io.IOException;
public class ExceptionHandle {
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("An arithmetic exception occurred: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
try {
int[] arr = new int[5];
System.out.println("Value at index 10: " + arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("An array index out of bounds exception occurred: " +
e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
try {
methodWithThrows();
} catch (IOException e) {
System.out.println(e.getMessage());
System.out.println("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 java.util.*;
import java.lang.*;
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(System.in);
try {
System.out.println(" ENTER AGE.");
age = in.nextInt();
if (age < 18)
throw new InvalidAgeException("YOU ARE NOT ELIGIBLE TO VOTE");
else
System.out.println("YOU ARE ELIGIBLE TO VOTE");
}
catch(InvalidAgeException e)
{
System.out.println("CAUGHT AN EXCEPTION");
System.out.println(e.getMessage());
}
System.out.println("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 java.util.LinkedList;

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 {
pc.produce();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run()
{
try {
pc.consume();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
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 (list.size() == capacity)
wait();
System.out.println("Producer produced-" + value);
list.add(value++);
notify();
Thread.sleep(1000);
}
}
}
public void consume() throws InterruptedException
{
while (true) {
synchronized (this)
{
while (list.size() == 0)
wait();
int val = list.removeFirst();
System.out.println("Consumer consumed-" + val);
notify();
Thread.sleep(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);
p1.start();
c1.start();
}
}
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;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = cubbyhole.get();
System.out.println("Consumer " + this.number + " got: " + value);
}
}
}
class Producer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
cubbyhole.put(i);
System.out.println("Producer " + this.number + " put: " + i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}

Output:
Experiment 8
Aim: WAP in java to implement Reader Writer problem using
Threads.
Code:
package read;
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 {
public void run() {
try {
readLock.acquire();
readCount++;
if (readCount == 1) {
writeLock.acquire();
}
readLock.release();
System.out.println("Thread "+Thread.currentThread().getName() + " is READING");
Thread.sleep(1500);
System.out.println("Thread "+Thread.currentThread().getName() + " has FINISHED
READING");
readLock.acquire();
readCount--;
if(readCount == 0) {
writeLock.release();
}
readLock.release();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
static class Write implements Runnable {
public void run() {
try {
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) {
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args) throws Exception {
Read read = new Read();
Write write = new Write();
Thread t1 = new Thread(read);
t1.setName("thread1");
Thread t2 = new Thread(read);
t2.setName("thread2");
Thread t3 = new Thread(write);
t3.setName("thread3");
Thread t4 = new Thread(read);
t4.setName("thread4");
t1.start();
t3.start();
t2.start();
t4.start();
}
}

Output:
Experiment 9
Aim: WAP in java to obtain Host Name and IP Address
Code:
package inet;

import java.net.*;
public class Main{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.instagram.com");

System.out.println("Host Name: "+ip.getHostName());


System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e)
{

System.out.println(e);
}
System.out.println("By: Madho Singh (055)");
}
}

Output:
Experiment 10
Aim: WAP in java to Establish connection between client and server
Code:
Server:

package Socket;
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args){

try{
ServerSocket ss=new ServerSocket(1234);
Socket s=ss.accept();
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();

System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}

Client:
package Socket;

import java.io.*;
import java.net.*;

public class Client {


public static void main(String[] args) {
try{
Socket s=new Socket("localhost",1234);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();

s.close();
}catch(Exception e){System.out.println(e);}
}
}

Output:
Experiment 11
Aim: WAP in java to establish connection between client and server
and print factorial.
Code:
Server:
package fact;

import java.net.*;
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);
s.receive( packet );
String message = new String(packet.getData(), 0, 0, packet.getLength());

int res=1;
int ms=Integer.parseInt(message);
for(int i=1;i<=ms;i++) res=res*i;
String str1=res+" ";
System.out.println( "Factorial of " + message + " is " + str1);

}
}
catch(Exception e){

}
}
Client:
package fact;
import java.net.*;

import java.io.*;
public class Client{
public static void main(String ar[]) {
int myPort = 1234;
try {

DatagramSocket ds = new DatagramSocket();


DatagramPacket pack;
InetAddress addr = InetAddress.getLocalHost();
BufferedReader b=new BufferedReader (new InputStreamReader(System.in));

{
System.out.print("Enter the number to find factorial : ");
String message=b.readLine();
byte [] data = new byte [ message.length() ];
message.getBytes(0, data.length, data, 0);

pack = new DatagramPacket(data, data.length, addr, myPort);


ds.send( pack );
}
}
catch ( IOException e )

{
System.out.println( 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 java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UdpServer {


public static void main (String[] args){

try{
DatagramSocket serverSocket = new DatagramSocket(9876);
System.out.println("UDP Server litening on 9876");

byte[] receiveData = new byte[1024];

DatagramPacket receivePacket = new DatagramPacket(receiveData,


receiveData.length);
serverSocket.receive(receivePacket);
String message = new String(receivePacket.getData(),0,receivePacket.getLength());
System.out.println("Received mesage: "+ message);
serverSocket.close();

}catch (Exception e){


e.printStackTrace();
}
}
}

Client:
package UDP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpClient {


public static void main(String[] args){
try{
DatagramSocket clientSocket = new DatagramSocket();

InetAddress serverAddress = InetAddress.getByName("localhost");

byte[] sendData = "Hello from UDP client!".getBytes();


DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length,serverAddress,9876);
clientSocket.send(sendPacket);
clientSocket.close();

}catch (Exception e){


e.printStackTrace();
}
}
}

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 java.io.*;
import java.net.*;
class Server {
public static void main(String[] args)
{

ServerSocket server = null;


try {
server = new ServerSocket(1234);
server.setReuseAddress(true);
while (true) {

Socket client = server.accept();


System.out.println("New client connected"
+ client.getInetAddress()
.getHostAddress());
ClientHandler clientSock

= new ClientHandler(client);
new Thread(clientSock).start();
}
}
catch (IOException e) {

e.printStackTrace();
}
finally {
if (server != null) {
try {
server.close();

}
catch (IOException e) {
e.printStackTrace();
}
}

}
}
private static class ClientHandler implements Runnable {
private final Socket clientSocket;
public ClientHandler(Socket socket)

{
this.clientSocket = socket;
}
public void run()
{

PrintWriter out = null;


BufferedReader in = null;
try {
out = new PrintWriter(
clientSocket.getOutputStream(), true);

in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.printf(
" Sent from the client: %s\n",
line);
out.println(line);

}
}
catch (IOException e) {
e.printStackTrace();
}

finally {
try {
if (out != null) {
out.close();
}

if (in != null) {
in.close();
clientSocket.close();
}
}

catch (IOException e) {
e.printStackTrace();
}
}
}

}
}

Client:
package Multi;
import java.io.*;
import java.net.*;
import java.util.*;
class Client {

public static void main(String[] args)


{
try (Socket socket = new Socket("localhost", 1234)) {
PrintWriter out = new PrintWriter(
socket.getOutputStream(), true);

BufferedReader in
= new BufferedReader(new InputStreamReader(
socket.getInputStream()));
Scanner sc = new Scanner(System.in);
String line = null;

while (!"exit".equalsIgnoreCase(line)) {
line = sc.nextLine();
out.println(line);
out.flush();
System.out.println("Server replied "

+ in.readLine());
}
sc.close();
}
catch (IOException e) {

e.printStackTrace();
}
}
}
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 java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {


public static void main(String[] args){
try{
ServerSocket serverSocket = new ServerSocket(1212);
System.out.println("Server litening on port 1212...");

Socket clientSocket = serverSocket.accept();


System.out.println("Connection Established!");
InputStream inputStream = clientSocket.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("received_file.txt");
byte[] buffer = new byte[1024];

int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != 1){
fileOutputStream.write(buffer,0,bytesRead);
}
System.out.println("File received Succesfully !");

fileOutputStream.close();
clientSocket.close();
}
catch (IOException e){
e.printStackTrace();
}

}
}
Client:
package FTP;
import java.io.IOException;

import java.io.OutputStream;
import java.net.Socket;
import java.io.FileInputStream;
public class Client {
public static void main(String[] args) {

try {
Socket socket = new Socket("localhost", 1212);
System.out.println("Connection established! ");
OutputStream outputStream = socket.getOutputStream();
FileInputStream fileInputStream = new FileInputStream("file_to_send.txt");

byte[] buffer = new byte[1212];


int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}

System.out.println("File sent successfully!");


fileInputStream.close();
socket.close();
;
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output:

You might also like