Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

APJ ABDUL KALAM TECHNOLOGICAL UNIVERSITY

Third Semester B.Tech Degree Examination December 2022 (2019 scheme)


Course Code: CST205
Course Name: OBJECT ORIENTED PROGRAMMING USING JAVA
Max. Marks: 100 Duration: 3 Hours

PART A
Answer all questions. Each question carries 3 marks
Marks

1) How is platform independence achieved in java? (3)

Byte code implementation makes java a platform independent language.Byte code is a machine
code for JVM.Byte code is a machine independent language.It is an intermediate code that is not
completely compiled. The Java compiler generate byte code for JVM rather than different machine
code for each type of machine. JVM executes the byte code generated by compiler and produce
output.JVM is the one that makes java platform independent. Java language and Java Virtual
Machine helped in achieving the goal of “write once; run anywhere, any time, forever.” Changes
and upgrades in operating systems, processors and system resources will not force any changes in
Java programs. Java compiler (javac) compiles *.java files to obtain *.class files that contain the
byte codes understood by the JVM.Thus platform independence is achieved.

2) Explain how garbage collection is done in Java? (3)

• When JVM starts up, it creates a heap area which is known as runtime data area. This is where
all the objects (instances of class) are stored.
• Since this area is limited, it is required to manage this area efficiently by removing the objects
that are no longer in use.
• The process of removing unused objects from heap memory is known as Garbage collection and
this is a part of memory management in Java.
• Languages like C/C++ don’t support automatic garbage collection, however in java, the garbage
collection is automatic.
• In java, garbage means unreferenced objects.
• Main objective of Garbage Collector is to free heap memory by destroying unreachable objects.
• Unreachable objects : An object is said to be unreachable iff it doesn’t contain any reference to
it.
• Eligibility for garbage collection : An object is said to be eligible for GC(garbage collection) iff
it is unreachable.
• finalize() method – This method is invoked each time before the object is garbage collected and
it perform cleanup processing.
• The Garbage collector of JVM collects only those objects that are created by new keyword. So
if we have created any object without new, we can use finalize method to perform cleanup
processing.
Request for Garbage Collection
• We can request to JVM for garbage collection however, it is upto the JVM when to start the
garbage collector.
• Java gc() method is used to call garbage collector explicitly.
• However gc() method does not guarantee that JVM will perform the garbage collection.
• It only request the JVM for garbage collection. This method is present in System and Runtime
class.

3) Explain the use of static variable with the help of an example. (3)

When a variable is declared as static, then a single copy of the variable is created and shared among
all objects at the class level. Static variables are, essentially, global variables. All instances of the
class share the same static variable.
Example:
public class StaticKeywordExample {
private static int count = 0; // static variable
public static void printCount() { // static method
System.out.println("Number of Example objects created so far: " + count);
}
}
As you can see above, we declared the count variable as a static variable, while we declared the
printCount method as a static method.
When a variable is declared static in Java programming, it means that the variable belongs to the
class itself rather than to any specific instance of the class. This means that there is only one copy
of the variable in memory, regardless of how many instances of the class are created.

4) Can final modifier be used with an abstract class.?Justify your answer. (3)

No, you cannot make an abstract class or method final in Java because the abstract and final are
mutually exclusive concepts. An abstract class is incomplete and can only be instantiated by
extending a concrete class and implementing all abstract methods, while a final class is considered
complete and cannot be extended further. This means when you make an abstract class final, it
cannot be extended hence it cannot be used and that's why the Java compiler throws a compile-
time error when you try to make an abstract class final in Java. In short, an abstract class cannot
be final in Java, using both abstract and final modifiers with a class is illegal in Java.
5) Differentiate between the usage of keywords throw and throws. (3)
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword.
Example:
Java program to demonstrate the working of throw keyword in exception handling

public class GFG {


public static void main(String[] args)
{
// Use of unchecked Exception
try {
// double x=3/0;
throw new ArithmeticException();
}
catch (ArithmeticException e) {
e.printStackTrace();
}
}
}
Output:
java.lang.ArithmeticException

