0% found this document useful (0 votes)
180 views29 pages

JAVA Lab Sorce Codes

The document contains 14 questions related to Java programming. Question 1 asks to write programs demonstrating constructor overloading, method overloading, and inner classes with access protection. Question 2 involves string handling methods like checking string buffer capacity, reversing and uppercasing strings, and appending strings. Question 3 involves inheritance and interfaces to calculate area of shapes. Question 4 creates account and exception classes to demonstrate exception handling.

Uploaded by

Amar Kamate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
180 views29 pages

JAVA Lab Sorce Codes

The document contains 14 questions related to Java programming. Question 1 asks to write programs demonstrating constructor overloading, method overloading, and inner classes with access protection. Question 2 involves string handling methods like checking string buffer capacity, reversing and uppercasing strings, and appending strings. Question 3 involves inheritance and interfaces to calculate area of shapes. Question 4 creates account and exception classes to demonstrate exception handling.

Uploaded by

Amar Kamate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Java Programming Laboratory

1. a.Write a JAVA Program to demonstrate Constructor Overloading and Method Overloading.


b.Write a JAVA Program to implement Inner class and demonstrate its Access protection.
2. Write a program in Java for String handling which performs the following:
i) Checks the capacity of StringBuffer objects.
ii) Reverses the contents of a string given on console and converts the resultant string in upper case.
iii) Reads a string from console and appends it to the resultant string of ii.
3. a.Write a JAVA Program to demonstrate Inheritance.
b. Simple Program on Java for the implementation of Multiple inheritance using interfaces to calculate the area of
a rectangle and triangle.
4. Write a JAVA program which has
i. A Class called Account that creates account with 500Rs minimum balance, a deposit() method to deposit
amount, a withdraw() method to withdraw amount and also throws LessBalanceException if an account holder
tries to withdraw money which makes the balance become less than 500Rs.
ii. A Class called LessBalanceException which returns the statement that says withdraw amount ( Rs) is not valid.
iii. A Class which creates 2 accounts, both account deposit money and one account tries to withdraw more money
which generates a LessBalanceException take appropriate action for the same.
5. Write a JAVA program using Synchronized Threads, which demonstrates Producer Consumer concept.
6. Write a JAVA program to implement a Queue using user defined Exception Handling (also make use of throw,
throws.).
7. Complete the following:
1. Create a package named shape.
2. Create some classes in the package representing some common shapes like Square, Triangle, and Circle.
3. Import and compile these classes in other program.
8. Write a JAVA Program
a. Create an enumeration Day of Week with seven values SUNDAY through SATURDAY. Add a method is
Workday( ) to the DayofWeek class that returns true if the value on which it is called is MONDAY through
FRIDAY. For example, the call DayOfWeek.SUNDAY.isWorkDay ( ) returns false.
9. Write a JAVA program which has
i. A Interface class for Stack Operations
ii. A Class that implements the Stack Interface and creates a fixed length Stack.
iii. A Class that implements the Stack Interface and creates a Dynamic length Stack.
iv. A Class that uses both the above Stacks through Interface reference and does the Stack operations that
demonstrates the runtime binding.
10. Write a JAVA program to print a chessboard pattern.
11. Write a JAVA Program which uses FileInputStream / FileOutPutStream Classes.

12. Write JAVA programs which demonstrates utilities of LinkedList Class.


13. Write a JAVA program which uses Datagram Socket for Client Server Communication.
14. Write a JAVA applet program, which handles keyboard event.

1a)

class Rectangle
{
int area,length,breadth;
Rectangle()
{
length=0;
breadth=0;
}
Rectangle(int length,int breadth)
{
this.length=length;
this.breadth=breadth;
}
Rectangle(Rectangle r)
{
length=r.length;
breadth=r.breadth;
}
Rectangle(int a)
{
length=breadth=a;
}
void ComputeArea()
{
area=length*breadth;
}
int ComputeArea(int lenc,int brec)
{
return((length+lenc)*(breadth+brec));
}
int ComputeArea(Rectangle r)
{
return((length+r.length)*(breadth+r.breadth));
}
void display()
{
System.out.println(area);
}
public static void main(String args[])
{
int a;

Rectangle
Rectangle
Rectangle
Rectangle

r=new Rectangle();
r1=new Rectangle(5);
r2=new Rectangle(4,5);
r3=new Rectangle(r2);

r.ComputeArea();
r1.ComputeArea();
r2.ComputeArea();
r3.ComputeArea();
System.out.println("Area of all the Rectangles =");
r.display();
r1.display();
r2.display();
r3.display();
System.out.println("Area of r2 with length and breadth incremented by
2:"+r2.ComputeArea(2,2));
System.out.println("Area of r2 and r3:"+r2.ComputeArea(r3));
}
}

1b)
class Outer
{
int out=1000;

public int outer_x=100;


private int outer_y=200;
protected int outer_z=300;
void test()
{
Inner inner=new Inner();
inner.display();
}
class Inner
{
public int inner_x=1000;
private int inner_y=2000;
protected int inner_z=3000;
void display()
{
System.out.println("Inside inner class");
System.out.println("outer_x:"+outer_x);
System.out.println("outer_y:"+outer_y);
System.out.println("outer_z:"+outer_z);
System.out.println("outer_x:"+outer_x);
System.out.println("outer_y:"+outer_y);
System.out.println("outer_z:"+outer_z);
}
}
}
class DemoInner
{
public static void main(String[] args)
{
Outer outer=new Outer();
outer.test();
}
}

