Вы находитесь на странице: 1из 47

CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

OBJECT ORIENTED PROGRAMMING

INTRODUCTION

Object-oriented programming (OOP) is a computer science term used to characterize a


programming language that began development in the 1960’s. The term ‘object-oriented programming’
was originally coined by Xerox PARC to designate a computer application that describes the
methodology of using objects as the foundation for computation. By the 1980’s, OOP rose to
prominence as the programming language of choice, exemplified by the success of C++. Currently,
OOPs such as Java, J2EE, C++,C=, Visual Basic.NET, Python and java Script are popular OOP
programming languages that any career-oriented Software Engineer or developer should be familiar
with.

OOP is widely accepted as being far more flexible than other computer programming languages.
OOPs use three basic concepts as the fundamentals for the Abstraction, Polymorphism, Event Handling
and Encapsulation are also significant concepts within object-oriented programming languages that are
explained in online tutorial describing the functionality of each concept in detail.

It is an approach that provides a way of modularizing programs by creating partitioned memory area for
both data and functions that can be used as templates for creating copies of such modules on demand.

 Program is designed around the data being operated upon rather than upon the operations
themselves.
 OOP allows decomposition of a problem into a number of entities called objects and then builds
data and functions around these objects.
 The data of an object can be accessed only by the functions associated with that object. However
functions of one object can access the functions of other objects.
 OOP attempts to fit the language to the problem.

Page 1
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Comparison

Structured Programming Object Oriented programming

Emphasis is on doing things Emphasis is on data


Large programs are divided into smaller programs Programs are divided into what are known as
known as functions objects.
Most of the functions share global data Functions that operate on data of the object are
tied together in the data structures
Data move openly around the system from Data is hidden and cannot be accessed by external
function to function. function.
Its components doesn’t model the real world Its components model the real world objects
objects
Employs top-down approach in program design. Follows bottom-up approach in program design.

FEATURES OF OBJECT ORIENTED PROGRAMMING

 Emphasis is on data rather than procedure.


 Programs are divided into what are known as objects.
 Data structures are designed such that they characterize the objects.
 Follows bottom up approach in program design.
 Object may communicate with each other through functions.
 New data and functions can be easily added whenever necessary.
 Data is hidden and cannot be accessed by external functions.

BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING

These include:

 Objects
 Classes
 Data abstraction and encapsulation
 Inheritance
 Polymorphism
 Dynamic binding
 Message passing

Page 2
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

INTRODUCTION TO JAVA PROGRAMMING LANGUAGE


Today Java programming language is one of the most popular programming languages which is
used in critical applications like stock market trading system on BSE, banking systems or android mobile
application.

Java was developed by James Gosling from Sun Microsystems in 1995 as an object-oriented
language for general-purpose business applications and for interactive, Web-based Internet applications.
The goal was to provide a platform-independent alternative to C++. In other terms, it is architecturally
neutral, which means that you can use Java to write a program that will run on any platform or device
(operating system). Java program can run on a wide variety of computers because it does not execute
instructions on a computer directly. Instead, Java runs on a Java Virtual Machine (JVM).

Java is a general-purpose programming language that’s used in all industries for almost any type
of application. If you master it, your chances of getting employed as a software developer will be higher
than if you specialize in some domain-specific programming languages. The Java language is object-
oriented (OO), which allows you to easily relate program constructs to objects from the real world.

HISTORY OF JAVA RELEASES

Java Release Important Features/Code Name


Version/CodeName Date

JDK 1.0 (Oak) 23rd Jan Initial release


1996

JDK 1.1 19th Feb Reflection, JDBC, Inner classes, RMI


1997
J2SE 1.2 (Playground) 8th Dec Collection, JIT, String memory map
1998

J2SE 1.3 (Kestrel) 8th May Java Sound, Java Indexing, JNDI
2000

J2SE 1.4 (merlin) 6th Feb 2002 Assert, regex, exception chaining,

J2SE 5.0 (Tiger) 30th Sept Generics, autoboxing, enums


2004

Page 3
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Java SE 6.0 (Mustang) 11th Dec JDBC 4.0, java compiler API, Annotations
2006

Java SE 7.0 (Dolphin) 28th July String in switch-case, Java nio, exception
2011 handling new way

This program runs fine under GNU Gcc compiler. We have tested this on a Ubuntu Linux system.
But if you are using any other compiler like Turbo C++, the program needs to be modified to be executed
successfully. For the sake of simplicity, we have not included that additional stuff here.

THE JAVA PROGRAM LIFE CYCLE

Java requires the source code of your program to be compiled first. It gets converted to either
machine-specific code or a byte code that is understood by some run-time engine or a java virtual
machine.

Not only will the program be checked for syntax errors by a Java compiler, but some other libraries of
Java code can be added (linked) to your program after the compilation is complete (deployment stage).

Page 4
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

 Step1 : Create a source document using any editor and save file as .java (e.g. abc.java)
 Step2 : Compile the abc.java file using “javac” command or eclipse will compile it automatically.
 Step3 : Byte Code (abc.class) will be generated on disk.
 Step4 : This byte code can run on any platform or device having JVM (java.exe convert byte code
in machine language)
TERMINOLOGIES USED IN JAVA PROGRAMMING

JDK (Java Development Kit): JDK contains JRE along with various development tools like Java
libraries, Java source compilers, Java debuggers, bundling and deployment tools

JRE (Java Runtime Environment): It is part of JDK but can be used independently to run any byte
code (compiled java program). It can be called as JVM implementation.

JVM (Java Virtual Machine): ‘JVM’ is software that can be ported to various hardware platforms. JVM
will become an instance of JRE at runtime of java program. Byte codes are the machine language for the
JVM. Like a real computing machine, JVM has an instruction set which manipulates various memory
areas at run time. Thus for different hardware platforms, one has corresponding the implementation of
JVM available as vendor supplied JREs.

Java API (Application Programming Interface) : Set of classes’ written using Java programming
language which runs on JVM. These classes will help programmers by providing standard methods like
reading from the console, writing to the console, saving objects in data structure etc.

Advantages of Java programming language

 Built-in support for multi-threading, socket communication, and memory management (automatic
garbage collection).
 Object Oriented (OO).
 Better portability than other languages across operating systems.

Page 5
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

 Supports Web-based applications (Applet, Servlet, and JSP), distributed applications (sockets,
RMI, EJB etc.) and network protocols (HTTP, JRMP etc.) with the help of extensive standardized
APIs (Application Programming Interfaces).
Summary

 Java is platform independent programming language which means compile once and run
anywhere.
 Java provides built-in functionality for Thread, collection, File IO etc.
 The Java language is object-oriented (OO) programming language which will allow the
programmer to relate java domain objects with real life objects.

HOW TO COMPILE AND RUN JAVA PROGRAM IN COMMAND PROMPT


Create a temporary folder C:\OOPs Program. Using Notepad or another text editor, create a small Java
file HelloWorld.java with the following text:
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}

Save your file as HelloWorld.java in C:\OOPs Program.


Run Command Prompt (found under All Programs/Accessories in the Start menu). Type
C:\> cd \ OOPs Program
This makes C:\ OOPs Program the current directory.
C:\ OOPs Program > set path=” C:\Program Files\Java\jdk1.6.0_20\bin”
(use the JDK folder for the version installed on your system). This tells the system where to find JDK
programs for that reason, go to your C drive then click on Program Files->java-> jdk1.6.0_20-> bin

Page 6
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Copy that link and paste into command Prompt


set path=” C:\Program Files\Java\jdk1.6.0_20\bin”
C:\ OOPs Program > javac HelloWorld.java
C:\ OOPs Program > java HelloWorld
The program output:
Hello, World!

Ex.No.1 GENERATING THE ELECTRICITY BILL

AIM
To Develop a java application to generate electricity bill and Create a class with the following
member: Consumer number, consumer name, previous month reading, the type of EB
connection(i.e domestic or commercial). Compute the bill amount using following tariff. If the
type of the EB connection is domestic, calculate the amount to be paid as follows:
 First 100 units – Rs. 1 per unit
 101 – 200 units – Rs. 2.5 per unit
 201 – 500 units – Rs. 4 per unit
 >501 units – Rs. 6 per unit

If the type of the EB connection is commercial, calculate the amount to be paid as follows:
 First 100 units – Rs. 2 per unit
 101 – 200 units – Rs. 4.5 per unit
 201 – 500 units – Rs. 6 per unit

Page 7
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

 >501 units – Rs. 7 per unit

DESCRIPTION

Class

A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

 fields
 methods
 constructors
 blocks
 nested class and interface

Syntax to declare a class:


class <class_name>
{      
field;  
   method;  
}  

Object

Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.

An object has three characteristics:

 state: represents data (value) of an object.


 behavior: represents the behavior (functionality) of an object such as deposit, withdraw
etc.
 identity: Object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. But, it is used internally by the JVM to identify each
object uniquely.

Object is an instance of a class. Class is a template or blueprint from which objects are created.
So object is the instance(result) of a class.

ALGORITHM

Step 1: Define the class named ComputeElectricityBill


Step 2: Read the Consumer number, consumer name, previous month reading, current month
reading the type of EB connection(i.e domestic or commercial) from the user using

Page 8
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

getdata() method.
Step 3: Calculate the number of units consumed = current month reading - previous month
reading.
Step 4: If the type of the EB connection is domestic, calculate the amount to be paid as follows:
if(units>501)
bill = units * 6 ;
else if(units>=200)
bill = units * 4 ;
else if(units>=100)
bill = units * 2.5 ;
else
bill = units * 1 ;

Step 5: If the type of the EB connection is Commercial, calculate the amount to be paid as
follows:
if(units>501)
bill = units * 7 ;
else if(units>=200)
bill = units * 6 ;
else if(units>=100)
bill = units * 4.5 ;
else
bill = units * 2 ;

Step 6: Display the customer Details with amount to be paid using display() method.

SAMPLE OUTPUT

D:\>javac ComputeElectricityBill.java
D:\>java ComputeElectricityBill

Enter customer number


12
Enter customer name
Panimalar
Enter the type of connection (domestic / commercial)
domestic
Enter the previous reading
1000
Enter the current reading
1200
************** Customer details*************

Page 9
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Customer Number : 12
Customer Name:Panimalar
Type of EB Connection : domestic
Previous unit : 1000
Current unit :1200
units consumed : 200
Bill to pay:800.0

RESULT

Thus the java program to generate electricity bill for a customer was developed and
executed successfully.

VIVA QUESTIONS

1. Difference between header files and import packages?


2. What is the difference between procedural and object-oriented programs?
3. What are Encapsulation, Inheritance and Polymorphism?
4. What is OOPs?

Ex.No.2 IMPLEMENTATION OF CURRENCY CONVERTOR, DISTANCE


CONVERTER AND TIME CONVERTER USING PACKAGE
AIM

To develop a java application to implement currency convertor (Dollar to INR, EURO to


INR, Yen to INR and Vice Versa),distance converter (meter to KM, miles to KM and Vice
Versa) and time converter(hours to minutes, seconds and Vice Versa) using package.

DESCRIPTION

A java package is a group of similar types of classes, interfaces and sub-packages.


Package in java can be categorized in two forms
1. Built-in package
2. User-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Page 10
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Here, we will have the detailed learning of creating and using user-defined package named
“Convertor” for Currency Convertor, distance Convertor and time Convertor.

ALGORITHM

Step 1: Create a Package named convertor.


Step 2: Define the main class named convert.
Step 3: Define the class named currency and write the necessary code to perform the currency
convertor and save it in the package “convertor”.
Step 4: Define the class named distance and write the necessary code to perform the distance
Convertor and save it in the package “convertor”.
Step 5: Define the class named time and write the necessary code to perform the time convertor
and save it in the package “convertor”.
Step 6: Create and invoke the object for currency class and perform the currency convertor.
Step 7: Create and invoke the object for distance class and perform the distance convertor.
Step 8: Create and invoke the object for time class and perform the time convertor.

OUTPUT

D:\>cd convertor
D:\convertor>javac currency.java // compile the c.java
D:\convertor>javac distance.java // compile the d. java
D:\convertor>javac time.java // compile the t.java
D:\convertor>cd .. // change the directory
D:\>javac convert.java // compile the main program(a.java)
D:\>java convert

Welcome to the Currency Converter Program


Enter the currency in US Dollars
78
78.0 Dollar = 5098.860000000001 Rupees
**********************************************************
Welcome to the distance Converter Program

Enter the input in Kilometer


2
2.0 = 2000.0 Meter
**********************************************************
Welcome to the Time Converter Program
Enter the input in Hours
1
1.0 Hours = 60.0 Minutes

RESULT

Page 11
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Thus the java program to implement Currency Convertor, Distance Converter and Time
Converter using Package was developed and executed successfully.

VIVA QUESTIONS

1. Explain the usage of Java packages.


2. What is the package name for Object class?
3. Name few classes that are part of java.io package ?
4. Name few classes that are part of java.lang package ?
5. Name few classes that are part of java.util package ? 

Ex.No.3 GENERATING THE EMPLOYEE PAY SLIP

AIM

To develop a java application with Employee class with emp_name, emp_id, address,
mail_id, mobile_no as member. Inherits the classes, Programmer, Assistant Professor,
Associative Professor and Professor from employee class. Add Basic Pay(BP) as the member of
all the inherited classes with 97% of BP as DA,10% of BP as HRA,12% of BP as PF,0.1% of BP
for staff club fund. Generate pay slip for the employees with their Gross and net salary.

DESCRIPTION

Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object. Inheritance represents the IS-A relationship, also known as parent-
child relationship.

Page 12
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).


o For Code Reusability.

Terms used in Inheritence

o Class: A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits
the features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates
you to reuse the fields and methods of the existing class when you create a new class.
You can use the same fields and methods already defined in previous class.

Syntax of Java Inheritance

class Super {
.....
.....
}

class Sub extends Super {


.....
.....
}
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called parent or super class and the new
class is called child or subclass.

Java Inheritance Example

Page 13
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

ALGORITHM

Step 1: Define the Base class named Employee


Step 2: Declare the corresponding variable of employee(emp_name, emp_id, address, mail_id,
mobile_no,da, hra,pf,scf, gross,net).
Step 3: Read the input from the user using getdata() method.
Step 4: Define the derived classes Programmer, Assistant Professor, Associate Professor and
Professor that derives Employee class.
Step 5: Read the Basic salary of the Employee from the user.
Step 6: Calculate the parameters like DA, HRA, PF, staff club fund, Gross and net salary for
Employee using calculate() method.
DA=(97/100)*basicsalary
HRA=(10/100)*basicsalary
PF=(12/100)*basicsalary
SCF=(0.1/100) *basicsalary
Gross=basicsalary+DA+HRA+PF+SCF
Netsalary=Gross – PF
Step 7: Display the Employee Pay slip using display() method.

SAMPLE OUTPUT

D:\>javac emp.java
D:\>java emp

1.PROGRAMMER
2.ASSISTANT PROFESSOR
3.ASSOCIATE PROFESSOR
4.PROFESSOR
Enter the choice
1
Enter the programmer details
Enter name
abcd
Enter id
100
Enter the address
adyar
Enter mail
abcd@gmail.com
Enter mobile
9898989898

Page 14
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

***************Employee details***************
Employee Name = abcd
Employee ID = 100
Employee address = adyar
Employee mobile number = 9898989898
Employee Mail ID = abcd@gmail.com
Basic pay = 2500.0
DA = 2425.0
HRA = 250.0
PF = 300.0
Staff Club Fund = 2.5
Gross Salary = 5477.5
Net Salary = 5177.5

RESULT

Thus the java application to generate Employee Pay Slip using inheritance was developed
and executed Successfully.

VIVA QUESTIONS

1.What is inheritance in java.


2. Types of inheritance
3. Why use inheritance in java
4. Write the Syntax of Java Inheritance.

Ex.No.4 DESIGN AND IMPLEMENT A JAVA INTERFACE FOR STACK


ADT USING ARRAY WITH EXCEPTION HANDLING.

AIM
To design a java interface for stack ADT. Implement this interface using array. Provide
necessary exception handling in both the implementations.

DESCRIPTION

The interface keyword is used to declare an interface. It provides total abstraction; means


all the methods in interface are declared with empty body and are public and all fields are public,
static and final by default. A class that implement interface must implement all the methods
declared in the interface.

Page 15
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Syntax to define interface:


[access_specifier] interface InterfaceName
{
Datatype VariableName1=value;
Datatype VariableName2=value;
.
Datatype VariableNameN=value;

returnType methodName1(parameter_list);
returnType methodName2(parameter_list);
.
.
returnType methodNameN(parameter_list);
}

Where,
Access_specifer : either public or none.
Name: name of an interface can be any valid java identifier.
Variables: They are implicitly public, final and static, meaning that they cannot be changed by the
implementing class. They must be initialized with a constant value.
Methods: They are implicitly public and abstract, meaning that they must be declared without body and
defined only by the implementing class.

