Java Lab Solution
Program 1: Print Message.
class firstprogram
{
public static void main(String arg[])
{
[Link]("this is java's first program");
}
}
Execution steps:
Javac [Link] (File name)
Java firstprogram (class name)
Program 2: WAP to find the average,sum,min and max of the N numbers Using user
Input. import [Link].*; class Average{ public static void main(String args[])
{ Scanner sc= new Scanner([Link]);// to take user input
int choice; int a=0,min=0,max=0,x; int n
=[Link];
[Link]("1-sum");
[Link]("2-Average");
[Link]("3-Minimum");
[Link]("4-Maximum");
[Link]("Enter Ur Choice : ");
choice=[Link]();
for(int i=0;i<n;i++){
a+=[Link](args[i]);//to convert string into Integer
}
switch(choice)
{
case 1 :[Link]("The sum is : "+a);
break;
case 2 :[Link]("The Average is : "+a/n);
break;
case 3 :for(int i=0;i<n-1;i++) { x=[Link](args[i]);
if(x<[Link](args[i+1])) min=x;
else min=[Link](args[i+1]);
}
[Link]("The minimum is : "+min);
break;
case 4 :
for(int i=0;i<n-1;i++) { x=[Link](args[i]);
if(x>[Link](args[i+1]))
max=x;
else
max=[Link](args[i+1]);
}
[Link]("The maximum is : "+max);
break;
}
}
}
Program 3: WAP to Demonstrate Type Casting.
class typecast
{
public static void main(String args[])
{
byte h=127;
int a=300;
float a1=12.222f;
float g;
short b=200; long
c=999999; float e=345.89F;
double f=45645.78222222222222;
g= (float)f;
[Link]("short b ="+g);
[Link]("short b ="+b);
[Link]("long c ="+c);
[Link]("float e="+e);
[Link]("double f="+f);
[Link]("short b="+b);
[Link]("short to byte "+(byte)b);
[Link]("int to byte "+(byte)a);
[Link]("int to float"+(float)a);
[Link]("long to byte "+(byte)c);
[Link]("double to long "+(long)f);
[Link]("double to int "+(int)f);
[Link]("double to byte "+(byte)f);
[Link]("double to short "+(short)f);
[Link]("double to float "+(float)f);
[Link]("float to int "+(int)e);
[Link]("float to byte "+(byte)e);
[Link]("float to short "+(short)e);
[Link]("float to long "+(long)e);
[Link]("float to double ="+(double)e);
[Link]("long to int"+(int)c);
[Link]("byte to int ="+(int)h);
}
}
Program 4: WAP to Test the Prime num.
import [Link].*; class prime
{
public static void main(String args[])
{ int flag,x,i;
flag=0;
int a[]=new int[7];
for(x=0;x<[Link];x++)
{
a[x]=[Link](args[x]);
for(i=2;i<(a[x]/2);i++)
{
if((a[x]%i)==0)
{
break;
}
else flag=1;
}
if(flag==1)
[Link](a[x]+" is a prime no "); else
[Link](a[x]+" is not a prime no ");
flag=0;
}
}
}
Program 5: WAP to find out the HCF and LCF.
import [Link].*; class
hcf
{
public static void main(String args[])
{
int a,b;
Scanner sc= new Scanner([Link]);
[Link]("Enter two nos :");
a=[Link](); b=[Link]();
int big; int small;
if(a>b)
{
big=a;
small=b;
}
else
{
big=b;
small=a;
}
for(int i=1;i<=big;i++)
{
if(((big*i)%small)==0)
{
int lcm=big*i;
[Link]("The least common multiple is "+(lcm));
break;
}
}
int temp=1; while(temp!=0)
{
temp=big%small;
if(temp==0)
{
[Link]("GCD is "+small);
} else
{
big=small;
small=temp;} }}}
Program 6: WAP to calculate the Simple Interest and Input by the user.
import [Link].*; class
si
{
int p,t;
float si,r;
public si()
{
r=0;
p=0;
}
public void getdata()
{
Scanner sc =new Scanner([Link]);
[Link]("Enter principle : "); p=[Link]();
[Link]("Enter rate : ");
r=[Link]();
[Link]("Enter time period : ");
t=[Link]();
}
public void cal()
{
si=(p*r*t)/100;
}
public void display()
{
[Link]("Principle : Rs"+p); [Link]("Rate :
"+r);
[Link]("Time period : "+t);
[Link]("Simple Interest : Rs"+si);
}
public static void main(String args[])
{
si s = new si();
[Link]();
[Link]();
[Link]();
}
}
Program 7:
WAP to create a Simple class to find out the Area and perimeter of rectangle and box
using super and this keyword . class rect
{
int l,b;
public rect(int l,int b)
{ this.l=l;
this.b=b;
}
public int area()
{
return l*b;
}
}
class box extends rect
{
int d;
public box(int l,int b,int d)
{
super(l,b);
this.d=d;
}
public int volume()
{
int vol = area()*d;
return vol;
}
public static void main(String args[])
{ int vol ,area;
[Link]("derived object in derived reference");
rect r= new rect(10,20);
area=[Link]();
[Link]("area is "+area+"\n");
[Link]("base object in base reference");
box b = new box(10,20,30);
vol=[Link]();
area=[Link]();
[Link]("area is "+area);
[Link]("volume is "+vol+"\n");
[Link]("derived object in base reference");
rect b1= new box(10,90,70); area =
[Link]();
//vol=[Link](); as with refernce of base class we can't call derived's
method
[Link]("area is "+area);
//as super class doesn't knw abt the base class but reference can be assigned
/*[Link]("base object in derived reference");
box b2=(new rect (10,20)); vol
= [Link]();
[Link]("area is "+area);*/
r=b;
[Link]([Link]());
[Link]([Link]());
}
}
Program 8:
WAP to design a class account using the inheritance and static that show all function
of bank(withrowal,deposite) and generate account number dyanamically.
import [Link].*;
class bank
{ static int acc_no =10001; float
amt;
public void display()
{
[Link]("Account no :"+acc_no );
[Link]("Current Amount :"+amt );
}
public bank()
{
amt=1000;
[Link]("Ur account no is "+acc_no);
acc_no++;
}
public void getamt()
{
[Link]("Current balance :"+amt);
}
public void withdraw(float x)
{
if(amt==1000 || amt<=x )
{
[Link]("Sorry u can't withdraw");
}
else
{
amt=amt-x;
[Link]("amount withdrawn :"+x);
[Link]("After withdrawl");
getamt();
}
}
public void deposit(float x)
{
if(x==0.0)
[Link]("OOPS 0 can't be deposited");
else {
amt+=x;
[Link]("After deposition");
getamt();}
}
public static void main(String args[])
{ Scanner sc = new
Scanner([Link]); bank b1 = new bank();
[Link](0);
[Link](120.5f); [Link]();
[Link]("\n");
bank b2 = new bank();
[Link](1000.0f);
[Link](150.5f);
}
}
Program 9: WAP to design a class Shape (Implement Runtime polymorphim) using
abstract Methods and Classes.
class AbstractDemo1
{ public static void main(String args[])
{
Shape shape; Rectangle r =
new Rectangle();
[Link](40,20);
shape = r;
[Link]([Link]());
[Link]([Link]());
}
}
abstract class Shape
{
void someMethod()
{
[Link]("This is some method");
}
abstract float getArea();
abstract float getPerimeter();
}
class Square extends Shape
{
float side;
Square()
{
side = 0;
}
Square(float side)
{
[Link] = side;
}
void setSide(float side)
{
[Link] = side;
}
float getArea()
{
return side * side;
}
float getPerimeter()
{
return 4 * side;
}
} import
[Link].*; class
MyCircle extends
MyShape
{
private float radius;
static float pi;
static
{
pi = 22 / 7.0f;
}
MyCircle()
{
super("circle");
radius = 0;
}
MyCircle(float radius)
{
super("circle");
[Link] = radius;
}
void setDimensions(float radius)
{
[Link] = radius;
}
void showDimensions()
{
[Link]("radius : " + radius);
}
float getArea()
{
return radius * radius * pi;
}
}
class Rectangle extends Shape
{ private float length;
private float breadth;
Rectangle()
{
length = breadth = 0;
}
Rectangle(float length, float breadth)
{
setDimensions(length, breadth);
}
void setDimensions(float length, float breadth)
{
[Link] = length;
[Link] = breadth;
}
float getArea()
{
return length * breadth;
}
float getPerimeter()
{
return (2 * (length + breadth));
}
}
Program 10:WAP to design a String class that perform String Method(Equal, Reverse
the string, change case, trim etc. )
public class StringDemo
{
public static void main(String args[])
{
String str = "This is some sample String with some words that have been
repeated some times";
[Link]("Total no. of characters : " + [Link]());
[Link]("To Upper Case : " + [Link]());
[Link]("To Lower Case : " + [Link]());
[Link]("Original String : " + str);
[Link]([Link](8));
[Link]([Link](8,19));
[Link]([Link]("some"));
String s = " " + str + " ";
[Link](s);
[Link]("[" + [Link]() + "]");
[Link]([Link]("s","$$##"));
String sh = "parth is a good boy";
[Link](sh + " -> " + new StringBuffer(sh).reverse());
}}
Program 11: WAP to handle the Exception using try and multiple catch block.
class exception
{
public static void main(String args[]){
try{ int
d=42; int
a =0; int
c=d/a;
}
catch(ArithmeticException e){
[Link]("Division by zero error");
}
}
}
Other Example:
public class ExceptionHandling
{
public static void main(String args[])
{
String num[]={"123","456","abc","789"};
int sum=0;
int i;
for(i=0;i<=[Link];i++)
{
try{
sum+=[Link](num[i]);
}
catch(NumberFormatException e)
{ [Link]("NUMBER FORMAT ERROR");
}
catch(ArrayIndexOutOfBoundsException e)
{[Link]("ARRAY ERROR");
}
finally
{ [Link]("i = "+i);
}
}
[Link]("sum is"+sum); }
Program 12:WAP that Implement the Nested try Statements.
class NestedTry
{
public static void main(String args[])
{ int a=[Link];
try{
int d=42/a;
try
{
if(a==1){
int c= a/(a-a);}
if(a==2)
{
int c[]={2,3,4};
c[5]=90;
}
}
catch(ArrayIndexOutOfBoundsException e)
{[Link]();
}
}
catch(ArithmeticException e)
{
[Link]();
}
}
}
Program 13:WAP that Implement Throw and Throws.
class ThrowDemo
{
ThrowDemo()
{
try
{ throw new NullPointerException();
}
catch(NullPointerException e)
{
[Link]("Caught in constructor");
throw e;
}
}
public static void main(String args[])
{
try{
ThrowDemo td=new ThrowDemo();
}
catch(NullPointerException e)
{
[Link]("Caught in Main");
}
}
}
class ThrowsDemo
{
ThrowsDemo() throws NullPointerException
{ [Link]("in constructor");
throw new NullPointerException();
} public static void
main(String args[])
{
try{
ThrowsDemo td=new ThrowsDemo();
}
catch(NullPointerException e)
{
[Link]("Caught in Main");
}
}
}
Program 14: WAP that Implement Custom Exception.
import [Link].*;
class MyException extends Exception
{
private int e;
MyException (int a )
{ e=a; }
public String
toString()
{
return ("Error in entry"+e);
}
}
public class mine
{ public void compute(int a) throws MyException
{
int age=a;
if(age>150)
throw new MyException (age);
[Link]("COrrect age");
}
public static void main(String args[])
{
mine m=new mine();
try{
[Link](1);
[Link](789);
}
catch(MyException e)
{
[Link](e);
}
}
}
Program 15: WAP to Create a package that access the member of external class as well
as same package.
package pack; class
base
{
public static void main(String arg[])
{
[Link]("Base class(p1)"); p1 w=new
p1();
//w.f1();
[Link]("Derived class(p2)"); p2 x=new p2();
// x.f2();
[Link]("Simple class(p3)"); p3
y=new p3();
// y.f3();
}
}
package pack; public
class p1
{
int a=1;
public int b=2;
private int c=3;
protected int d=4;
public p1()
{
[Link]("Value of a="+a);
[Link]("Value of b="+b);
[Link]("Value of c="+c);
[Link]("Value of d="+d);
}
}
package pack; class
p2 extends p1
{
p2()
{
[Link]("Value of a="+a);
[Link]("Value of b="+b);
//[Link]("Value of c="+c);
[Link]("Value of d="+d);
}
}
package pack; class
p3
{
p1 p=new p1();
p3()
{
[Link]("Value of a="+(p.a));
[Link]("Value of b="+(p.b));
//[Link]("Value of c="+(p.c));
[Link]("Value of d="+(p.d));
}
}
package pack1;
class simple extends pack.p1
{
public simple()
{
// [Link]("Value of a="+a);
[Link]("Value of b="+b);
// [Link]("Value of c="+c);
[Link]("Value of d="+d);
}
}
package pack1; class
s2
{
public static void main(String arg[])
{
simple s=new simple();
s1 p=new s1();
}
}
package pack1; class
s1
{
s1()
{
pack.p1 z=new pack.p1();
// [Link]("Value of a="+(z.a));
[Link]("Value of b="+(z.b));
// [Link]("Value of c="+(z.c));
// [Link]("Value of d="+(z.d));
}
}
Program16: WAP that show the partial implementation of Interface.(calculation of
Salary of Employee).
import [Link].*;
interface salary
{
int getsal();
}
abstract class employee
{ String name; int
age; String
sex;
int sal;
employee(String name,int age,String sex,int sal)
{
[Link]=name;
[Link]=age; [Link]=sex;
[Link]=sal;
}
abstract void display();
}
class labour extends employee implements salary
{ int wage;
int hrs;
labour(String name,int age,String sex,int sal,int hrs)
{
super(name,age,sex, sal);
[Link]=hrs;
}
public int getsal()
{
wage=sal*hrs;
return wage;
}
void display()
{
[Link]("name :"+name);
[Link]("Age :"+age);
[Link]("Sex :"+sex);
[Link]("salary : Rs"+sal);
[Link]("Hours worked :"+hrs);
[Link]("Wage of the daily labour :Rs"+getsal());
}
}
class staff extends employee implements salary
{ int hra,da,ta;
staff(String name,int age,String sex,int sal,
int hra,int da,int ta)
{
super(name,age,sex, sal);
[Link]=da; [Link]=ta;
[Link]=hra;
}
public int getsal()
{
int wage=sal+ta+da+hra;
return wage;
}
void display()
{
[Link]("name :"+name);
[Link]("Age :"+age);
[Link]("Sex :"+sex);
[Link](" basic salary :Rs"+sal);
[Link]("Daily allowance : Rs"+da);
[Link]("Travel allowance : Rs"+ta);
[Link]("Household allowance : Rs"+hra);
[Link]("total salary :Rs"+getsal());
}
} class
sal
{
public static void main(String args[])
{ Scanner sc= new Scanner ([Link]);
int ch,da,ta,hra,sal,hrs,age;
String name;
String sex;
[Link]("Enter ur choice for salary calculation");
[Link]("1-labour");
[Link]("2-Staff");
ch=[Link]();
switch(ch)
{
case 1 :
[Link]("Enter the following for a lobour");
[Link]("Name :");
name=[Link]();
[Link]("age :");
age=[Link]();
[Link]("Sex : ");
sex=[Link]();
[Link]("salary :");
sal=[Link]();
[Link]("daily working hours :");
hrs=[Link]();
labour l = new labour(name,age,sex,sal,hrs);
[Link]();
break;
case 2 :
[Link]("Enter the following for a Staff");
[Link]("Name :");
name=[Link]();
[Link]("age :");
age=[Link]();
[Link]("Sex : ");
sex=[Link]();
[Link]("salary : ");
sal=[Link]();
[Link]("daily allowance :");
da=[Link]();
[Link]("travel allowance :");
ta=[Link]();
[Link]("household allowance :");
hra=[Link]();
staff s = new staff(name,age,sex,sal,hra,da,ta);
[Link]();
break;
}
}
Program 17:
WAP to create Arithmetic Math Calculator Using Applet Class ant Event Handling.
/*<APPLET CODE ="[Link]" WIDTH =300 HEIGHT =400>
</APPLET>*/
import [Link].*;
import [Link].*; import [Link];
public class calc extends Applet implements ActionListener
{ Button add,sub,divide,multi;
Label result,no1,no2;
TextField tf,ip1,ip2;
Panel p1,p2,p3;
public void init()
{
add=new Button("ADD"); sub=new
Button("SUBTRACT");
divide=new Button("DIVIDE");
multi=new Button("MULTIPLY");
result = new Label("Result = ");
no1=new Label ("NUMBER 1:");
no2=new Label ("NUMBER 2:");
tf=new TextField(20); ip1=new
TextField(10); ip2=new TextField(10);
p1=new Panel();
p2=new Panel(); p3=new
Panel();
[Link](false);
[Link](20,40); [Link](20,40);
[Link](20,40);
[Link](this);
[Link](this); [Link](this);
[Link](this);
setLayout(new FlowLayout());
[Link](no1);
[Link](ip1); [Link](no2);
[Link](ip2); [Link](add);
[Link](sub); [Link](divide);
[Link](multi);
[Link](result);
[Link](tf); add(p1);
add(p2);
add(p3);
setSize(400,200);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{ int a,b;
int result; a
=[Link]([Link]());
b=[Link]([Link]());
if([Link]()==add)
{[Link]("ADD");
result=(a+b); [Link]("Addition
:"+[Link](result));
}
if([Link]()==sub
) { result=(ab);
[Link]("Sub
traction :
"+[Link](resu
lt));
}
if([Link]()==multi)
{
result=(a*b);
[Link]("Multiplication : "+[Link](result));
}
if([Link]()==divide)
{
try{
if(b==0)
{
result=(a/b);
[Link]("Division :"+[Link](result));
}
}
catch(ArithmeticException ae )
{
[Link]("Division can't be performed");
}
}
}
}
Program 18: WAP to Draw the line, Rectangle, oval, text etc using the graphics method.
/*<applet code = "[Link]" width = "500" height = "300"> </applet>*/
import [Link]; import
[Link].*;
public class AppletDemo extends Applet
{ public void init()
{setBackground([Link]);
} public void paint(Graphics
g) {
Font f=new Font("TIMES NEW ROMAN ",[Link],32);
[Link](f);
[Link]([Link]);
[Link]("WELCOME TO APPLET ",30,30);
[Link](60,60,150,150);
[Link]([Link]);
[Link](90,100,20,20);
[Link](160,100,20,20);
[Link]([Link]);
[Link](120,150,150,150);
[Link](120,150,140,130);
[Link](90,130,90,60,0,-180);
}
}
Program 19: WAP to create a frame Window Using Frame Class.
public class AWT1
{
public static void main(String args[])
{
MyFrame mf = new MyFrame();
}
}
import [Link].*;
/*
class MyWindowListener implements WindowListener
{
public void windowActivated(WindowEvent we){}
public void windowDeactivated(WindowEvent we){}
public void windowOpened(WindowEvent we){} public
void windowClosed(WindowEvent we){} public void
windowIconified(WindowEvent we){}
public void windowDeiconified(WindowEvent we){}
public void windowClosing(WindowEvent we)
{
[Link](0);
}
} */
class MyWindowAdapter extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
}
import [Link].*;
import [Link].*;
class MyFrame extends Frame //implements WindowListener
{
MyFrame()
{
super("Sample Java Frame");
//MyWindowListener mwl = new MyWindowListener();
//MyWindowAdapter mwa = new MyWindowAdapter();
//addWindowListener(mwa);
addWindowListener(new MyWindowAdapter());
//addWindowListener(this);
setSize(400,300);
setResizable(true);
//setUndecorated(true);
setVisible(true);
}
}
Program 19: WAP to create UI component on Frame Window Using Frame Class.
public class AWT1
{
public static void main(String args[])
{
MyFrame mf = new MyFrame();
}
}
import [Link].*;
class MyWindowAdapter extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
}
import [Link].*;
import [Link].*;
class MyFrame extends Frame
{
Label lbl, l2;
TextField t1;
MyFrame()
{
super("Sample Java Frame");
addWindowListener(new MyWindowListener());
setSize(500,400);
addControls();
setVisible(true);
}
private void addControls()
{
setLayout(null);
lbl = new Label("Sample Label",[Link]);
[Link](250,22);
[Link](10,40);
//[Link]("This is the text in the label control");
[Link]([Link]);
[Link]([Link]);
//[Link]([Link]);
add(lbl);
l2 = new Label([Link]());
[Link]([Link]());
[Link]([Link]().x, [Link]().y + 30);
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
//[Link](false);
add(l2);
t1 = new TextField("This is some initial text in the text box control");
[Link](200,22); [Link](10,160);
[Link]('^');
if ([Link]())
{
[Link]("Input has been masked");
[Link]("Mask character is " + [Link]());
}
add(t1);
[Link](false);
// [Link](false);
}
}
Program 20: WAP to implement ListBox.
public class AWT1
{ public static void main(String args[])
{
MyFrame mf = new MyFrame();
}
}
import [Link].*;
import [Link].*;
public class MyFrame extends Frame implements ActionListener
{
List lst;
Button btn;
MyFrame()
{
super("Sample Java Frame");
addWindowListener(new MyWindowAdapter()); setSize(500,400);
addControls();
setVisible(true);
}
private void addControls()
{
setLayout(null);
lst = new List();
[Link](30,50);
[Link](200,300);
[Link](true);
add(lst);
[Link]("sfsdf");
[Link]("55656"); [Link]("dfgdfg");
[Link]("sfsdf"); [Link]("cvb");
[Link]("sfcvbcbcvbcvbsdf");
[Link]("bmmbnm");
[Link]("ioouo");
[Link]("qeqwe");
[Link](".m,.m,.");
btn = new Button("Click Me");
[Link](this); [Link](100,24);
[Link](250,50);
add(btn);
public void actionPerformed(ActionEvent ae)
{
[Link]("Total Selected Items : " +
[Link]().length);
String aItem[] = [Link]();
int i;
for (i=0;i<[Link];i++)
[Link](aItem[i]);
}
}
import [Link].*;
class MyWindowAdapter extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
}