The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions.
If there occurs any unchecked exception such as NullPointerException, it is programmers fault
that he is not performing check up before the code being used.

6) Explain the significance of CLASSPATH environment variable in Java. (3)

CLASSPATH is an environment variable (i.e., global variables of the operating system available
to all the processes) needed for the Java compiler and runtime to locate the Java packages/classes
used in a Java program.

7) List any three event sources and their corresponding event types and listeners used.
(3)
An event is an object that describes a state change in a source.The components in user interface
that can generate the events are the sources of the event. A listener is an object that is notified
when an event occurs.
i)Button - Generates action events when the button is pressed.
The ActionListener Interface is invoked when an action event is generated.
This interface defines the actionPerformed( ) method that is invoked when an action event occurs.
Its general form is shown here:
void actionPerformed(ActionEvent ae )

ii)Check box - Generates item events when the check box is selected or deselected.
The ItemListener Interface is invoked when an item event is generated.
This interface defines the itemStateChanged( ) method that is invoked when the state of an item
changes. Its general form is shown here:
void itemStateChanged(ItemEvent ie )

iii)Text components - Generates text events when the user enters a character.
The TextListener Interface is invoked when a text event is generated.
This interface defines the textChanged( ) method that is invoked when a change occurs in a text
area or text field. Its general form is shown here:
void textChanged(TextEvent te )

8) Illustrate the creation of arraylist with the help of a sample program. (3)

ArrayList provides us with dynamic arrays in Java.


ArrayList<String> alist=new ArrayList<String>();
This statement creates an ArrayList with the name alist with type “String”. The type determines
which type of elements the list will have. Since this list is of “String” type, the elements that are
going to be added to this list will be of type “String”.
Similarly we can create ArrayList that accepts int elements.
ArrayList<Integer> list=new ArrayList<Integer>();

Program
import java.util.*;
class JavaExample
{
public static void main(String args[])
{
ArrayList<String> alist=new ArrayList<String>();
alist.add("Steve");
alist.add("Tim");
alist.add("Lucy");
alist.add("Pat");
alist.add("Angela");
alist.add("Tom");
//displaying elements
System.out.println(alist);
//Adding "Steve" at the fourth position
alist.add(3, "Steve");
//displaying elements
System.out.println(alist);
}
}
Output:
[Steve,Tim,Lucy,Pat,Angela,Tom]
[Steve,Tim,Lucy,Steve,Pat,Angela,Tom]

9) Compare Swing API and AWT API. (3)

10) What are layout managers? List any two layout managers. (3)

• A layout manager automatically arranges our controls within a window by using some type of
algorithm.
• Each Container object has a layout manager associated with it.
• A layout manager is an instance of any class that implements the LayoutManager interface.
• The layout manager is set by the setLayout( ) method.If no call to setLayout( ) is made, then the
default layout manager is used.
• The setLayout( ) method has the following general form:
void setLayout(LayoutManager layoutObj)
• The layout manager is notified each time we add a component to a container.
• Each layout manager keeps track of a list of components that are stored by their names.
• Whenever the container needs to be resized, the layout manager is consulted via its
minimumLayoutSize( ) and preferredLayoutSize( ) methods.
– Each component that is being managed by a layout manager contains the getPreferredSize() and
getMinimumSize( ) methods.
• Java has several predefined LayoutManager classes,
– FlowLayout
– BorderLayout
– GridLayout
– CardLayout
– GridBagLayout

PART B
Answer any one full question from each module. Each question carries 14 marks
MODULE 1

11) a)Consider the problem of a Service Station which provides three types of services to its
customers: refuelling, vehicle maintenance and parking. Customer can pay using cash, card
or cheque. The pricing for vehicle maintenance depends on the cost of parts and labour.
Parking areas are rented according to weekly and monthly rates. Construct an UML class
diagram for the above problem by identifying atleast six entities in the system which can be
represented using classes and show the relationship between them.

(10)

b) Describe programming structure of Java that deals with the organization of Java
code. (4)

A typical structure of a Java program contains the following elements:


• Documentation Section
• Package Declaration
• Import Statements
• Interface Section
• Class Definition
• Main Method Class