2)
import java.util.Scanner;
class Ex2
{
public static void main(String args[])
{
StringBuffer sb=null;

Scanner s=new Scanner(System.in);


sb=new StringBuffer(s.next());
System.out.println("String Buffer Capacity:"+sb.capacity());
StringBuffer sbr=sb.reverse();
String s1=new String(sbr);
System.out.println("Reverse of given String:"+sbr);
sbr=new StringBuffer(s1.toUpperCase());
System.out.println("Upper case of reverse String "+sbr);
sbr=sbr.append(s.next());
System.out.println("String after appending:"+sbr);
}
}

3a)
class Box
{
double width;
double height;
double depth;
Box(Box ob)
{

width=ob.width;
height=ob.height;
depth=ob.depth;
}
Box(double w,double h,double d)
{
width=w;
height=h;
depth=d;
}
Box()
{
width=-1;
height=-1;
depth=-1;
}
Box(double len)
{
width=height=depth=len;
}
double volume()
{
return width*height*depth;
}
}
class BoxWeight extends Box
{
double weight;
BoxWeight(double w,double h,double d,double wt)
{
super(w,h,d);
weight=wt;
}
}
class DemoBoxWeight
{
public static void main(String args[])
{
BoxWeight mybox1 = new BoxWeight(10,20,15,34.3);
BoxWeight mybox2 = new BoxWeight(2,3,4,0.076);
double vol;
vol=mybox1.volume();
System.out.println("Volume of mybox1 is :" +vol);
System.out.println("Weight of mybox1 is :" +mybox1.weight);

vol=mybox2.volume();
System.out.println("Volume of mybox2 is :" +vol);
System.out.println("Weight of mybox2 is :" +mybox2.weight);
}
}

3b)
interface TwoD
{
void calArea();
}
class TwoDim
{
float s1,s2;
float area;
void displayArea()
{

System.out.println("Area="+area);
}
}
class Triangle extends TwoDim implements TwoD
{
Triangle(int a,int b)
{
s1=a;
s2=b;
}
public void calArea()
{
area=0.5f*s1*s2;
}
}
class Rectangle extends TwoDim implements TwoD
{
Rectangle(int a,int b)
{
s1=a;
s2=b;
}
public void calArea()
{
area=s1*s2;
}
}
class Ex3b
{
public static void main(String args[])
{
Rectangle r=new Rectangle(5,4);
Triangle t=new Triangle(5,6);
r.calArea();
t.calArea();
r.displayArea();
t.displayArea();
}
}

4)
import java.io.*;
class LessBalanceException extends Exception
{
double amt;
LessBalanceException(double wamt)
{
amt=wamt;
System.out.println("withdraw not possible"+amt);
}
}
class Account
{
public double bal;

Account()
{
bal=500.0;
}
public void deposit(double damt)
{
bal=bal+damt;
}
public void withdraw(double wamt) throws LessBalanceException
{
if((bal-wamt)<=500)
throw(new LessBalanceException(wamt));
else
{
bal=bal-wamt;
System.out.println("Amount withdrawn:"+wamt);
System.out.println("balance:"+bal);
}
}
}
public class OwnExceptionDemo
{
public static void main(String args[])
{
Account a1=new Account();
Account a2=new Account();
a1.deposit(5000);
a2.deposit(5000);
System.out.println("balance of a1:"+a1.bal);
System.out.println("balance of a2:"+a2.bal);
try
{
a1.withdraw(4000);
a2.withdraw(5000);
}
catch(LessBalanceException e)
{
System.out.println("cant withdraw"+e);
}
}
}
5)
class Q

{
int n;
boolean valueSet=false;
synchronized int get()
{
while(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException cought");
}
System.out.println("Got:"+n);
valueSet=false;
notify();
return n;
}
synchronized void put(int n)
{
while(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException cought");
}
this.n=n;
System.out.println("Put:"+n);
valueSet=true;
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;

new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
{
q.put(i++);
}
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}
public class SynchronisedThreadsDemo
{
public static void main(String args[])
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press ctrl+c to Stop");
}
}