Note:

The java compiler adds public and abstract keywords before the interface method and public, static
and final keywords before data members.

ALGORITHM

Step 1: Create an interface called Mystack.


Step 2: Declare the following methods in the interface
public void pop();
public void push();
public void display();
Step 3: Define the Class Stack_array that implements all the 3 methods of the Mystack
interface with necessary exception handling codes.
Step 4: Define the main Class “StackADT” and Create the object for the Class Stack_array.
Step 5: Get the choice from the user. If the choice is 1, then perform the PUSH ADT.
5.1 Check the stack for overflow.
5.2 Increment the top value.

Page 16
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

5.3 Read the value to be pushed to the stack.


5.4 Push the value into the stack.
5.5 Display the pushed value.
Step 6: If the Choice is 2, then perform the POP ADT.
6.1 Check the stack for underflow.
6.2 Pop the top value from the stack.
6.3 Decrement the top value.
6.4 Display the value that is popped from the stack.
Step 7: If the choice is 3, call display() method to display the elements in the Stack.

SAMPLE OUTPUT

D:\>javac StackADT.java
D:\>java StackADT

Implementation of Stack using Array


1.Push
2.Pop
3.Display
4.Exit

Enter your choice:


1
Enter the element
10
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
20
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
30
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
40
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
50
1.Push 2.Pop 3.Display 4.Exit

Page 17
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Enter your choice:


1
Stack Overflow
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
3
Elements are: 10 <-- 20 <-- 30 <-- 40 <-- 50 <--

RESULT

Thus the java application to implement a java interface for Stack ADT using array with
exception handling was developed and executed Successfully.

VIVA QUESTIONS
1. Define stack ADT
2. What is interface.
3. Write the syntax to declare the interface.
4. List down the access specifier in java.

Ex.No.5 STRING OPERATIONS USING ARRAY LIST

AIM
To write a java program to perform the following string operations using ArrayList.
Write the functions for the following
1. Append – add at end
2. Insert – add at particular index
3. Search
4. List all string that starts with given letter
DESCRIPTION

Page 18
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

ArrayList is a resizable-array implementation of the List interface. Java ArrayList class


uses a dynamic array for storing the elements. It inherits AbstractList class and implements List
interface.

The important points about Java ArrayList class are:

o Java ArrayList class can contain duplicate elements.


o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the index basis.
o In Java ArrayList class, manipulation is slow because a lot of shifting needs to be
occurred if any element is removed from the array list.

Hierarchy of ArrayList class


As shown in the below diagram, Java ArrayList class extends AbstractList class which
implements List interface. The List interface extends Collection and Iterable interfaces in
hierarchical order.

Drawback of Array

The issue with arrays is that they are of fixed length so if it is full we cannot add any
more elements to it, likewise if number of elements gets removed from it the memory
consumption would be the same as it doesn’t shrink.

Advantage of ArrayList

On the other ArrayList can dynamically grow and shrink after addition and removal of
elements. Apart from these benefits, ArrayList class enables us to use predefined methods of it
which makes our task easy.

Page 19
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Methods of Java ArrayList

Method Description

void add(int index, Object It is used to insert the specified element at the specified
element) position index in a list.

boolean addAll(Collection It is used to append all of the elements in the specified


c) collection to the end of this list, in the order that they are
returned by the specified collection's iterator.

void clear() It is used to remove all of the elements from this list.

int lastIndexOf(Object o) It is used to return the index in this list of the last
occurrence of the specified element, or -1 if the list does not
contain this element.

Object[] toArray() It is used to return an array containing all of the elements in


this list in the correct order.

Object[] toArray(Object[] a) It is used to return an array containing all of the elements in


this list in the correct order.

boolean add(Object o) It is used to append the specified element to the end of a list.

boolean addAll(int index, It is used to insert all of the elements in the specified
Collection c) collection into this list, starting at the specified position.

Object clone() It is used to return a shallow copy of an ArrayList.

int indexOf(Object o) It is used to return the index in this list of the first
occurrence of the specified element, or -1 if the List does
not contain this element.

void trimToSize() It is used to trim the capacity of this ArrayList instance to


be the list's current size.

ALGORITHM

Step 1: Define class named arraylist.

Page 20
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Step 2: In the main class, create the object for the ArrayList class.
Step 3: To append a String at last position of arraylist use the add() method.
obj.add("Ajeet"); //appends this string in the last
obj.add("Harry");
obj.add("Chaitanya");
obj.add("Steve");
obj.add("Anuj");
Step 4: To add a String at particular position in array list use the add() method with the position
number as 1st parameter.
obj.add(0, "Rahul"); // appends this string in the specified position
obj.add(1, "Justin");
Step 5: To remove a particular String from the array list use remove() method.
obj.remove("Chaitanya"); //removes this element
obj.remove("Harry");
Step 6: To search a particular string in the arraylist, find the index of the search element using
indexOf() method. This returns the index of the search element if present. If the element
is not found in the list then this method returns the value -1.
Ex: int pos = obj.indexOf(search);
if(pos = = -1) Search element is not present in array List.

SAMPLE OUTPUT

D:\>javac arraylist.java
D:\>java arraylist

Currently the array list has following elements:[Ajeet, Harry, Chaitanya, Steve, Anuj]

Current array list is:[Rahul, Justin, Ajeet, Steve, Anuj]

Current array list is:[Rahul, Ajeet, Steve, Anuj]

Enter the element to search

Rahul

Rahul is present in 0 position

RESULT

Thus the java application to perform string operations using arraylist was developed and
executed successfully.

Page 21
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

VIVA QUESTIONS

1. Difference between an array and ArrayList in Java?