Documentation section
• You can write a comment in this section. It helps to understand the code. These are optional
• It is used to improve the readability of the program.

Package declaration
• It is an optional part of the program, i.e., if you do not want to declare any package, then there
will be no problem with it, and you will not get any errors.
• Package is declared as: package package_name;
Eg: package mypackage;

Import Statement
• If you want to use a class of another package, then you can do this by importing it directly into
your program.
• Many predefined classes are stored in packages in Java
• We can import a specific class or classes in an import statement.

Interface section
• This section is used to specify an interface in Java
• Interfaces are like a class that includes a group of method declarations
• It's an optional section and can be used when programmers want to implement multiple
inheritances within a program.

Class Definition
• A Java program may contain several class definitions.
• Classes are the main and essential elements of any Java program.
• A class is a collection of variables and methods

Main Method Class


• The main method is from where the execution actually starts and follows the order specified for
the following statements
• Every Java stand-alone program requires the main method as the starting point of the program.
• This is an essential part of a Java program.
12) a) Differentiate between the two main approaches of software design. (7)

Software design is a process to transform user requirements into some suitable form, which helps
the programmer in software coding and implementation.
The design process for software systems often has two levels. At the first level the focus is on
deciding which modules are needed for the system on the basis of SRS (Software Requirement
Specification) and how the modules should be interconnected.
Software design is the first step in SDLC (Software Design Life Cycle).It tries to specify how to
fulfill the requirements mentioned in SRS document.

Functional Oriented Design (FOD)

In function-oriented design, the system is comprised of many smaller sub-systems known as


functions.
These functions are capable of performing significant task in the system
Function oriented design inherits some properties of structured design where divide and conquer
methodology is used.
This design mechanism divides the whole system into smaller functions
These functional modules can share information among themselves by means of information
passing and using information available globally.

Eg: Banking process


Here withdraw, Deposit, Transfer are functions and that can be divided in to sub-functions
again.So, in FOD, the entire problem is divided in to number of functions and those functions
are broken down in to smaller functions and these smaller functions are converted in to software
modules.

Object Oriented Design (OOD)

OOD is based on Objects and interaction between the objects


Interaction between objects is called message communication.
It involves the designing of Objects, Classes and the relationship between the classes

Consider the previous example of Banking process.


Here, customer, money and account are objects
In OOD, implementation of a software based on the concepts of objects.
This approach is very close to the real-world applications
b) Construct a UML Activity diagram for an online Hotel Reservation System, which
shows the flow of activities for booking rooms at a hotel. (7)

MODULE 2

13)
(a)Write a Java program by creating a ‘Student’ class having the following data
members: rollNumber, name, mathMarks, phyMarks, chemMarks and methods
getRequiredDetails() – to get required input and displayAverage() – to calculate average
marks and display it. In class ‘Implement’ create an object of the Student class and get the
required details from user and display the average marks of that student. (7)

import java.util.Scanner;
class Student{
int rollNumber;
double mathMarks, phyMarks, chemMarks, avg;
String name;
void getRequiredDetails(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter Roll No. of Student");
rollNumber = sc.nextInt();
System.out.println("Enter Name of Student: ");
name = sc.next();
System.out.println("Input marks in Mathematics: ");
mathMarks = sc.nextDouble();
System.out.println("Input marks in Physics: ");
phyMarks = sc.nextDouble();
System.out.println("Input marks in Chemistry: ");
chemMarks = sc.nextDouble();
}
void displayAverage(){
avg=(mathMarks+phyMarks+chemMarks)/3;
System.out.println("Average Mark is : " + avg);
}
}
class Implement{
public static void main(String [] args){
Student st = new Student();
st.getRequiredDetails();
st.displayAverage();
}
}

(b)Write a java program that illustrates how ‘this’ keyword can be used to resolve the
ambiguity between formal parameters and instance variables. (7)
14)
(a) Explain the concept of method overloading with the help of a program. (7)

With method overloading, multiple methods can have the same name with different parameters
● Method overloading is one of the ways that Java supports polymorphism.
● There are two ways to overload the method in java
○ By changing number of arguments
○ By changing the data type
Example:

Advantage of method overloading:


● The main advantage of this is cleanliness of code.
● Method overloading increases the readability of the program.
● Flexibility
Example - Consider the following example, which have two methods that add numbers of different
type
Instead of defining two methods that should do the same thing, it is better to overload one.
(b)What is inheritance? Illustrate hierarchical inheritance using a sample Program. (7)

● Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
● The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes.
● When you inherit from an existing class, you can reuse methods and attributes of the parent
class. Moreover, you can add new methods and attributes in your current class also
● Inheritance represents the IS-A relationship which is also known as a parent-child
relationship.
● Syntax: 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 a parent or superclass,
and the new class is called child or subclass.
Hierarchical Inheritance Example:

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
}}

MODULE 3

15)
(a)Write a program to read the first n characters in a file, where n is given by the user. The
characters read from file has to be reversed and displayed on screen. Built in methods can
be used in the program. (7)
import java.io.*;
import java.util.Scanner;
class FileReverse{
public static void main(String [] args) throws IOException{
char [] rev = new char[200];
int k=0,i, n;
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of Characters: ");
n = sc.nextInt();
FileReader fr = new FileReader("text.txt");
while (( i = fr.read()) != -1 && k!=n){
rev[k] = (char)i;
k++;
}
for(int p=n; p>=0; p--){
System.out.print(rev[p]);
}
}
}

(b)Explain the role of access modifiers when packages are used in Java. (7)
There are four types of Java access modifiers:
● Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
● Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
● Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
● Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.
16)
(a)Create a user defined exception ‘InvalidAgeException’. Write a Java program that takes
age as a Command Line Argument. Raise the Exception ‘InvalidAgeException’ if age is less
than 18.

import java.util.Scanner;

class InvalidAgeException extends Exception {

public InvalidAgeException(String str) {


System.out.println(str);
}
}
class AgeExcDemo {

public static void main(String[] args) {


int age = Integer.parseInt(args[0]);

try {
if(age < 18)
throw new InvalidAgeException("Invalid age");
else
System.out.println("Valid age");
}
catch (InvalidAgeException a) {
System.out.println(a);
}
}
}

(b)Explain the concept of Serialization and demonstrate how an object can be serialized with
a sample program.

● Serialization in Java is the process of converting the Java code Object into a Byte Stream,
to transfer the Object Code from one Java Virtual machine to another and recreate it using
the process of Deserialization.
● Most impressive is that the entire process is JVM independent, meaning an object can be
serialized on one platform and deserialized on an entirely different platform.
● For serializing the object, we call the
writeObject() method of ObjectOutputStream,
and for deserialization we call the readObject()
method of ObjectInputStream class.
● We must have to implement the Serializable
interface for serializing the object.
● Advantages of Java Serialization
○ It is mainly used to travel object's state
on the network (which is known as
marshaling).

MODULE 4
17)
(a) Illustrate the event handling mechanism in Java using the Delegation Event Model with
the help of a diagram. (8)
(b) Illustrate the usage of the following methods related to String with appropriate sample
code. (6)
(i) find() (ii)substring() (iii) replace() (ii)substring( )

We can extract a substring using substring( ).


It has two forms.

1. The first is :String substring(int startIndex)


• Here, startIndex specifies the index at which the substring will begin. This form returns a copy
of the substring that begins at startIndex and runs to the end of the invoking string.
2. The second form of substring( ) allows to specify both the beginning and ending index of the
substring: String substring(int startIndex, int endIndex)
• Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The
string returned contains all the characters from the beginning index, up to, but not including, the
ending index

(iii) replace( )

replace( ) -The replace( ) method has two forms.

1. The first form replaces all occurrences of one character in the invoking string with another
character. String replace(char original, char replacement)
◦ Here, original specifies the character that will be replaced by the character specified by
replacement.The resulting string is returned.
String s = "Hello".replace('l', 'w');
◦ Here letter l is replaced by w. So “Hewwo” is put into String object s.
2. The second form of replace( ) replaces one character sequence with another. String
replace(CharSequence original, CharSequence replacement)