6)
class QueueFullException extends Exception
{
QueueFullException()
{
System.out.println("Queue is Full");
}
}
class QueueEmptyException extends Exception
{
QueueEmptyException()
{
System.out.println("Queue is Empty");
}
}
class Queue
{
int a[],f,r;
Queue(int size)
{
a=new int[size];
f=0;
r=-1;
}

void insert( int ele) throws QueueFullException


{
if(r==a.length-1)
throw(new QueueFullException() );
else
{
r++;
a[r]=ele;
}
}
int remove() throws QueueEmptyException
{
System.out.println(" f= "+f+" r= "+r);
if(f>r||r==-1)
{
throw(new QueueEmptyException());
}
else
{
return(a[f++]);
}
}
void display() throws QueueEmptyException
{
if(f>r||r==-1)
throw(new QueueEmptyException());
else
{
for(int i=f;i<=r;i++)
System.out.println(a[i]+"\n");
}
}
}
class QueueDemo
{
public static void main(String[] args)
{
Queue q = new Queue(5);
try
{
for(int i=0;i<6;i++)
q.insert(i);
}

catch(QueueFullException e)
{
System.out.println("Queue is Full"+e);
}
System.out.println("Contents of the Queue are : ");
try
{
q.display();
for(int i=0;i<6;i++)
System.out.println(q.remove());
}
catch(QueueEmptyException e)
{
System.out.println("\nNo Elements to display");
}
}
}

7)
//ShapeDemo.java
import shape.*;
class ShapeDemo
{
public static void main(String args[])
{
Square s = new Square(5);
System.out.println("Area of Square = " + s.calArea() );
Triangle t = new Triangle(5,5);
System.out.println("Area of Triangle = " + t.calArea() );
Circle c = new Circle(5);
System.out.println("Area of Circle = " + c.calArea() );
}
}
//Square.java
package shape;
public class Square
{
int side,area;
public Square()
{
side=0;
area=0;
}
public Square(int a)
{
side=a;

}
public int calArea()
{
area = side * side;
return area;
}
}
//Triangle.java
package shape;
public class Triangle
{
double base,altitude,area;
public Triangle()
{
base=0;
altitude=0;
area=0;
}
public Triangle(float b , float a)
{
base = b ;
altitude = a ;
}
public double calArea()
{
area = 0.5 * base * altitude ;
return area;
}
}
//Circle.java
package shape;
public class Circle
{
double r,area;
public Circle()
{
r=0;
area=0;
}
public Circle(double radius)
{
r=radius;
}

public double calArea()


{
area = 3.142 * r * r;
return area;
}
}

8)
import java.util.Scanner;
enum week
{
SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY;
boolean WorkDay()
{
if(ordinal()==0||ordinal()==6)
return false;
else
return true;
}
}
class EnumDemo
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
week day;
System.out.println("Enter Day:");
String d=s.next();
day=week.valueOf(d);
System.out.println("Is the workday? ANS:"+day.WorkDay());
}
}

9)
interface IntStack
{
public void push(int item);
public int pop();
}
class FixedStack implements IntStack
{
private int stack[];
private int tos;
FixedStack(int size)
{
stack=new int[size];
tos=-1;
}
public void push(int item)
{
if(tos==stack.length)
{
System.out.println("Stack Overflow");
}
else
{
stack[++tos]=item;
}
}
public int pop()
{
if(tos<0)
{
System.out.println("Stack Underflow");
return 0;
}
else
return stack[tos--];

}
}
class DyStack implements IntStack
{
private int stack[];
private int tos;
DyStack(int size)
{
stack=new int[size];
tos=-1;
}
public void push(int item)
{
if(tos==stack.length-1)
{
int temp[]=new int[stack.length*2];
for(int i=0;i<stack.length;i++)
temp[i]=stack[i];
stack=temp;
stack[++tos]=item;
}
else
stack[++tos]=item;
}
public int pop()
{
if(tos<0)
{
System.out.println("Stack Underflow");
return 0;
}
else
return stack[tos--];
}
}
public class StackDemo
{
public static void main(String[] args)
{
int i;
IntStack mystack;
DyStack ds=new DyStack(5);
FixedStack fs=new FixedStack(8);
mystack=ds;
for(i=0;i<12;i++)
mystack.push(i);

mystack=fs;
for(i=0;i<8;i++)
mystack.push(i);
mystack=ds;
System.out.println("Values in Dyanamic stack");
for(i=0;i<12;i++)
System.out.println(mystack.pop());
mystack.pop();
mystack=fs;
System.out.println("Values in fixed stack");
for(i=0;i<8;i++)
System.out.println(mystack.pop());
mystack.pop();
}
}