2. List the methods used in ArrayList.
3. How to remove duplicates from ArrayList in Java? 
4.  How to reverse ArrayList in Java? 
5. How to create and initialize ArrayList in one line?

Ex.No.6 DESIGN AN ABSTRACT CLASS FOR SHAPE

AIM

To Write a java program to create an abstract class named Shape that contains 2 integers
and an empty method named PrintArea( ). Provide 3 classes named Rectangle, Triangle and
Circle such that each one of the classes extends the class Shape. Each one of the classes contain
only the method PrintArea( ) that prints the area of the given shape.

DESCRIPTION

Page 22
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Abstract class
A class that is declared as abstract is known as abstract class. It needs to be extended
and its method implemented. It cannot be instantiated (can’t create object for abstract class).
Example abstract class
abstract class A
{

}  
Abstract method
A method that is declared as abstract and does not have implementation is known as
abstract method.

Example abstract method


abstract void printStatus(); //no body and abstract  

When to use Abstract Methods & Abstract Class?

Abstract methods are usually declared where two or more subclasses are expected to do a
similar thing in different ways through different implementations. These subclasses extend the
same Abstract class and provide different implementations for the abstract methods. Abstract
classes are used to define generic types of behaviors at the top of an object-oriented
programming class hierarchy, and use its subclasses to provide implementation details of the
abstract class.

ALGORITHM

Step 1: Define abstract base class named shape.


Step 2: Declare 2 integer variable x, y in the class shape.
Step 3: Declare the abstract method named PrintArea( ) in the class shape.

Step 4: Define 3 subclasses named Rectangle, Triangle and Circle that extends the abstract class
Shape.
Step 5: These subclasses extend the same Abstract class Shape but provides different
implementations for the abstract methods PrintArea( )
Step 6: Define a main class and create 3 objects for 3 subclasses Rectangle, Triangle and Circle.
We can’t create object for abstract class Shape.
Step 7: Using the respective objects initialize the class variables and invoke the abstract methods
PrintArea( ) as shown below.

Rectangle r = new Rectangle();


r.x = 10;
r.y = 20;
r.printArea();

Page 23
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Triangle t = new Triangle();


t.x = 30;
t.y = 35;
t.printArea();

Circle c = new Circle();


c.x = 2;
c.printArea();

SAMPLE OUTPUT

D:\>javac Abst.java
D:\>java Abst

Area of Rectangle is 200


-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
Area of Triangle is 525
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
Area of Circle is 12
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
RESULT

Thus the java application to demonstrate the concept of abstract class and abstract
method was developed and executed successfully.

VIVA QUESTIONS

1. Define abstract class


2. Define abstract method
3. When to use Abstract Methods and Abstract Class?
4. How to instantiate abstract class.

Ex.No:7 IMPLEMENTATION OF USER DEFINED EXCEPTION


HANDLING
AIM
To write a java program to implement user defined exception handling.

DESCRIPTION

WHAT IS EXCEPTION?
Exception is an abnormal condition.

WHAT IS EXCEPTION IN JAVA?


In java, exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.

Page 24
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

EXCEPTION HANDLING IN JAVA

The exception handling in java is one of the powerful mechanism to handle the runtime


errors so that normal flow of the application can be maintained.

EXCEPTION CLASS HIERARCHY

JAVA EXCEPTION HANDLING KEYWORDS


There are 5 keywords used in java exception handling.

1. try
2. catch
3. finally
4. throw
5. throws

JAVA USER-DEFINED EXCEPTION OR CUSTOM EXCEPTION

Page 25
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

If the user is creating their own Exception, then such exceptions are known as custom
exception or user-defined exception. Java custom exceptions are used to customize the
exception according to user need.

By the help of custom exception, the user can have their own exception and messages.

Here we will discuss the exceptions handled when the age entered is not between 15 and 25.

ALGORITHM

Step 1: Import java.lang package for exception handling.


Step 2: Create a user defined exception class named MyException that extends the Exception
Class
Step 2: Using Constructor initialize the variable age.

Step 3: Create a class userdef which contains a static method and throws the MyException
Step 4: Input the age from the user.
Step 5: If the entered age is between 15 and 25, then no exception is thrown. The entered age
is displayed as such.
Step 6: If the entered age is below 15 or above 25, then the user exception is caught and
exception message is thrown.
Step 7: If the entered age is not within the range of integer data type, then the inbuilt exception is
caught and thrown.

SAMPLE OUTPUT

D:\>javac userdef.java
D:\>java userdef

Enter the age (above 15 and below 25)


14
Caught MyException
Number not in range

D:\>java userdef
Enter the age (above 15 abd below 25)

Page 26
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

24
The number is : 24

D:\>java userdef
Enter the age (above 15 abd below 25)
66666666666666666666666
Inbuilt exception caught
java.lang.NumberFormatException: For input string: "66666666666666666666666"

RESULT

Thus the java application to implement the user defined exception handling was
developed and executed successfully.

VIVA QUESTIONS

1. What is Exception in Java?


2. What are the Exception Handling Keywords in Java?
3. Explain Java Exception Hierarchy?
4. What are important methods of Java Exception Class?
5. What is difference between Checked and Unchecked Exception in Java?
6. What is difference between throw and throws keyword in Java?
7. How to write custom exception in Java?
8. What is OutOfMemoryError in Java?

Ex.No:8 IMPLEMENTATION OF FILE SYSTEM

AIM
To write a java program that reads a file name from the user, displays the information
about whether the file exists, whether the file is readable or writable, the type of the file and
length of the file in bytes.

DESCRIPTION

The File class contains several methods for working with the path name, deleting and
renaming files, creating new directories, listing the contents of a directory, and determining
several common attributes of files and directories.

Page 27
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

How to create a File Object?


A File object is created by passing in a String that represents the name of a file, or a
String or another File object. For example,
File a = new File("abc.txt");

Methods in File handling


1. boolean canRead() : Tests whether the application can read the file denoted by this
abstract pathname.
2. boolean canWrite() : Tests whether the application can modify the file denoted by this
abstract pathname.
3. boolean delete() : Deletes the file or directory denoted by this abstract pathname.
4. boolean exists() : Tests whether the file or directory denoted by this abstract pathname
exists.
5. String getName() : Returns the name of the file or directory denoted by this abstract
pathname.
6. String getPath() : Converts this abstract pathname into a pathname string.
7. long length() : Returns the length of the file denoted by this abstract pathname.

ALGORITHM

Step 1: Import the necessary packages.


Step 2: Create a class named filedemo.
Step 3: Inside the main method prompt the user to enter file name.
Step 4: Provide the file name to the File object to create an object of File.

Step 5: Use the methods provided by the File class to know information such as file exists,
readable, writable, length and provide the appropriate output.

SAMPLE OUTPUT

D:\>javac filedemo.java
D:\>java filedemo

Enter the file name


a.txt
This file : Exists
File Name:a.txt
Path:a.txt
Is Readable:true
IS Writable:true
File Size:26bytes

Page 28
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

********************************************
contents in the file
hello
welcome to java

D:\>javac filedemo.java
D:\>java filedemo

Enter the file name


a.txt
This file : Exists
File Name:a.txt
Path:a.txt
Is Readable:true
IS Writable:false
File Size:26bytes
********************************************
contents in the file
hello
welcome to java

RESULT

Thus the java application to implement the file operations was developed and executed
successfully.

VIVA QUESTIONS

1. What is a stream and what are the types of Streams and classes of the Streams?
2. Tell something about BufferedWriter?What are flush() and close() used for?
3. What is a IO stream?
4. What are FileInputStream and FileOutputStream?
5. Which streams are advised to use to have maximum performance in file copying? 
Ex.No:9 IMPLEMENTATION OF MULTI-THREADED
APPLICATION
AIM

To write a java program that implements a multi-threaded application that has 3 threads.
First thread generates random integer every one second and if the value is even, the second
thread computes the square of the number and prints. If the value is odd, the third thread will
print the value of cube of the number.

DESCRIPTION

Page 29
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

A program can be divided into a number of small processes. Each small process can
be addressed as a single thread.

Multithreading is a technique of executing more than one thread, performing


different tasks, simultaneously. Multithreading enables programs to have more than one
execution paths which executes concurrently. Each such execution path is a thread. For example,
one thread is writing content on a file at the same time another thread is performing spelling
check.

Advantages of Multithreading:

1. Threads are light weight compared to processes.


2. Threads share the same address space and therefore can share both data and code.
3. Context switching between threads is usually less expensive that between processes.
4. Cost of thread communication is low than inter-process communication.
5. Threads allow different tasks to be performed concurrently.
6. Reduces the computation time. Through multithreading, efficient utilization of system
resources can be achieved.

THREAD STATES

The start() method creates the system resources necessary to run the thread, schedules the thread
to run and calls the thread’s run() method.
ALGORITHM

Step 1: Create a class named even that implements Runnable.


Step 2: Create a class named odd that implements Runnable.
Step3: Create thread objects and Random class object.
Step 4: Pass the objects of our class to thread class .
Step 5: Call the start( ) method.

SAMPLE OUTPUT

D:\>javac Mthread.java
D:\>java Mthread

Page 30
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Main Thread and Generated Number is 4


Thread Name:Even Thread and 4is even Number and Square of 4 is: 16
--------------------------------------
Main Thread and Generated Number is 9
Thread Name:ODD Thread and 9 is odd number and Cube of 9 is: 729
--------------------------------------
Main Thread and Generated Number is 35
Thread Name:ODD Thread and 35 is odd number and Cube of 35 is: 42875
--------------------------------------
Main Thread and Generated Number is 5
Thread Name:ODD Thread and 5 is odd number and Cube of 5 is: 125
--------------------------------------
Main Thread and Generated Number is 69
Thread Name:ODD Thread and 69 is odd number and Cube of 69 is: 328509
--------------------------------------
Main Thread and Generated Number is 39
Thread Name:ODD Thread and 39 is odd number and Cube of 39 is: 59319

RESULT

Thus the java program to implement multi-threaded application was developed and
executed successfully.

VIVA QUESTION

1. What are the benefits of Multi-Threading?


2. What is difference between user Thread and daemon Thread?
3. How can we create a Thread in Java?
4. How can we make sure main () is the last thread to finish in Java Program?
5. How can we achieve thread safety in Java?

Ex.No:10 IMPLEMENTATION OF GENERIC FUNCTIONS

AIM
To write a java program to find the maximum value from the given type of elements
using a generic functions.

DESCRIPTION

Why Generic Programming?


Generic programming means writing code that can be reused for objects of many different types.

Page 31
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Generic class

A class that can refer to any type is known as generic class.


A generic class declaration looks like a non-generic class declaration, except that the class name
is followed by a type parameter section.
The type parameter section of a generic class can have one or more type parameters
separated by commas. These classes are known as parameterized classes or parameterized types
because they accept one or more parameters.

Generic Method

Like generic class, we can create generic method that can accept any type of argument. we
can write a single generic method declaration that can be called with arguments of different
types. Based on the types of the arguments passed to the generic method, the compiler handles
each method call appropriately. Following are the rules to define Generic Methods −
 All generic method declarations have a type parameter section delimited by angle
brackets (< and >) that precedes the method's return type ( < E > in the next example).
 Each type parameter section contains one or more type parameters separated by commas.
A type parameter, also known as a type variable, is an identifier that specifies a generic
type name.
 The type parameters can be used to declare the return type and act as placeholders for the
types of the arguments passed to the generic method, which are known as actual type
arguments.
 A generic method's body is declared like that of any other method. Note that type
parameters can represent only reference types, not primitive types (like int, double and
char).

ALGORITHM

Step 1: Define a class named MaximumTest.


Step 2: All generic method declarations have a type parameter section delimited by angle
brackets (< and >) that precedes the method's return type.
Step 3: Define a generic method maximum ( ) to find the maximum value from the given type of
elements.
Step 4: Read 3 elements of any type(int / float / String) from the user.
Step 5: The generic method maximum( ) compare all the 3 inputs using compareTo( ) method
and print the maximum value from the given type of elements.

SAMPLE OUTPUT
Page 32
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

D:\>javac MaximumTest.java
D:\>java MaximumTest

Enter 3 numbers
10 -7 100

Maximum value is 100

RESULT

Thus the java program to implement generic methods to find the maximum value from
the given type of elements was developed and executed successfully.

VIVA QUESTION

1. What is Generics in Java? What are advantages of using Generics?


2. How Does a Generic Method Differ From a Generic Type?
3. What are the basic interfaces of Java Collections Framework?
4. Why Collection doesn’t extend Cloneable and Serializable interfaces?
5. What is Java Collections Framework? List out some benefits of Collections framework?

Ex.No:11 EVENT-DRIVEN PROGRAMMING

AIM
Design a calculator using event-driven programming paradigm of java with following
options.
 Decimal manipulations
 Scientific manipulations
DESCRIPTION

Page 33
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create
window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java. Unlike AWT, Java Swing provides platform-independent and
lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.

Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.

Method Description
public void add(Component c) add a component on another component.

public void setSize(int width,int sets size of the component.


height)

public void sets the layout manager for the


setLayout(LayoutManager m) component.

public void setVisible(boolean b) sets the visibility of the component. It is


by default false.

ALGORITHM

Step 1: Create the class scientificcalculator.


Step 2: Define and declare all the necessary variables to perform the scientific and decimal
operations.
Step 3: Using scientificcalculator() constructor create buttons that are in the scientific calculator.
Step 4: Using actionPerformed() method define the function that has to be done when
the corresponding buttons are pressed.
Step 5: In the main function create the objects for the class scientific calculator and then
using that objects set the title for the program as scientific calculator and then press
the buttons in the calculator to get the results which you want

SAMPLE OUTPUT

Page 34
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

D:\>javac ScientificCalculator.java
D:\>java ScientificCalculator

RESULT

Thus the java program to design a calculator using event-driven programming paradigm
was developed and executed successfully.

VIVA QUESTIONS

1.What is Event Handling in java?


2. List the Components of Event Handling.
3. How Events are handled in java ?
4. Differentiate awt and swing in java.

Ex.No:12 MINI PROJECT

AIM
To develop a mini project for Tic-Tac-Toe game using Java swing concepts.

DESCRIPTION

Tic-Tac-Toe is a very common game that is fairly easy to play. The rules of the game are
simple and well-known.

Page 35
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

 The game is to be played between two people (in this program between HUMAN and
COMPUTER).
 One of the player chooses ‘O’ and the other ‘X’ to mark their respective cells.
 The game starts with one of the players and the game ends when one of the players has
one whole row/ column/ diagonal filled with his/her respective character (‘O’ or ‘X’).
 If no one wins, then the game is said to be draw.

How to implement Tic Tac Toe using JAVA ?

The basic idea is to use a two-dimensional array, board, to maintain the game board.
Cells in this array, stores the value that indicate if that cell is empty or stores an X or O.

Page 36
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

RESULT

Thus Tic-Tac-Toe game was designed and executed successfully with the help of Java
Swing.

Page 37
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

ADDITIONAL PROGRAMS

Ex.No:13 METHOD OVERRIDING IN JAVA


AIM

To write a java program to implement method overriding.

DESCRIPTION

If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.

Method overriding is one of the way by which java achieve Run Time Polymorphism.

Page 38
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

In other words, If subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).
4. There are many differences between method overloading and method overriding in java.

ALGORITHM
Step 1: Create a class MODemo.
Step 2:Create a subclass B extends MODemo..
Step 3: Subclass has same method has super class.
Step 4: Create object to the derived class to call the derived class methods.

class Parent
{
    void show() { System.out.println("Parent's show()"); }
}
 
class Child extends Parent
{
    
    void show() { System.out.println("Child's show()"); }
}
 
class Main
{
    public static void main(String[] args)
    {
        Parent obj1 = new Parent();
        obj1.show();
 
        
        Parent obj2 = new Child();
        obj2.show();
    }
}

Page 39
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

SAMPLE OUTPUT

D:\>javac Main.java
D:\>java Main

Parent's show()
Child's show()

RESULT
Thus the java program to demonstrate the concept of method overriding was executed
and verified successfully.

Ex.No:14 COMMAND LINE ARGUMENTS

AIM

To read array of numbers through command line arguments and sort in ascending order.
DESCRIPTION

The java command-line argument is an argument i.e. passed at the time of running the
java program. The arguments passed from the console can be received in the java program and it
can be used as an input. So, it provides a convenient way to check the behavior of the program

Page 40
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

for the different values. We can pass N (1,2,3 and so on) numbers of arguments from the
command prompt.
Example of command-line argument that prints all the values

In this example, we are printing all the arguments passed from the command-line. For this
purpose, we have traversed the array using for loop.

class A
{  
public static void main(String args[])
{  
   for(int i=0;i<args.length;i++)  
System.out.println(args[i]);  
}  
}  

D:> javac A.java  
D:> java A abcd hello 1 3 abc  

Output:
abcd
hello
1
3
abc

ALGORITHM