18)
(a) What is multithreading? Write a multithreaded Java program that demonstrates the
working of wait() and notify() methods. (7)

Multithreading in Java is a process of executing multiple threads simultaneously. A thread is a


lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both
are used to achieve multitasking. However, we use multithreading than multiprocessing because
threads use a shared memory area. They don't allocate separate memory area so saves memory,
and context-switching between the threads takes less time than process. Java Multithreading is
mostly used in games, animation, etc.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.
(b) Explain how ActionEvent class and FocusEvent class is used with emphasis on the
methods and constants provided by the given classes (7)

The ActionEvent Class


● An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a
menu item is selected. The ActionEvent class defines four integer constants that can be
used to identify any modifiers associated with an action event: ALT_MASK
,,CTRL_MASK , META_MASK , and SHIFT_MASK .
● ActionEvent has these three constructors:
○ ActionEvent(Object src , int type , String cmd )
○ ActionEvent(Object src , int type , String cmd , int modifiers )
○ ActionEvent(Object src , int type, String cmd, long when , int modifiers )

The FocusEvent Class


The component-level focus event. There are two levels of focus change events: permanent and
temporary. Permanent focus change events occur when focus is directly moved from one
component to another, such as through calls to requestFocus() or as the user uses the Tab key to
traverse components. Temporary focus change events occur when focus is temporarily gained or
lost for a component as the indirect result of another operation, such as window deactivation or a
scrollbar drag. In this case, the original focus state will automatically be restored once that
operation is finished, or, for the case of window deactivation, when the window is reactivated.
Both permanent and temporary focus events are delivered using the FOCUS_GAINED and
FOCUS_LOST event ids; the levels may be distinguished in the event using the isTemporary()
method.

Variables
o FOCUS_FIRST: Marks the first integer id for the range of focus event ids.
o FOCUS_LAST: Marks the last integer id for the range of focus event ids.
o FOCUS_GAINED: The focus gained event type.
o FOCUS_LOST: The focus lost event type.
Methods
o isTemporary: Returns whether or not this focus change event is a temporary change.
o paramString: Overrides paramString in class ComponentEvent

MODULE 5

19)
(a)Write a Java program that uses two textfields and a button. The first textfield accepts
temperature in Celsius. When the ‘Convert’ button is clicked the second textfield displays
the temperature in Fahrenheit. Use appropriate Swing components and event handling
techniques. F=(C*9/5)+32 (9)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TemperatureConverter extends JFrame implements ActionListener {


JTextField celsiusTextField;
JButton convertButton;
JLabel fahrenheitLabel;

public TemperatureConverter() {

// Set up the user interface


JFrame jfrm = new JFrame("Temperature Converter");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(800, 200);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel celsiusLabel = new JLabel("Celsius:");
celsiusTextField = new JTextField(10);
fahrenheitLabel = new JLabel("Temperature in Fahrenheit: ");
convertButton = new JButton("Convert");
convertButton.addActionListener(this);

jfrm.add(celsiusLabel);
jfrm.add(celsiusTextField);
jfrm.add(convertButton);
jfrm.add(fahrenheitLabel);
jfrm.setVisible(true);
}

public void actionPerformed(ActionEvent e) {


if (e.getSource() == convertButton) {
// Get the temperature in Celsius
String celsiusText = celsiusTextField.getText();
double celsius = Double.parseDouble(celsiusText);

// Convert the temperature to Fahrenheit


double fahrenheit = (celsius * 9 / 5) + 32;
// Set the temperature in Fahrenheit text field
fahrenheitLabel.setText(String.format("Temperature in Fahrenheit: " + fahrenheit));
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TemperatureConverter();
}
});
}
}

(b) Describe the two different ways to create frames using Swing package with appropriate
examples. (7)

The Swing package provides two different ways to create frames:

Extending the JFrame Class:


One way to create a frame in Swing is to create a class that extends the JFrame class. This approach
allows you to create a custom frame by adding components, customizing the look and feel, and
adding event listeners.

Here is an example of creating a frame by extending the JFrame class:

import javax.swing.*;

public class MyFrame extends JFrame {


public MyFrame() {
super("My Frame");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[] args) {


new MyFrame();
}
}
In this example, we create a class MyFrame that extends the JFrame class. In the constructor of
the MyFrame class, we set the title of the frame, its size, and its default close operation. We also
make the frame visible.

In the main() method, we create an instance of the MyFrame class, which creates and displays the
frame.

Creating an Instance of the JFrame Class:


Another way to create a frame in Swing is to create an instance of the JFrame class and add
components to it. This approach is useful when you want to create a simple frame without much
customization.

Here is an example of creating a frame by creating an instance of the JFrame class:

import javax.swing.*;

public class MyFrame {


public static void main(String[] args) {
JFrame frame = new JFrame("My Frame");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

In this example, we create an instance of the JFrame class and set its title, size, and default close
operation. We also make the frame visible.

In both approaches, we use the setSize() method to set the size of the frame, the
setDefaultCloseOperation() method to set the default close operation of the frame, and the
setVisible() method to make the frame visible.

Note: It is generally recommended to create a class that extends JFrame when you want to create
a custom frame with more complex functionality, and to create an instance of JFrame when you
want to create a simple frame with basic functionality.
20)
(a) Discuss the Model View Controller (MVC) Architecture using a diagram. Also list out
the advantages of writing programs based on MVC Architecture. (7)

• A visual component is a composite of three distinct aspects:


– The state information associated with the component MODEL
– The way that the component looks when rendered on the screen VIEW
– The way that the component reacts to CONTROLLER
• MVC (Model View Controller) architecture is successful because each piece of the design
corresponds to an aspect of a component.
• In MVC terminology,
– the Model corresponds to the state information associated with the component.
• For example, in the case of a check box, the model contains a field that indicates if the box
is checked or unchecked.
– The View determines how the component is displayed on the screen, including any
aspects of the view that are affected by the current state of the model.
– The Controller determines how the component reacts to the user.
• For example, when the user clicks a check box, the controller reacts by changing the model
to reflect the user’s choice (checked or unchecked). So view changes.
• By separating a component into a model, a view, and a controller, the specific
implementation of each can be changed without affecting the other two.
• Swing uses a modified version of MVC that combines the view and the controller into a
single logical entity called the UI delegate.
– So, Swing’s approach is called either the Model-Delegate architecture or the Separable
Model architecture.
• Swing’s pluggable look and feel is made possible by its Model-Delegate architecture.
• Because the view (look) and controller (feel) are separate from the model, the look and feel
can be changed without affecting how the component is used within a program.
• To support the Model-Delegate architecture, most Swing components contain two objects.
– The first represents the model.
• Models are defined by interfaces
– The second represents the UI delegate.
• UI delegates are classes that inherit ComponentUI.
(b) Explain the various steps for connecting to database using JDBC API, using a sample
program. (7)

Basic Steps to use a Database in Java


1.Establish a connection
2.Create JDBC Statements
3.Execute SQL Statements
4.GET ResultSet
5.Close connections

1. Establish a Connection
import java.sql.*;
Load the vendor specificdriver
◦ Class.forName("oracle.jdbc.driver.OracleDriver");
Dynamically loads a driver class, for Oracledatabase
Make the connection
◦ Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@oracle-prod:1521:OPROD",
username, passwd);

Establishes connection to database by obtaining a Connection object

2. Create JDBC Statements


Statement stmt = con.createStatement();
Creates a Statement object for sending SQL statements to the database

3. Execute SQL Statements

String createLehigh = "Create table Lehigh " + "(SSN Integer not


null, Name VARCHAR(32), " + "Marks Integer)";
stmt.executeUpdate(createLehigh);
String insertLehigh = "Insert into Lehigh values“ +"(123456789,abc,100)";
stmt.executeUpdate(insertLehigh);

4. Get ResultSet

String queryLehigh = "select * from Lehigh";


ResultSet rs = Stmt.executeQuery(queryLehigh);
while (rs.next()) {
int ssn = rs.getInt("SSN");
String name = rs.getString("NAME");
int marks = rs.getInt("MARKS");
}

5. Close Connection

stmt.close();
con.close();
rs.close()

You might also like