10)
import
import
import
import

java.awt.*;
java.awt.event.*;
java.util.*;
javax.swing.*;

public class ChessGameDemo extends JFrame


{
JLayeredPane layeredPane;
JPanel chessBoard;
JLabel chessPiece;
int xAdjestment;
int yAdjustment;
public ChessGameDemo()
{
Dimension boardSize=new Dimension(600,600);
//use a layered pane for this application
layeredPane=new JLayeredPane();
getContentPane().add(layeredPane);
layeredPane.setPreferredSize(boardSize);
chessBoard=new JPanel();
layeredPane.add(chessBoard,JLayeredPane.DEFAULT_LAYER);
chessBoard.setLayout(new GridLayout(8,8));
chessBoard.setPreferredSize(boardSize);
chessBoard.setBounds(0,0,boardSize.width,boardSize.height);
for(int i=0;i<64;i++)
{
JPanel square=new JPanel(new BorderLayout());
chessBoard.add(square);
int row=(i/8)%2;
if(row==0)
square.setBackground(i%2==0?Color.blue:Color.white);
else
square.setBackground(i%2==0?Color.white:Color.blue);
}
}
public static void main(String[] args)
{
JFrame frame= new ChessGameDemo();
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

frame.pack();
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
11)
import java.io.*;
public class CopyFile
{
public static void main(String args[])
throws IOException
{
int i;
FileInputStream fin;
FileOutputStream fout = null;
try
{
try
{
fin=new FileInputStream(args[0]);
}
catch(FileNotFoundException e)
{
System.out.println("Input File not found.");
return;
}
try
{
fout=new FileOutputStream(args[1]);
}
catch(FileNotFoundException e)
{
System.out.println("Output file not found,");
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Usage: CopyFile From TO"+ e);
return;
}
try
{
do
{
i=fin.read();
if(i!=-1)
fout.write(i);

}
while(i!=-1);
}
catch(IOException e)
{
System.out.println("FileError :"+e);
}
fin.close();
fout.close();
}
}

12)
import java.util.*;
class LinkedListDemo
{
public static void main(String args[])
{
//Create linked list
LinkedList<String> ll=new LinkedList<String>();
//Add Elements to the linked list
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1,"A2");
System.out.println("Original contents of ll: "+ll);
//Remove Elements from the linked list
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: "+ll);
//Remove first & Last Elements
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first & last: "+ll);
//Get & Set a value
String val=ll.get(2);
ll.set(2,val+"Changed");
System.out.println("ll after change: "+ll);
}
}

13)
import java.net.*;
public class WriteServer
{
public static int serverPort=9990;
public static int clientPort=9980;
public static int buffer_size=1024;
public static DatagramSocket ds;
public static byte buffer[]=new byte[buffer_size];
public static void TheServer() throws Exception
{
int pos=0;
while(true)
{
int c=System.in.read();
switch(c)
{
case -1:
System.out.println("Server Quits. ");
return;
case '\r':
break;
case'\n':
ds.send(new
DatagramPacket(buffer,pos,InetAddress.getLocalHost(),clie
ntPort));
pos=0;
break;
default:
buffer[pos++]=(byte)c;
}
}
}
public static void TheClient() throws Exception
{
while(true)
{
DatagramPacket p=new DatagramPacket(buffer,buffer.length);
ds.receive(p);

System.out.println(new String(p.getData(),0,p.getLength()));
}
}
public static void main(String[] args) throws Exception
{
if(args.length==1)
{
ds=new DatagramSocket(serverPort);
TheServer();
}
else
{
ds=new DatagramSocket(clientPort);
TheClient();
}
}
}

14)
import java.applet.*;
import java.awt.Graphics;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/* <applet code="KeyEvents" height=500 width=500>
</applet> */
public class KeyEvents extends Applet implements KeyListener
{
String msg=" ";
int X=10,Y=20;
public void init()
{
addKeyListener(this);
}
public void keyTyped(KeyEvent ke)
{
msg+=ke.getKeyChar();
repaint();
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key Down");
int key=ke.getKeyCode();
switch(key)
{
case KeyEvent.VK_F1:
msg+="<F1>";
break;
case KeyEvent.VK_F2:
msg+="<F2>";
break;
case KeyEvent.VK_F3:
msg+="<F3>";
break;
case KeyEvent.VK_LEFT:
msg+="<Left Arrow>";
break;
case KeyEvent.VK_RIGHT:
msg+="<Right Arrow>";
break;
case KeyEvent.VK_PAGE_DOWN:
msg+="<Page Down>";

break;
case KeyEvent.VK_PAGE_UP:
msg+="<Page Up>";
break;
}
repaint();
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy