Lab Manual Object Oriented Programming Through JAVA
Lab Manual Object Oriented Programming Through JAVA
Lab Manual Object Oriented Programming Through JAVA
OF INDIA)
Department of CSE
(Emerging Technologies)
LAB MANUAL
Object Oriented Programming through
JAVA
LABORATORY MANUAL
DEPARTMENT OF CSE
(EMERGING TECHNOLOGIES)
Vision
Mission
To achieve and impart holistic technical education using the best of infrastructure,
outstanding technical and teaching expertise to establish the students in to
competent and confident engineers.
Evolving the center of excellence through creative and innovative teaching learning
practices for promoting academic achievement to produce internationally accepted
competitive and world class professionals.
PROGRAM OUTCOMES (POs)
Able to analyze the necessity for Object Oriented Programming paradigm and
over structured programming and become familiar with the fundamental concepts
in OOP.
Guidelines to students
A. Standard operating procedure
a) Explanation on today’s experiment by the concerned faculty using PPT covering
the following aspects:
1) Name of the experiment
2) Aim
3) Software/Hardware requirements
4) Writing the java programs by the students
5) Commands for executing programs
Writing of the experiment in the Observation Book
The students will write the today’s experiment in the Observation book as per the
following format:
a) Name of the experiment
b) Aim
c) Writing the program
d) Viva-Voce Questions and Answers
e) Errors observed (if any) during compilation/execution
Students are required to carry their lab observation book and record book with completed
experiments while entering the lab.
Students must use the equipment with care. Any damage is caused student ispunishable.
Students are not allowed to use their cell phones/pen drives/ CDs in labs.
Students need to be maintain proper dress code along with ID Card
Students are supposed to occupy the computers allotted to them and are not supposed to
talk or make noise in the lab.
Students, after completion of each experiment they need to be updated in observation
notes and same to be updated in the record.
Lab records need to be submitted after completion of experiment and get itcorrected with
the concerned lab faculty.
If a student is absent for any lab, they need to be completed the same experiment in the
free time before attending next lab.
Steps to perform experiments in the lab by the student
Step1: Students have to write the date, aim and forthat experiment in the observation book.
Step2: Students have to listen and understand the experiment explained by the faculty and
note down the important points in the observation book.
Step3: Studentsneed to write procedure/algorithm in the observation book.
Step4: Analyze and Develop/implement the logic of the program by the student in
respective platform
Step5: After approval of logic of the experiment by the faculty then the experiment has to be
executed on the system.
Step6: After successful execution the results are to be shown to the faculty andnoted the
same in the observation book.
Step7: Students need to attend the Viva-Voce on that experiment and write the samein the
observation book.
Step8: Update the completed experiment in the record and submit to the concernedfaculty
in-charge.
Regularity 3 Marks
Program written 3 Marks
Execution & Result 3 Marks
Viva-Voce 3 Marks
Dress Code 3 Marks
Allocation of Marks for Lab Internal
Total marks for lab internal are 30 Marks as per Autonomous (JNTUH.)
These 30 Marks are distributed as:
Average of day to day evaluation marks: 15 Marks
Lab Mid exam: 10 Marks
VIVA & Observation: 5 Marks
Viva-Voce 10 Marks
Record 10 Marks
INDEX
S.No PageNos.
List of Programs
1 Write a java program to find the Fibonacci series using recursive and non 1
recursive functions
2 Write a java program to multiply two given matrices. 3
3 Write a java program for Method overloading and Constructor 4
overloading
4 Write a java program to display the employee details using 6
Scanner class
5 Write a java program that checks whether a given string is 7
palindrome or not
6 A)Write a java program to represent Abstract class with example. 8
B)Write a java program to implement Interface using extends keyword 9
7 A) Write a java program to create inner classes 11
B) Write a java program to create user defined package 12
8 A)Write a java program for creating multiple catch blocks 13
B)Write a java program for producer and consumer problem using Threads 14
9 Write a Java program that implements a multi-thread application that has 16
three threads
10 A)Write a java program to display File class properties 18
B)Write a java program to represent ArrayList class 19
C)Write a Java program loads phone no, name from a text file using hash 20
table
11 Write an applet program that displays a simple message 23
12 A)Write a Java program compute factorial value using Applet 24
B)Write a program for passing parameters using Applet 26
13 A) Write a java program for handling Mouse events and Key events 27
B) Write a java program for handling Key events 31
14 Write a java program that connects to a database using JDBC 33
15 A)Write a java program to connect to a database using JDBC and insert 34
values into it.
B)Write a java program to connect to a database using JDBC and delete 36
values from it
16 Write a java program that works as a simple calculator. Use a Grid Layout 38-45
to arrange Buttons for digits and for the + - * %operations. Add a text field to
display the result
WEEK -1 Date:
Aim: Write a java program to find the Fibonacci series using recursive and non
recursive functions
Program:
class fib
{
int a,b,c;
void nonrecursive(int n) //Non recursive function to find the Fibonacci series.
{
a=0;
b=1;
System.out.print(a+ "" + b);
c=a+b;
while(c<=n)
{
System.out.print(c);
a=b;
b=c;
c=a+b;
}
}
int recursive(int n) // Recursive function to find the Fibonacci series.
{
if(n==0)
return (0);
if(n==1)
return (1);
else
return(recursive(n-1)+recursive(n-2));
}
}
// Class that calls recursive and non recursive functions
class fib1
{
public static void main(String args[])
{
int n=5;
System.out.println("The Fibonacci series using non recursive is");
// Creating object for the fib class.
fib f=new fib();
// Calling non recursive function oF fib class.
f.nonrecursive(n);
System.out.println("\n The Fibonacci series using recursive is");
for(int i=0;i<=n;i++)
{
// Calling recursive function of fib class.
int F1=f.recursive(i);
System.out.print(F1);
}
}
}
Malla Reddy College of Engineering and Technology (MRCET CAMPUS) Page |1
B.Tech – CSE (Emerging Technologies) R-20
Output 1:
EXERCISE:
WEEK -2 Date:
Aim: Write a java program to multiply two given matrices.
public class MatrixEx
{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
EXERCISE:
1. Write a java program to Transpose of a matrix is obtained by changing rows to cols & columns to
rows.
2. Write a java program to check whether the Matrix is Symmetric or Not.
3. Write a Java Program to find Matrix is an Identity Matrix or not.
4. Write a java program to add and subtract two given matrices.
WEEK -3 Date:
Aim: Write a java program for Method overloading and Constructor overloading
Method overloading:
import java.io.*;
class MethodOverloadingEx {
Output:
Constructor overloading
Student(){
System.out.println("this a default constructor");
}
Student(int i, String n){
id = i;
name = n;
}
WEEK - 4 Date:
Write a java program to display the employee details using Scanner class
import java.util.*;
class EmployeeDetails
{
public static void main(String args[])
{
System.out.println("enter name,id,age,salary");Scanner sc=new Scanner(System.in);
String n=sc.next();int i=sc.nextInt(); int a=sc.nextInt();
float s=sc.nextFloat();
System.out.println("name is"+n+"idis"+i+"ageis"+a+"salaryis"+s);
}
}
EXERCISE:
1. Write a java program to Read and display the student details using Scannerclass.
2. Write a java program that displays the number of characters, lines, words,white spaces in
a text file.
WEEK - 5 Date:
Aim: Write a java program that checks whether a given string is palindrome or not
Program:
// Class to find whether string is palindrome or not.
class palindrome
{
public static void main(String args[])
{
// Accepting the string at run time.
String s=args[0];
String s1="";
int le,j;
// Finding the length of the string.
le = s.length();
// Loop to find the reverse of the string.
for(j=le-1;j>=0;j--)
{
s1=s1+s.charAt(j);
}
// Condition to find whether two strings are equal and display the message.
if(s.equals(s1))
System.out.println("String "+s+" is palindrome"); else
System.out.println("String "+s+" is not palindrome");
}
}
WEEK – 6A Date:
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}
EXERCISE:
Write a java program that reads a file and displays the file on the screen, with an asterisk
mark before each line
WEEK – 6B Date:
Output 1:
WEEK – 7A Date:
Write a java program to create inner classes
class A
{
int
a=10;
void
display(
)
{
B
b=new
B();
b.show(
);
}
class B
{
int
b=20;
void
show(
)
{
System.out.println(" a value is " +a);
System.out.println(" b value is " +b);
}
}
}
class InnerDemo
{
public static void main(String args[])
{
A
a=new
A( );
a.displa
y( );
}
}
WEEK – 7B Date:
A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
B.java
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
WEEK – 8A Date:
WEEK – 8B Date:
Write a java program for producer and consumer problem using Threads
class InterThreadDemo
{
public static void main(String args[])
{
Producer p1=new Producer();
Consumer c1=new Consumer(p1);
Thread t1=new Thread(p1);
Thread t2=new Thread(c1);
t2.start();
t1.start();
}
}
class Producer extends Thread
{
StringBuffer sb;
Producer()
{
sb=new StringBuffer();
}
public void run()
{
synchronized(sb)
{
for(int i=0;i<=10;i++)
{
try
{
sb.append(i+":");
Thread.sleep(1000);
System.out.println("appending");
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
sb.notify();
}
}
}
WEEK – 9 Date:
Write a Java program that implements a multi-thread application that has three
threads
class Thread1 extends Thread
{
public void run()
{
for(int i=0;i<=5;i++)
{
System.out.println("Thread1:"+ i);
}
}
}
class Thread2 extends Thread
{
public void run()
{
for(int j=0;j<=5;j++)
{
System.out.println("Thread2:"+ j);
}
}
}
class Thread3 extends Thread
{
public void run()
{
for(int k=0;k<=5;k++)
{
System.out.println("Thread3:"+ k);
}}}
class MultiThreadDemo
{
public static void main(String args[])
{
Thread1 t1=new
Thread1(); Thread2
t2=new Thread2();
Thread3 t3=new
Thread3();t1.start();
t2.start();
t3.start();
for(int i=0;i<=5;i++)
{
System.out.println("main thread:"+ i);
}
}}
Malla Reddy College of Engineering and Technology (MRCET CAMPUS) P a g e | 16
B.Tech – CSE (Emerging Technologies) R-20
Test Output:
Test output:
Write a Java program loads phone no, name from a text file using hash table
Aim: Implement a program to display the content of a text file where the data is organized as
one line per record and each field in a record are separated by a whitespace (\\s means 0 or
more repetitions of any whitespace character. It takes a name or phone number as input and
prints the corresponding other value from the hash table.
Program:
import java.util.*;
import java.io.*;
public class Hashtbl {
public static void main(String[] args)
{
try
{
FileInputStream fs = new FileInputStream("E:\\kalpana\\ph.txt");
Scanner sc = new Scanner(fs).useDelimiter("\\s+");
Hashtable<String, String> ht = new Hashtable<String, String>();
String[] arrayList;
String a;
System.out.println("HASH TABLE IS");
System.out.println("--------------------------");
System.out.println("KEY : VALUE");
while (sc.hasNext())
{
a = sc.nextLine();
arrayList = a.split("\\s+");
ht.put(arrayList[0], arrayList[1]);
System.out.println(arrayList[0] + ":" + arrayList[1]);
}
System.out.println("----MENU------");
System.out.println("----1.Search by Name------");
System.out.println("----2.Search by Mobile------");
System.out.println("----3.Exit------");
String opt = "";
String name, mobile;
Scanner s = new Scanner(System.in);
while (opt != "3")
{
System.out.println("Enter Your Option 1,2,3");
opt = s.next();
switch (opt)
{
case "1":
{
System.out.println("Enter Name");
name = s.next();
if (ht.containsKey(name))
{
System.out.println("Mobile is " + ht.get(name));
}
else
{
System.out.println("Not Found");
}
}
break;
case "2":
{
System.out.println("Enter mobile");
mobile = s.next();
if (ht.containsValue(mobile)) {
for (@SuppressWarnings("rawtypes") Map.Entry e : ht.entrySet()) {
if (mobile.equals(e.getValue())) {
System.out.println("Name is " + e.getKey());
}
}
}
else
{
System.out.println("Not Found");
}
}
break;
case "3":
{
opt = "3";
System.out.println("Menu Successfully Exited");
}
break;
default:
System.out.println("Choose Option betwen 1 and Three");
break;
} } }
catch (Exception ex) {
System.out.println(ex.getMessage());
} } }
Test output:
WEEK – 11 Date:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="FactorialApplet" width=300 height=300>
</applet>
*/
public class FactorialApplet extends Applet implements ActionListener
{
Label L1,L2;
TextField T1,T2;
Button B1;
public void init()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
L1=new Label("enter the value");
add(L1);
T1=new TextField(10);add(T1);
L2=new Label("factorial value is");
add(L2);
T2=new TextField(10);add(T2);
B1=new Button("compute");
add(B1);
B1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==B1)
{
int value=Integer.parseInt(T1.getText());
int fact=factorial(value);
T2.setText(String.valueOf(fact));
}
}
int factorial(int n)
{
if(n==0)return 1;else
return n*factorial(n-1);
}
}
Test outputs:
WEEK – 13B
Write a program for handling Key Events
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SimpleKey" width=300 height=100>
</applet> */
public class SimpleKey extends Applet implements KeyListener
{
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init()
{
addKeyListener(this);
requestFocus(); // request input focus
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g)
{
g.drawString(msg, X, Y);
}
}
Test outputs:
WEEK – 14 Date:
Aim: Write a java program that connects to a database using JDBC
Program:
import java.sql.Connection;
import java.sql.DriverManager;
public class PostgreSQLJDBC
{
public static void main(String args[ ])
{
Connection c = null; try
{
Class.forName("org.postgresql.Driver");
c = DriverManager .getConnection
("jdbc:postgresql://localhost:5432/testdb", "postgres", "123");
} catch (Exception e)
{
e.printStackTrace();
System.err.println(e.getClass().getName()+": "+e.getMessage()); System.exit(0);
}
System.out.println("Opened database successfully");
}
}
Write a java program to connect to a database using JDBC and insert values into it
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class PostgreSQLJDBC
{
public static void main(String args[ ])
{
Connection c = null; Statement stmt = null; try {
Class.forName("org.postgresql.Driver"); c = DriverManager
.getConnection("jdbc:postgresql://localhost:5432/testdb", "manisha", "123");
c.setAutoCommit(false); System.out.println("Opened database successfully"); stmt =
c.createStatement();
String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
+ "VALUES (1, 'Paul', 32, 'California', 20000.00 );";
stmt.executeUpdate(sql);
stmt.close();
c.commit();
c.close();
}
catch (Exception e)
{
System.err.println( e.getClass().getName()+": "+ e.getMessage());
System.exit(0);
}
System.out.println("Records created successfully");
}
}
Write a java program to connect to a database using JDBC and delete values from it
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
stmt = c.createStatement();
String sql = "DELETE from COMPANY where ID=2;";
stmt.executeUpdate(sql);
c.commit();
ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;");
while ( rs.next( ) )
{
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");
System.out.println( "ID = " + id );
System.out.println( "NAME = " + name );
System.out.println( "AGE = " + age );
System.out.println( "ADDRESS = " + address );
System.out.println( "SALARY = " + salary );
System.out.println();
}
rs.close();
stmt.close();
c.close();
}
catch ( Exception e )
{
System.err.println( e.getClass().getName()+": "+ e.getMessage());
System.exit(0);
}
System.out.println("Operation done successfully");
}
}
WEEK – 16
Date:
Write a java program that works as a simple calculator. Use a Grid Layout to arrange
Buttons for digits and for the + - * % operations. Add a text field to display the result
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class A extends JFrame implements ActionListener
{
public JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16;
public JTextField tf1;
public JPanel p;
public String v = "";
public String v1 = "0";
public String op = "";
public A( )
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
p = new JPanel(new FlowLayout());
tf1 = new JTextField(10);
p.add(tf1);
add(p);
setLayout(new GridLayout(0, 3));
b1 = new JButton("1");
b1.addActionListener(this);
add(b1);
b2 = new JButton("2");
b2.addActionListener(this);
add(b2);
b3 = new JButton("3");
b3.addActionListener(this);
add(b3);
b4 = new JButton("4");
b4.addActionListener(this);
add(b4);
b5 = new JButton("5");
b5.addActionListener(this);
add(b5);
b6 = new JButton("6");
b6.addActionListener(this);
add(b6);
b7 = new JButton("7");
b7.addActionListener(this);
add(b7);
b8 = new JButton("8");
b8.addActionListener(this);
add(b8);
b9 = new JButton("9");
b9.addActionListener(this);
add(b9);
b10 = new JButton("0");
b10.addActionListener(this);
add(b10);
b11 = new JButton("+");
b11.addActionListener(this);
add(b11);
b12 = new JButton("-");
b12.addActionListener(this);
add(b12);
b13 = new JButton("*");
b13.addActionListener(this);
add(b13);
b14 = new JButton("/");
b14.addActionListener(this);
add(b14);
b16 = new JButton("%");
b16.addActionListener(this);
add(b16);
b15 = new JButton("=");
b15.addActionListener(this);
add(b15);
setVisible(true);
Malla
} Reddy College of Engineering and Technology (MRCET CAMPUS) P a g e | 39
B.Tech – CSE (Emerging Technologies) R-20
case "7": {
v = v + "7";
tf1.setText(v);
}
break;
case "8": {
v = v + "8";
tf1.setText(v);
}
break;
case "9": {
v = v + "9";
tf1.setText(v);
}
break;
case "0": {
v = v + "0";
tf1.setText(v);
}
break;
case "+": {
op = "+";
v1 = tf1.getText();
v = "";
}
break;
case "-": {
op = "-";
v1 = tf1.getText();
v = "";
}
break;
case "*": {
op = "*";
v1 = tf1.getText();
v = "";
}
Malla Reddy College of Engineering and Technology (MRCET CAMPUS) P a g e | 41
B.Tech – CSE (Emerging Technologies) R-20
break;
case "/": {
op = "/";
v1 = tf1.getText();
v = "";
}
break;
case "%": {
op = "%";
v1 = tf1.getText();
v = "";
}
break;
case "=": {
switch (op) {
case "+": {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) + Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}
break;
case "-": {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) - Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}
break;
case "*": {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) * Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}
break;
case "/": {
try {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) / Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
break;
case "%": {
try {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) % Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
Malla Reddy College of Engineering and Technology (MRCET CAMPUS) P a g e | 43
B.Tech – CSE (Emerging Technologies) R-20
break;
}
}
break;
}
}
}
public class Calc
{
public static void main(String[] args)
{
A a = new A();
}
}
Test outputs: