1.
Write a java program to accept a year number from the key and test if it is
leap or not.
import java.io.*;
class Program{
public static void main(String args[])
{
int n=2015;
year y=year.of(n);
Boolean flag=y.isLeap();
If(flag)
{
System.out.println(“%n year %d is Leap.”,n);
}
else
{
System.out.println(“%n year %d is not Leap.”,n);
}
}
}
Output:
c:\>javac Program.java
c:\>java Program
year 2015 is not leap.
2.Write a java program for calculating and displaying area
of a circle.
import java.io.*;
class Circle
{
public static void main (String args[])
{
final double PI=(double)22/7;
double r=15.5;
double area=PI*r*r;
System.out.println(“Area=”+Area);
}
}
Output:
C:\>javac Circle.java
C:\>java Circle
Area=755.0714285714286
3.Write a java program to create a push button and add it to a frame.
import java.awt.*;
import java.awt.event.*;
class But extends Frame
{
But()
{
Button b=new Button(“ok”);
Add(b);
b.addActionListener(new Myclass());
}
Public static void main(String args[])
{
But obj=new But();
obj.setSize(400,300);
obj.setVisible(true);
}
}
Class Myclass implements ActionListener
{
Public viod actionPerformed(ActionEvent ae)
{
System.exit(0);
}
}
Output:
C:\>javac But.java
C:\>java But
4.Write a java program to find the areas of square and Rectangle by deriving
them from Shape.
import java.io.*;
class Shape
{
Protected double1;
Shape(double 1)
{
this.1=1;
}
}
class Square extends Shape
{
Square(double 1)
{
Super(1);
}
Void area()
{
System.out.println(“Area of Rectangle=”+(1*b));
}
}
class Inherit
{
Public static void main(String args[])
{
Square s=new Square(5.5);
s.area();
Rectangle r=new Rectangle(5.5,6);
r.area();
}
}
Output:
C:\>javac Inherit.java
C:\>java Inherit
Area of Square=30.25
Area of Rectangle=33.0
5.Write a java program to make cloning Employee class object by writing own
myclone()method,from where object class clone()method is called.
import java.io.*;
class Employee implements Cloneable
{
int id;
String name;
Employee(int id,String name)
{
this.id=id;
this.name=name;
}
void getdata()
{
System.out.println(“id=”+id);
System.out.println(“name=”+name);
}
Public object myClone() throws CloneNotSupportedException
{
return super.Clone();
}
}
class CloneDemo
{
Public static void main(String args[])throws CloneNotSupportedException
{
Employee e1=new Employee(10,”teja”);
System.out.println(“original object :”);
e1.getdata();
Employee e2=(Employee)e1.myClone();
System.out.println(“Cloned object:”);
e2.getdata();
}
}
Output:
C:\>javac CloneDemo.java
C:\>java CloneDemo
Original object:
Id=9
Name=teja
Cloned object:
Id=9
Name=teja
6.Write a java program for calculating electricity bill for commercial and domestic plans by using
abstract class.
abstract class Plan
{
protected double rate;
public abstract void getRate();
public void calculateBill(int units)
{
System.out.print(“Bill amount for”+units+”units:”);
System.out.println(rate*units);
}
}
class commercialPlan extends Plan
{
public void getRate()
{
rate=5.00;
}
}
class Calculate
{
public static void main(String args[])
{
Plan P;
System.out.println(“Commercial connection:”);
P= new CommercialPlan();
P.getRate();
P.calculateBill(250);
System.out.println(“domestic connection:”);
P=new DomesticPlan();
P.getRate();
P.calculateBill(150);
}
}
Output:
C:\>javac Calculate.java
C:\>java Calculate
Commercial connection:
Bill amount for 250 units: 1250.0
Domestic connection:
Bill amount for 150 units: 390.0
7. Write a java program to create a package and store Addition class and
subtraction class in it.
import pack.Addition;
import pack.subtraction;
class Use
{
public static void main(String args[])
Addition obj=new Addition(10,15.5)
obj.sum();
double res=Subtraction.sub(10,15.5);
System.out.println(“Result=”+res);
}
}
Output:
C:\>javac Use.java
C:\>java Use
sum=25.5
Result=5.5
8.Write a java program to convert int into binary ,hexadecimal and octal format.
import java.io.*;
class Convert
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Enter an integer:”);
Srting str=br.readLine();
int i=Inter.ParseInt(str);
System.out.println(“In decimal:”+i);
str=Integer.toBinaryString(i);
System.out.println(“In binary:”+str);
str=Integer.toHexString(i);
System.out.println(“In hexadecimal:”+str);
str=Integer.toOctalString(i);
System.out.println(“In octal:”+str);
}
}
Output:
C:\>javac Convert.java
C:\>java Convert
Enter an Integer: 456
In decimal: 456
In binary : 111001000
In hexadecimal: 1c8
In Octal:710
9)Write a java program for Multiple Exception Handling.
class Ex1
{
public static void main(String args[])
{
try
{
System.out.println(“open files”);
int n=args.length;
System.out.println(“n=”+n);
int a=45/n;
System.out.println(“a=”+a);
int b[]={10,20,30};
b[50]=100;
}
Catch(ArithematicException|ArrayIndexOutof BoundsException ae)
System.out.println(ae);
}
finally
{
System.out.println(“close files”);
}
}
}
Output:
C:\> javvac Ex1.java
C:\>java Ex1
Open files
N=0
Java.lang.ArithmeticException:/by zero
Close files
C:\>java Ex1 11 22
Open files
N=2
A=22
Java.lang.ArrayIndexOutofBoundsException:50
Close files
10 ) Write a java program to throw a User Defined Exception.
class MyException extends Exception
{
private static int accno[]={1001,1002,1003,1004,1005};
private static string name[]={“Mounika”, “Nireekshana”, “Hemapriya”, “Haritha”, “Laxmi Devi”};
private static double bal[]={10000.00, 12000.00, 5600.50, 999.00, 1100.55};
MyException()
{
}
MyException(string str)
{
Super(str);
}
public static void main(String args[])
{
try{
System.out.println(“ACCNO”+”\t”+”CUSTOMER”+”\t”+ “BALANCE”);
For(int i=0; i<5; i++)
{
System.out.println(accno[i]+”\t”+name[i]+”\t”+ bal[i]);
If(bal[i]<1000)
{
MyException me=new MyException(“Balance amount is less”);
throw me;
}
}
}
catch(MyException me){
me.printstackTrace();
}
}
}
Output:
C:\>javac MyException.java
C:\>java MyException
ACCNO CUSTOMER BALANCE
1001 Mounika 10000.00
1002 Nireekshana 12000.0
1003 Hema priya 5600.5
1004 Haritha 999.0
MyException: Balance amount is less
At MyException.main(MyException.java:39)
11.Write a java program for to synchronize the threads acting on the same object. Synchronize block
can be executed only one thread at a time.
class Reserve implements Runnable
{
int available=1;
int wanted;
Reserve(int i)
{
Wanted=I;
}
public void run()
{
Synchronized(this)
{
System.out.println(“Avaliable Berths=”+available);
if(available>=wanted)
{
String name=Thread.currentThread().getName();
System.out.println(wanted=”Berths reserved for”+name);
try
{
Thread.sleep(1500);
available=available-wanted;
}catch(InterruptedException ie){}
}
else System.out.println(“sorry, no berths”);
}
}
}
class Safe
{
Public static void main(String args[])
Reserve obj=new Reserve(1);
Thread t1=new Thread(obj);
Thread t2=new Thread(obj);
t1.setName(“first person”);
t2.setName(“second person”);
t1.start();
t2.start();
}
}
Output:
C:\>javac Safe.java
C:\>java Safe
Avaliable Berths=1
1 Berths reserved for first person
Avaliable Berths=0
Sorry, no Berths.
12.Write a java program for Thread Deadlock.
Class BookTicket extends Thread
Object train,comp;
BookTicket(object train, object comp)
{
this.train=train;
this.comp=comp;
}
Public void run()
{
Synchronized(train)
{
System.out.println(“BookTicket locked on train”);
try{
Thread.sleep(150);
}catech(InterruptedException e){}
System.out.println(“BookTicket now waiting to lock on compartment…”);
Synchronized(comp)
{
System.out.println(BookTicket locked on compartment”);
}
}
}
class CancelTicket extends Thread
{
Object train, comp;
cancelTicket(object train, object comp)
{
This.train=train;
This.comp=comp;
}
public void run()
{
Synchronized(comp)
{
System.out.println(“CancelTicket locked on compartment”);
try{
Thread.sleep(200);
}Catch(InterruptedException e){}
System.out.println(“CancelTicket now waiting to lock on train…”);
Synchronized(train)
{
System.out.println(“CancelTicket locked on train”);
}
}
}
}
class DeadLock
{
public static void main(String args[]) throws Exception
{
object train = new object();
object compartment = new object();
BookTicket obj1 = new BookTicket (train, compartment);
CancelTicket obj2 = new CancelTicket (train, compartment);
Thread t1= new Thread(obj1);
Thread t2= new Thread(obj2);
t1.start();
t2.start();
}
}
Output:
C:\> javac DeadLock.java
C:\> java DeadLock
BookTicket locked on train
CancelTicket locked on compartment
BookTicket now waiting to lock on compartment…
CancelTicket now waiting to lock on train…
13.Write a java program for creating Thread Groups.
class TGroups
{
public static void main(String args[]) throws Exception
{
Reservation res = new Reservation();
Cncellation can = new Cancellation();
ThreadGroup tg = new ThreadGroup(“First Group”);
Thread t1 = new Thread(tg, res, “First thread”);
Thread t2 = new Thread(tg, res, “Second thread”);
ThreadGroup tg1 = new ThreadGroup(tg, “Second Group”);
Thread t3 = new Thread(tg1, can, “Third thread”);
Thread t4 = new Thread(tg1, can, “Fourth thread”);
System.out.println(“parent of tg1= “+tg1.getparent());
Tg1.setMaxpriority(7);
System.out.println(“Thread group of t1= “+ t1.getThreadGroup());
System.out.println(“Thread group of t3= “+ t3.getThreadGroup());
t1.start();
t2.start();
t3.start();
t4.start();
System.out.println(“No of threads active in tg = “+tg.activeCount());
}
}
class Reservation extends Thread
{
public void run()
{ System.out.println(“ I am reservation thread”); }
}
class Cancellation extends Thread
{
public void run()
{
System.out,println(“ I am cancellation thread”);
}
}
Output:
C:\> javac TGroups.java
C:\> java TGroups
Parent of tg1= java.lang.ThreadGroup[name=First Group,maxpri= 10]
Thread group of t1= java.lang.ThreadGroup[name=First Group,maxpri=10]
Thread group of t3= java.lang.ThreadGroup[name=Second Group,maxpri=7]
No of threads active in tg= 4
I am reservation thread
I am reservation thread
I am cancellation thread
I am cancellation thread
14.Write a java program for animates the things using threads.
import java.awt.*;
class Banner extends Frame implements Runnable
{
String str=”Dream tech publications”;
Banner()
{
setLayout(null);
setBackground(color.cyan);
setForeground(color.red);
}
Public void paint(Graphics g)
{
Font f=new Font(“courier”,Font.BOLD,40);
g.setFont(f);
g.drawString(str,10,100):
}
public void run()
{
For(;;){
Repaint();
try{
Thread.sleep(400);
}
catch(InterruptedException ie){}
char ch=str.CharAt(0);
str=str.substring(1, str.length());
str=str+ch;
}
}
public static void main(String args[])
{
Banner b=new Banner();
b.setSize(400,400);
b.setTitle(“My banner”);
b.setVisible(true);
Thread t=new Thread(b);
t.start();
}
}
Output:
C:\>javac Banner.java
C:\>java Banner
15.Write a java program for creating a frame and close it is using Window Adapter
class.
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
public static void main(String args[])
{
MyFrame f=new MyFrame();
f.setTitle(“My AWT frame”);
f.setSize(300,250);
f.setVisible(true);
f.addwindowListener(new Myclass());
}
}
class Myclass extends windowAdapter
{
public void windowClosing(windowEvent e)
{
System.exit(0);
}
}
Output:
C:\>javac MyFrame.java
C:\>java MyFrame
CLICK ON CLOSE BUTTON, THE FRAME CLOSES
16.Write a java program for drawing a smiling face in a frame with filled colors.
import java.awt.*;
import java.awt.event.*;
class Draw2 extends Frame
{
this.addwindowListener(new windowAdepter()
{
public void windowClosing(windowEvent e)
{
System.exit(0);}
});
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.fillRect(40,40,200,200);
g.setColor(Color.yellow);
g.filloval(90,70,80,80);
g.setColor(Color.black);
g.fillovel(110,95,5,5);
g.fillovel(145,95,5,5);
g.drawLine(130,95,130,115);
g.setColor(Color.red );
g.fillArc(113,115,35,20,0,-180);
}
public static void main(String args[])
{
Draw2 d=new Draw2();
d.setSize(400,400);
d.setTitle(“My drawing”);
d.setVisible(true);
}
}
Output:
C:\>javac Draw2.java
C:\>java Draw2
17.Write a java program to display an image in the frame and also in the title bar of the
frame.
import java.awt.*;
import java.awt.event.*;
class Images extends Frame
{
Static Image img;
Images()
{
img=ToolKit.getdefaultToolKit().getImage(“diamonds.gif”);
MediaTraker Track=new MediaTracker(this);
Track.addImage(img,0);
try{
track.waitForID(0);
}catch(InterruptedException ie){}
addwindowListener(new windowAdpter()
{
public void windowClosing(windowEvent we)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
g.drawImage(img,50,50,null);
}
public static void main(String args[])
{
Images i=new Images();
i.setSize(500,400);
i.setTitle(“My images”);
i.setIconImage(img);
i.setVisible(true);
}
}
Output:
C:\>javac Images.java
C:\>java Images
18 .Write a java program to compress or uncompress the data.
A) Compress:
import java.io.*;
import java.util.zip.*;
class Zip
{
public static void main(String args[])
{
FileInputStream fis=new FileInputStream(“file1”);
FileOutputSream fos=new FileOutputStream(“file2”);
DeflaterOutputStream dos=new DeflaterOutputStream(fos);
int data;
while((data=fis.read())!=-1)
dos.write(data);
fis.close();
dos.close();
}
}
Output:
C:\>javac Zip.java
C:\>java Zip
19.)Uncompress:
import java.io.*;
import java.util.zip.*;
class UnZip
{
public static void main(String args[])
FileInputStream fis=new FileInputStream(“file2”);
FileOutputStream fos=new FileOutputStream(“file3”);
InflaterInputStream iis=new InflaterInputStream(fis);
int data;
while((data=iis.read()) !=-1)
fos.write(data);
fos.close();
iis.close();
}
}
Output:
C:\>javac UnZip.java
C:\>java UnZip
20.Write a java program for Serialization and De-Serialization of objects.
A) Serialization:
Import java.io.*;
Import java.util.*;
class StoreObj
{
Public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in);
FileOuputStream fos=new FileOuputStream(“objfile”);
ObjectOuputStream oos=new ObjectOuputStream(fos);
System.out.println(“how many employees?”);
Int n=Intrger.parseInt(br.readLine());
For(int i=0;i<n;i++)
{
Employee e=new Employee();
e.getData();
oos.writeObject(e);
}
Oos.close();
}
}
Output:
C:\>javac StoreObj.java
C:\>java StoreObj
How many objects?2
Enter emp id:1001
Enter name:Hari
Enter salary:10250.50
Enter date of joining:
Enter day:10
Enter month:7
Enter year:2017
Enter emp id:1002
Enter name:Teja
Enter salary:15000.00
Enter date of joining:
Enter day:2
Enter month:6
Enter year:2018