Академический Документы
Профессиональный Документы
Культура Документы
INTRODUCTION
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
These include:
Objects
Classes
Data abstraction and encapsulation
Inheritance
Polymorphism
Dynamic binding
Message passing
Page 2
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE
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.
J2SE 1.3 (Kestrel) 8th May Java Sound, Java Indexing, JNDI
2000
J2SE 1.4 (merlin) 6th Feb 2002 Assert, regex, exception chaining,
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.
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.
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.
Page 6
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE
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
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.
fields
methods
constructors
blocks
nested class and interface
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.
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
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
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
DESCRIPTION
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
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
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
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
class Super {
.....
.....
}
Page 13
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE
ALGORITHM
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
AIM
To design a java interface for stack ADT. Implement this interface using array. Provide
necessary exception handling in both the implementations.
DESCRIPTION
Page 15
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE
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
Page 16
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE
SAMPLE OUTPUT
D:\>javac StackADT.java
D:\>java StackADT
Page 17
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE
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.
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
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
Method Description
void add(int index, Object It is used to insert the specified element at the specified
element) position index in a list.
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.
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.
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.
ALGORITHM
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]
Rahul
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
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.
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 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.
Page 23
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE
SAMPLE OUTPUT
D:\>javac Abst.java
D:\>java Abst
Thus the java application to demonstrate the concept of abstract class and abstract
method was developed and executed successfully.
VIVA QUESTIONS
DESCRIPTION
WHAT IS EXCEPTION?
Exception is an abnormal condition.
Page 24
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE
1. try
2. catch
3. finally
4. throw
5. throws
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 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
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
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
ALGORITHM
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
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
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.
Advantages of Multithreading:
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
SAMPLE OUTPUT
D:\>javac Mthread.java
D:\>java Mthread
Page 30
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE
RESULT
Thus the java program to implement multi-threaded application was developed and
executed successfully.
VIVA QUESTION
AIM
To write a java program to find the maximum value from the given type of elements
using a generic functions.
DESCRIPTION
Page 31
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE
Generic class
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
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
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
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.
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.
ALGORITHM
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
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.
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
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.
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.
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.
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.
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.
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 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.
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(new oracle.jdbc.driver.OracleDriver())
2. Create the connections
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.
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");
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
Page 46
CS8382 - OBJECT ORIENTED PROGRAMMING LABORATORY III Semester CSE
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