“SIMPLE JAVA PROGRAM”
AIM:
To write a java program to create one or more classes.
ALGORITHM:
Start the program
Declare and Initialize the variable.
Create a class Box mybox
Print the volume of the box
Stop the program.
PROGRAM:
class Box
double width;
double height;
double depth;
classBoxDemo
public static void main(String args[])
Box mybox = new Box();
Double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
1
System.out.println("Volume is " + vol);
OUTPUT:
RESULT:
Thus, the required java program has been typed, executed and verified successfully.
2
“EXCEPTION HANDLING”
AIM:
To write a java program to demonstrate the exception handling.
ALGORITHM:
Start the program
Declare and initialize the variables
Create a class exc2 with try catch block
Print the exception if it thrown
Stop the program.
PROGRAM:
class Exc2
public static void main(String args[])
int d, a;
try
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
catch (ArithmeticException e)
System.out.println("Division by zero.");
System.out.println("After catch statement.");
3
}
OUTPUT:
RESULT:
Thus, the required java program has been typed, executed and verified successfully.
4
“SINGLE INHERITANCE”
AIM:
To write a java program to perform single inheritance.
ALGORITHM:
Start the program
Declare and initialize the variables.
Create a base class employee
Create a derived class department from employee class
Print the result
Stop the program.
PROGRAM:
class employee
privateinteno;
private String ename;
public void setemp(intno,String name)
eno = no;
ename = name;
public void putemp()
System.out.println("Empno : " + eno);
System.out.println("Ename : " + ename);
class department extends employee
5
{
privateintdno;
private String dname;
public void setdept(intno,String name)
dno = no;
dname = name;
public void putdept()
System.out.println("Deptno : " + dno);
System.out.println("Deptname : " + dname);
public static void main(String args[])
department d = new department();
d.setemp(100,"aaaa");
d.setdept(20,"Sales");
d.putemp();
d.putdept();
6
OUTPUT:
RESULT:
Thus, the required java program has been typed, executed and verified successfully.
7
“MULTIPLE INHERITANCE – USING INTERFACE”
AIM:
To write a java program to perform multiple inheritance using interface.
ALGORITHM:
Start the program
Declare and initialize the variables.
Create a interface exam and class student.
Create a derived class which extends the student and implements the interface exam.
Print the result
Stop the program
PROGRAM:
importjava.lang.*;
import java.io.*;
interface Exam
voidpercent_cal();
class Student
String name;
int roll_no,mark1,mark2;
Student(String n, int r, int m1, int m2)
name=n;
roll_no=r;
mark1=m1;
mark2=m2;
8
}
void display()
System.out.println ("Name of Student: "+name);
System.out.println ("Roll No. of Student: "+roll_no);
System.out.println ("Marks of Subject 1: "+mark1);
System.out.println ("Marks of Subject 2: "+mark2);
class Result extends Student implements Exam
Result(String n, int r, int m1, int m2)
super(n,r,m1,m2);
public void percent_cal()
int total=(mark1+mark2);
float percent=total*100/200;
System.out.println ("Percentage: "+percent+"%");
void display()
super.display();
9
}
class Multiple
public static void main(String args[])
Result R = new Result("Ra.one",12,93,84);
R.display();
R.percent_cal();
OUTPUT:
RESULT:
Thus, the required java program has been typed, executed and verified successfully.
10
“MULTI-LEVEL INHERITANCE”
AIM:
To write a java program to perform multi-level inheritance.
ALGORITHM:
Start the program
Declare and initialize the variables.
Create a class account
Create a derived class sav-acc from base class account
Create a another derived class account details from sav-acc
Print the result
Stop the program.
PROGRAM:
importjava.lang.*;
import java.io.*;
class Account
String cust_name;
intacc_no;
Account(String a, int b)
cust_name=a;
acc_no=b;
void display()
System.out.println ("Customer Name: "+cust_name);
System.out.println ("Account No: "+acc_no);
11
}
classSaving_Acc extends Account
intmin_bal,saving_bal;
Saving_Acc(String a, int b, int c, int d)
super(a,b);
min_bal=c;
saving_bal=d;
void display()
super.display();
System.out.println ("Minimum Balance: "+min_bal);
System.out.println ("Saving Balance: "+saving_bal);
classAcct_Details extends Saving_Acc
int deposits, withdrawals;
Acct_Details(String a, int b, int c, int d, int e, int f)
super(a,b,c,d);
deposits=e;
12
withdrawals=f;
void display()
super.display();
System.out.println ("Deposit: "+deposits);
System.out.println ("Withdrawals: "+withdrawals);
class Multilevel
public static void main(String args[])
Acct_Details A = new Acct_Details("Pa.one",666,1000,5000,500,9000);
A.display();
13
OUTPUT:
RESULT:
Thus, the required java program has been typed, executed and verified successfully.
14
“HIERARCHICAL INHERITANCE”
AIM:
To write a java program to perform hierarchical inheritance.
ALGORITHM:
Start the program
Declare and initialize the variables.
Create a class one
Create a derived class two from base class one
Create a another derived class three from base class one
Print the result.
Stop the program.
PROGRAM:
class one //Super class
int x=10,y=20;
void display()
System.out.println("This is the method in class one");
System.out.println("Value of X= "+x);
System.out.println("Value of Y= "+y);
class two extends one //Sub class -1 of class one
void add()
System.out.println("This is the method in class two");
15
System.out.println("X+Y= "+(x+y));
class three extends one//Sub class-2 of class one
voidmul()
System.out.println("This is the method in class three");
System.out.println("X*Y= "+(x*y));
classHier
public static void main(String args[])
two t1=new two(); //Object of class two
three t2=new three(); //Object of class three
t1.display(); //Calling method of class one using class two object
t1.add(); //Calling method of class two
t2.mul(); //Calling method of class three
16
OUTPUT:
RESULT:
Thus, the required java program has been typed, executed and verified successfully.
17
“HYBRID INHERITANCE”
AIM:
To write a java program to perform hybrid inheritance.
ALGORITHM:
Start the program
Declare and initialize the variables.
Create a class a
Create a derived class b from base class a
Create a derived class c from base class a
Create another derived class final from c.
Print the result.
Stop the program.
PROGRAM:
class a
inti,j;
void show()
System.out.println("value of i is"+i);
System.out.println("value of j is"+j);
class b extends a
void sum()
int k=i+j;
System.out.println("value of k is "+k);
18
}
class c extends a
void fact()
{ int j=1;
for(int a=1;a<=i;a++)
j=j*a;
System.out.println(j);
class Final extends c
public static void main(String arg[])
aobj=new a();
obj.i=10;
obj.j=20;
obj.show();
b obj1=new b();
obj1.i=100;
obj1.j=200;
obj1.sum();
19
c obj2=new c();
obj2.i=5;
obj2.fact();
OUTPUT:
RESULT:
Thus, the required java program has been typed, executed and verified successfully.
20
“PACKAGES”
AIM:
To write a java program to create a user defined packages.
ALGORITHM:
Start the program
Declare and initialize the variables
Create a package p1
Create a class c1 under package p1
After compiling the program, put the class file into the folder p1
Run the program
Print the result
Stop the program.
PROGRAM:
package p1;
class c1
public void m1()
System.out.println("Method m1 of Class c1");
public static void main(String args[]){
c1obj = new c1();
obj.m1();
21
OUTPUT:
RESULT:
Thus, the required java program has been typed, executed and verified successfully.
22
“INTERFACES”
AIM:
To write a java program to demonstrate the interfaces.
ALGORITHM:
Start the program
Declare and initialize the variables
Create an interface call back
Create a implementation client for that interface
Run both interface and implementation program
Print the result
Stop the program.
PROGRAM:
Interface program:
interface Callback {
void callback(intparam);
Implementation program:
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
Program that uses the above interface:
classTestIface {
public static void main(String args[]) {
Callback c = new Client();
23
c.callback(42);
OUTPUT:
RESULT:
Thus, the required java program has been typed, executed and verified successfully.
24
“EVENT HANDLING”
AIM:
To write a java program to demonstrate the event handling.
ALGORITHM:
Start the program
Declare and initialize the variables
Create a class key which implements the key listener
Create a html code with the key.class
Compile the java code
Run in an applet viewer
Stop the program
PROGRAM:
Java program:
importjava.awt.*;
importjava.awt.event.*;
importjava.applet.*;
public class Key extends Applet
implementsKeyListener
int X=20,Y=30;
String msg="KeyEvents--->";
public void init()
addKeyListener(this);
requestFocus();
setBackground(Color.green);
setForeground(Color.blue);
25
}
public void keyPressed(KeyEvent k)
showStatus("KeyDown");
int key=k.getKeyCode();
switch(key)
caseKeyEvent.VK_UP:
showStatus("Move to Up");
break;
caseKeyEvent.VK_DOWN:
showStatus("Move to Down");
break;
caseKeyEvent.VK_LEFT:
showStatus("Move to Left");
break;
caseKeyEvent.VK_RIGHT:
showStatus("Move to Right");
break;
repaint();
public void keyReleased(KeyEvent k)
showStatus("Key Up");
26
}
public void keyTyped(KeyEvent k)
msg+=k.getKeyChar();
repaint();
public void paint(Graphics g)
g.drawString(msg,X,Y);
Html code:
<html>
<applet code="Key.class" width=300 height=400>
</applet>
</html>
27
OUTPUT:
RESULT:
Thus, the required java program has been typed, executed and verified successfully.
28
“FILE HANDLING”
AIM:
To write a java program to demonstrate file handling.
ALGORITHM:
Start the program
Declare and initialize the variables
Create a class test
Within try catch block, create a text file abc.txt
Load the content into the file abc using fileoutputstream
Print the result
Stop the program.
PROGRAM:
import java.io.*;
class Test
public static void main(String args[])
try
FileOutputStreamfout=new FileOutputStream("abc.txt");
String s="sample program for file handling";
byte b[]=s.getBytes();
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e)
29
System.out.println(e);
OUTPUT:
RESULT:
Thus, the required java program has been typed, executed and verified successfully.
30
“THREAD HANDLING”
AIM:
To write a java program to demonstrate the thread handling.
ALGORITHM:
Start the program
Declare and initialize the variables
Create a class threadeg
Create a thread and rename it
Print the occurrence of thread after 1000 seconds delay using sleep method.
Print the result
Stop the program.
PROGRAM:
classthreadeg
public static void main(String args[])
Thread t = Thread.currentThread();
System.out.println(“Current thread: “ + t);
// change the name of the thread
t.setName(“My Thread”);
System.out.println(“After name change: “ + t);
try {
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000);
} catch (InterruptedException e) {
31
System.out.println(“Main thread interrupted”);
OUTPUT:
RESULT:
Thus, the required java program has been typed, executed and verified successfully.
32
“JAVA SWINGS”
AIM:
To write a java program to demonstrate java swings.
ALGORITHM:
Start the program
Declare and initialize the variables
Import all AWT,Swing packages.
Create a class eventdemo
Using JLabel, JFram, JButton, create various label, frame, and button.
Use applet viewer to print the result.
Stop the program.
PROGRAM:
importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;
classEventDemo {
JLabeljlab;
EventDemo() {
// Create a new JFrame container.
JFramejfrm = new JFrame("An Event Example");
// SpecifyFlowLayout for the layout manager.
jfrm.setLayout(new FlowLayout());
// Give the frame an initial size.
jfrm.setSize(220, 90);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Make two buttons.
33
JButtonjbtnAlpha = new JButton("Alpha");
JButtonjbtnBeta = new JButton("Beta");
// Add action listener for Alpha.
jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEventae) {
jlab.setText("Alpha was pressed.");
});
// Add action listener for Beta.
jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEventae) {
jlab.setText("Beta was pressed.");
});
// Add the buttons to the content pane.
jfrm.add(jbtnAlpha);
jfrm.add(jbtnBeta);
// Create a text-based label.
jlab = new JLabel("Press a button.");
// Add the label to the content pane.
jfrm.add(jlab);
jfrm.setVisible(true);
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
34
SwingUtilities.invokeLater(new Runnable() {
public void run() {
newEventDemo();
});
OUTPUT:
RESULT:
Thus, the required java program has been typed, executed and verified successfully.
35
“APPLET”
AIM:
To write a java program to demonstrate the applet concept.
ALGORITHM:
Start the program
Declare and initialize the variables
Create a class appleteg extends Applet
Use paint method to draw rectangles, lines, circles.
Create a html code with appleteg.class file
Use applet viewer to display the result.
Stop the program.
PROGRAM:
Java program:
importjava.awt.*;
importjava.applet.*;
public class appleteg extends Applet
public void paint(Graphics g)
for(int i=0;i<=250;i++)
Color c1=new Color(35-i,55-i,110-i);
g.setColor(c1);
g.drawRect(250+i,250+i,100+i,100+i);
g.drawOval(100+i,100+i,50+i,50+i);
g.drawLine(50+i,20+i,10+i,10+i);
36
}
Html code:
<html>
<applet code="appleteg.class" width=200 height=200>
</applet>
</html>
OUTPUT:
37
RESULT:
Thus, the required java program has been typed, executed and verified successfully.
38
“RMI”
AIM:
To write a java program to demonstrate RMI.
ALGORITHM:
Start the program
Declare and initialize the variables
Create an interface program with calint.java
Create an implementation program with calimp.java
Create an client program with calclient.java
Create a server program with calserver.java
Compile all interface, implementation, client and server program
And start the rmi registry
Run the server program and client program separately
Print the result
Stop the program.
PROGRAM:
Interface program:
importjava.rmi.*;
public interface calint extends Remote
public double add(double a,double b)throws RemoteException;
public double sub(double a,double b)throws RemoteException;
public double mul(double a,double b)throws RemoteException;
public double divide(double a,double b)throws RemoteException;
public double div(double a)throws RemoteException;
public double sign(double a)throws RemoteException;
public double sqroot(double a)throws RemoteException;
public double per(double a)throws RemoteException;
39
Implementation program:
importjava.rmi.*;
importjava.rmi.server.*;
importjava.math.*;
public class calimp extends UnicastRemoteObject implements calint
publiccalimp()throws RemoteException
{}
public double add(double a,double b)throws RemoteException
return a+b;
public double sub(double a,double b)throws RemoteException
return a-b;
public double mul(double a,double b)throws RemoteException
return a*b;
public double divide(double a,double b)throws RemoteException
return a/b;
public double div(double a)throws RemoteException
40
{
return 1/a;
public double per(double a)throws RemoteException
return a/100;
public double sqroot(double a)throws RemoteException
return Math.sqrt(a);
public double sign(double a)throws RemoteException
return -a;
Client program:
import java.rmi.*;
import java.awt.*;
import java.awt.event.*;
public class calclient extends Frame implements ActionListener
Static calint in;
staticTextField tf;
static Button no[],cmd[],op[];
41
Double a,b,c;
String o;
Public calclient()throws Exception
String url="rmi://localhost/calculator";
in=(calint)Naming.lookup(url);
public void addbutton()throws Exception
Panel p1=new Panel();
String str[]={"backspace","c","ce"};
cmd=new Button[3];
for(int i=0;i<str.length;i++)
cmd[i]=new Button(str[i]);
cmd[i].addActionListener(this);
p1.add(cmd[i]);
Panel p2=new Panel();
p2.setLayout(new GridLayout(0,5));
no=new Button[10];
for(int i=0;i<=9;i++)
no[i]=new Button(""+i);
no[i].addActionListener(this);
42
}
op=new Button[10];
String str1[]={"+","-","*","/",".","=","1/x","%","+/-","sqrt"};
for(int i=0;i<str1.length;i++)
op[i]=new Button(str1[i]);
op[i].addActionListener(this);
p2.add(no[0]);p2.add(no[1]);p2.add(no[2]);p2.add(no[3]);p2.add(no[4]);
p2.add(no[5]);p2.add(no[6]);p2.add(no[7]);p2.add(no[8]);p2.add(no[9]);
p2.add(op[0]);p2.add(op[1]);p2.add(op[2]);p2.add(op[3]);p2.add(op[4]);
p2.add(op[5]);p2.add(op[6]);p2.add(op[7]);p2.add(op[8]);p2.add(op[9]);
Panel p3=new Panel();
p3.setLayout(new BorderLayout());
p3.add(p1,BorderLayout.NORTH);
p3.add(p2,BorderLayout.CENTER);
tf=new TextField();
setLayout(new BorderLayout());
add(tf,BorderLayout.NORTH);
add(p3,BorderLayout.CENTER);
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent we)
System.exit(0);
43
}
});
public static void main(String args[])throws Exception
calclient cc=new calclient();
cc.addbutton();
cc.setSize(200,200);
cc.setVisible(true);
public void actionPerformed(ActionEvent ae)
Button bt=(Button)ae.getSource();
String str=bt.getLabel();
try
if(str=="backspace")
tf.setText(tf.getText().substring(0,tf.getText().length()-1));
else if(str=="c"||str=="ce")
tf.setText("");
44
else if(str=="+"||str=="-"||str=="*"||str=="/")
a=Double.parseDouble(tf.getText());
tf.setText("");
o=str;
else if(str=="=")
b=Double.parseDouble(tf.getText());
if(str=="+")
c=in.add(a,b);
else if(str=="-")
c=in.sub(a,b);
else if(str=="*")
c=in.mul(a,b);
else
c=in.divide(a,b);
tf.setText(Double.toString(c));
else if(str=="1/x")
a=Double.parseDouble(tf.getText());
c=in.div(a);
tf.setText(Double.toString(c));
45
else if(str=="%")
a=Double.parseDouble(tf.getText());
c=in.per(a);
tf.setText(Double.toString(c));
else if(str=="+/-")
a=Double.parseDouble(tf.getText());
c=in.sign(a);
tf.setText(Double.toString(c));
else if(str=="sqrt")
a=Double.parseDouble(tf.getText());
c=in.sqroot(a);
tf.setText(Double.toString(c));
else
tf.setText(tf.getText()+str);
catch(Exception e)
{}
46
}
Server program:
importjava.rmi.*;
public class calserver
public static void main(String args[])throws Exception
calint in=new calimp();
Naming.rebind("calculator",in);
System.out.println("server running");
OUTPUT:
47
RESULT:
Thus, the required java program has been typed, executed and verified successfully.
48
“JDBC”
AIM:
To write a java program to demonstrate the JDBC.
ALGORITHM:
Start the program
Create a ODBC connection by start->control panel-> administrative tools->data source->
add
Create java program to add, delete, insert, update the record in the database
Import the sql package into the program
Give connection by using:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url ="jdbc:odbc:AdventureWorks;";
Connection con =DriverManager.getConnection(url, userName, password);
Create a Statement to execute the sql command
Stop the program.
PROGRAM:
importjava.sql.*;
public class AdventureWorks
public static void main(String[] args)
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String userName ="sa";
String password ="sample";
String url ="jdbc:odbc:AdventureWorks;";
Connection con =DriverManager.getConnection(url, userName, password);
49
System.out.println("Connected");
Statement stmt =con.createStatement();
//String sql1="CREATE TABLE olap1department " + "(departmentid INTEGER
PRIMARY KEY," + "departmentnamenvarchar(50) NOT NULL)";
//String sql2="INSERT INTO olap1department SELECT DepartmentID,Name FROM
HumanResources.Department";
//String sql3="CREATE TABLE olap1shiftdetails " + "(shiftid INTEGER PRIMARY
KEY," + "name nvarchar(50) NOT NULL," + "starttimedatetime NOT NULL," +
"endtimedatetime NOT NULL)";
//String sql4="INSERT INTO olap1shiftdetails SELECT
ShiftID,Name,StartTime,EndTime FROM HumanResources.Shift";
//String sql5="CREATE TABLE olap1employeecontactdetails " + "(Contactid
INTEGER PRIMARY KEY," + "Title nvarchar(8)," + "FirstNamenvarchar(50) NOT NULL," +
"MiddleNamenvarchar(50)," + "LastNamenvarchar(50) NOT NULL," + "Emailidnvarchar(50),"
+ "PhoneNumbernvarchar(25))";
//String sql6="INSERT INTO olap1employeecontactdetails SELECT
ContactID,Title,FirstName,MiddleName,LastName,EmailAddress,Phone FROM
Person.Contact";
//String sql7="CREATE TABLE olap1employeedetails " + "(EmplyeeId INTEGER
PRIMARY KEY," + "NationalIdNumbernvarchar(15) NOT NULL," + "Contactid INTEGER
NOT NULL," + "LoginIdnvarchar(256) NOT NULL," + "Title nvarchar(50) NOT NULL," +
"BirtdDatedatetime NOT NULL," + "MaritalStatusnchar(1) NOT NULL," + "Gender nchar(1)
NOT NULL," + "HireDatedatetime NOT NULL," + "VacationHours INTEGER NOT NULL," +
"SickLeaveHours INTEGER NOT NULL," + "FOREIGN KEY(Contactid) references
olap1employeecontactdetails)";
//String sql8="INSERT INTO olap1employeedetails SELECT
EmployeeID,NationalIDNumber,ContactID,LoginID,Title,BirthDate,MaritalStatus,Gender,Hire
Date,VacationHours,SickLeaveHours FROM HumanResources.Employee";
//String sql9="CREATE TABLE olap1empdepthistory " +"(EmplyeeId INTEGER
NOT NULL," + "departmentid INTEGER NOT NULL," + "shiftid INTEGER NOT NULL," +
"StartDatedatetime NOT NULL," + "EndDatedatetime," + "FOREIGN KEY(EmplyeeId)
references olap1employeedetails," + "FOREIGN KEY(departmentid) references
olap1department," + "FOREIGN KEY(shiftid) references olap1shiftdetails)";
50
String sql10="INSERT INTO olap1empdepthistory SELECT
EmployeeID,DepartmentID,ShiftID,StartDate,EndDate FROM
HumanResources.EmployeeDepartmentHistory";
stmt.executeUpdate(sql10);
//System.out.println("table created");
catch(Exception ex) {
System.out.println("Error: unable to load driver class!"+ex);
System.exit(1);
OUTPUT:
RESULT:
Thus, the required java program has been typed, executed and verified successfully.
51