Step 1: Create a class and pass the array numbers through command line arguments.
Step 2: Input these values to array.
Step 3: Sort the array elements using any sorting methods.
Step 4: Print the array elements in sorted order.

RESULT

Page 41
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Thus the java program to implement the command line arguments was executed and
verified successfully.

Ex.No:15 APPLET PROGRAM

AIM
To write a simple Java program to demonstrate the applet concept.

DESCRIPTION
An Applet is a Java program that runs in a Web browser. An applet can be a fully functional
Java application because it has the entire Java API at its disposal.

These import statements bring the classes into the scope of our applet class −

 java.applet.Applet

Page 42
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

 java.awt.Graphics

Every applet is an extension of the java.applet.Applet class. The base Applet class provides
methods that a derived Applet class may call to obtain information and services from the browser
context.

These include methods that do the following −

 Get applet parameters


 Get the network location of the HTML file that contains the applet
 Get the network location of the applet class directory
 Print a status message in the browser
 Fetch an image
 Fetch an audio clip
 Play an audio clip
 Resize the applet
 The viewer or browser looks for the compiled Java code at the location of the document.
To specify otherwise, use the codebase attribute of the <applet> tag as shown −
 <applet codebase = "https://amrood.com/applets" code = "HelloWorldApplet.class"
 width = "320" height = "120">
 If an applet resides in a package other than the default, the holding package must be
specified in the code attribute using the period character (.) to separate package/class
components. For example −
 <applet = "mypackage.subpackage.TestApplet.class" width = "320" height = "120">

ALGORITHM

Step1: Create a class Smiley that extends the Applet class to draw a Smiley face using
applet code.
Step 2: The java.applet.Applet class provides method paint () that returns the image object.
Step 3: Draw the Smiley image using drawPolygon(), drawArc(), drawLine(), fillOval()
methods.

SAMPLE OUTPUT

C:\>javac Smiley.java
C:\>AppletViewer Smiley.java 

Page 43
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

RESULT

Thus a simple Java program to demonstrate the applet concept was executed and verified
successfully.

Ex.No:16 ESTABLISHING JDBC CONNECTION IN JAVA

AIM

To write a java program that connects to a database using JDBC and perform add, delete,
modify and retrieve operations in student database.

What is JDBC ?

Page 44
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

JDBC is an acronym for Java Database Connectivity. It’s an advancement for


ODBC ( Open Database Connectivity ). JDBC is anstandard API specification developed in
order to move data from frontend to backend. This API consists of classes and interfaces written
in Java. It basically acts as an interface (not the one we use in Java) or channel between your
Java program and databases i.e it establishes a link between the two so that a programmer could
send data from Java code and store it in the database for future use.

Why JDBC came into existence ?

JDBC is an advancement for ODBC, ODBC being platform dependent had a lot of
drawbacks. ODBC API was written in C, C++, Python, Core Java and as we know above
languages (except Java and some part of Python) are platform dependent.

Steps for connectivity between Java program and database

1.Loading the Driver


To begin with, first load the driver or register it before using it in the program . Registration
is to be done once in the program. Register a driver in one of two ways mentioned below :

 Class.forName() : Here we load the driver’s class file into memory at the runtime. No
need of using new or creation of object .The following example uses Class.forName() to
load the Oracle driver –

Class.forName(“oracle.jdbc.driver.OracleDriver”);

  DriverManager.registerDriver(): DriverManager is a Java inbuilt class with a static


member register. Here we call the constructor of the driver class at compile time . The
following example uses DriverManager.registerDriver()to register the Oracle driver –

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
2. Create the connections

After loading the driver, establish connections using :

Connection con = DriverManager.getConnection(url,user,password)


user – username from which your sql command prompt can be accessed.
password – password from which your sql command prompt can be accessed.
con: is a reference to Connection interface.
url : Uniform Resource Locator. It can be created as follows:
String url = “ jdbc:oracle:thin:@localhost:1521:xe”
Where oracle is the database used, thin is the driver used , @localhost is the IP Address where
database is stored, 1521 is the port number and xe is the service provider. All 3 parameters above
are of String type and are to be declared by programmer before calling the function. Use of this
can be referred from final code.

3. Create a statement

Page 45
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Once a connection is established ywe can interact with the database. The JDBCStatement,
CallableStatement, and PreparedStatement interfaces define the methods that enable us to send
SQL commands and receive data from your database.

Use of JDBC Statement is as follows:


Statement st = con.createStatement();
Here, con is a reference to Connection interface used in previous step .

4. Execute the query

Now comes the most important part i.e executing the query. Query here is an SQL Query .
There are multiple types of queries. Some of them are as follows:
 Query for updating / inserting table in a database.
 Query for retrieving data .
The executeQuery() method of Statement interface is used to execute queries of retrieving
values from the database. This method returns the object of ResultSet that can be used to get all
the records of a table.
The executeUpdate(sql query) method of Statement interface is used to execute queries of
updating/inserting .

Example:
int m = st.executeUpdate(sql);
if (m==1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");

Here sql is sqlquery of the type String

5. Close the connections

So finally once the data has been sent to the specified location, we are at the verge of
completion of the task . By closing connection, objects of Statement and ResultSet will be closed
automatically. The close() method of Connection interface is used to close the connection.
Example :
con.close

ALGORITHM

Step 1: Start the program


Step 2: Create a class for the student.
Step 3: Load the Driver class
Step 4: Create a Connection object
Step 5: Create a Statement object
Step 6: Get the Connection and execute the create, retrieve, update and delete operations on an SQL
Command

Page 46
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE

Step 7: Close the Connection object, Statement object.


st.close(); cn.close();

SAMPLE OUTPUT

RESULT

Thus a java program that connects to a database using JDBC to perform add, delete,
modify and retrieve operations in student database was created and executed successfully.

Page 47

Вам также может понравиться