0% found this document useful (0 votes)
12 views

Solved Question Paper

Uploaded by

Shivam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Solved Question Paper

Uploaded by

Shivam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Unit-1

Q1. Comparison between console application, GUI application & web Application.
Solution
 Java programming language provides several ways in order to take input from the console and
provide its corresponding output on the same console.
 A Java console application is a program that runs in a text-based interface and takes input
and output from the user or the system.
 It can be used for debugging, testing, or solving business use cases.
 To run a Java console application, you need to enable the Java Console, which provides
information about the Java version and any error message.
 You can also create a menu to display the options for the user.
Java Console
Using the Console in Java, we can consider taking input and displaying the output. Generally,
Console is mainly meant for taking input. There are three ways to take the input from the Java
console. They are:
1. Using Java Scanner class (Basic level)
2. Using Java BufferedReader class (Intermediate level)
3. Using Java Console class
Scanner class in Java
 A class that is used to scan inputs within the program is known as the Scanner class.
 We use this class to take the input within the program by creating an abject in the Scanner
class.
 It is one of the easiest ways to scan the input from the user using the console.
 It is used to scan all the regular expressions in Java. The Scanner class is available in the util
package.
 So, in order to scan the inputs using the Scanner class, we need to import the " Java.util "
package.
Syntax of Scanner class:
Scanner obj = new Scanner(System.in);
Here, " Scanner " is considered as a class and " obj " is an object that is created within a class.
Example
Write a program in java to input roll.no. and name of the student using scanner class and
print the details.
Source Code:
import java.util.Scanner;
public class program1 {
public static void main(String[] args)
{
Scanner in= new Scanner(System.in);
System.out.println("Enter your Roll Number:");
int rno= in.nextInt();
System.out.println("Enter your Name:");
in.nextLine();
String name = in.nextLine(); System.out.println("HELLO " + name);
}
}
Output

2. BufferedReader class in Java


 It is one of the classical methods of taking input from the user (sometimes by using a console
also).
 A new statement, " InputStreamReader " is also introduced along with the " BufferedReader "
in order to scan the input values using BufferedReader.
Syntax of BufferedReader class:
InputStreamReader obj1 = new InputStreamReader(System.in);
or
BufferedReader obj2 = new BufferedReader(obj1);
Example
Write a program in java to input roll.no. and name of the student using BufferedReader class and
print the details.
Source Code:
import java.io.*;
public class program2 {
public static void
main(String[] args) throws
IOException{
InputStreamReader r=new
InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your Roll No:");
int rn= Integer.parseInt(br.readLine());
System.out.println("Enter your name:");
String name=br.readLine();
System.out.println("Your Roll No is " + rn);
System.out.println("Your Name No is " + name);
}
}
Output

Java Console class in Java


• The class " Console " in Java was introduced from Java version 1.5.
• The class " Console " can be accessed through the package " Java.io " .
Advantages
• The confidential data or information like passwords are hidden while taking input as well as
printing output.
• The methods of the console that can be read are also always synchronized.
Disadvantages
The Console class can only be executed on command prompt or terminal but not on any other IDE
platforms.

GUI Application in Java


 GUI, or Graphical User Interface, is a visual experience builder for Java applications that
allows users to interact with an application through graphical units like buttons, labels, and
windows.
 Swing and JavaFX are two commonly used applications to create GUIs in Java.
 Swing has a deeper integration with operating systems, but has a dated look-and-feel, while
JavaFX provides amazing functionality with a CSS layer that makes design easy and separates
functionality, layout, and design for more flexibility.
 GUI (Graphical User Interface) in Java is an easy-to-use visual experience builder for Java
applications.
 It is mainly made of graphical components like buttons, labels, windows, etc. through which
the user can interact with an application.
 GUI plays an important role to build easy interfaces for Java applications.
Example
import javax.swing.*;
public class Console_program {
public static void main(String[] args)
{
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
JButton button = new JButton("Press");
frame.getContentPane().add(button); // Adds Button to content pane of frame
frame.setVisible(true);
}
}
Output

Web Application in Java


 A Java web application is a type of software that uses Java technologies to run on the internet
and interact with users.
 It is developed with J2EE web components, such as Servlets and JSPs, and deployed on a web
server or a J2EE application server.
 Java web applications are portable, as they can run on any Java Virtual Machine, regardless of
the operating system and architecture.
 Java is one of the most popular programming languages for web development.
 Java Web Application is used to create dynamic websites.
 Java provides support for web application through Servlets and JSPs.
 We can create a website with static HTML pages but when we want information to be dynamic,
we need web application.
Features of Web Application:
 Web applications are distributed applications by nature. This means that any program that runs
on more than one computer and communicates using the network and server.
 Web applications are accessed using a web browser so they are very popular for the ease of
using the browser as a user client.
 The ability to update and maintain web applications without installing any software on
thousands of client computers becomes a key reason for the demand.
 Using many components web applications are created, some of which have a user interface
and some of which do not require a graphical user interface (GUI).
 Web applications frequently require an additional markup or scripting language, such as
HTML, CSS, or JavaScript programming language.
 Many applications use only the Java programming language, which is ideal because of its
versatility. Example: Java Servlets and JSP.
The Flow of the Web Application
Let's understand how the flow of the typical web application looks like.

1. In general, a user sends a request to the web-server using web browsers such as Google
Chrome, Microsoft Edge, Firefox, etc over the internet.
2. Then, the request is forwarded to the appropriate web application server by the web-server.
3. Web application server performs the requested operations/ tasks like processing the
database, querying the databases; produces the result of the requested data.
4. The obtained result is sent to the web-server by the web application server along with the
requested data/information or processed data.
5. The web server responds to the user with the requested or processed data/information and
provides the result to the user's screen .
S.No Console Application GUI Application
1 Console applications are light Windows Applications are
weight programs run inside form based standard Windows
the command prompt (DOS) desktop applications for
window. common day to day tasks.
2 They are commonly used for They are used for creating
test applications. Windows Applications.

3 Console programs are Many modern GUI


generally monochromatic and frameworks provide themed
don't animate much. widgets and have
move/size/show/hide
animation effects.
4 Console apps sometimes use GUI app gives us full
ASCII art for diagrams graphical ability.
5 A console program tends to be A GUI program tends to be
refined over time screwed.
6 Console-based applications Microsoft word is an example
include Alpine (an e-mail of a Windows application.
client), cmus (an audio
player), Irssi (an IRC client),
Lynx (a web browser).

Q2. Importance of Core Java while using advanced java features.


Solution:
Core Java focuses on the basics and covers the core language features, while Advanced Java delves
into specific domains, providing tools and libraries for building enterprise-level applications. Core
Java is necessary for all Java developers, whereas Advanced Java is specialized knowledge for
specific application development needs.
When to Use Core Java
Core Java is suitable for small-scale applications, command-line tools, basic web development,
and learning Java fundamentals. It is ideal for beginners and projects with straightforward
requirements that do not demand advanced functionality or enterprise-level capabilities.
Features of Core Java
Core Java includes various important topics like Class, Variable, Package, OOPs Concept, String,
Collection, Exception Handling, Multi-Threading, Enum, Arrays, Generics etc.

Its main pillars are inheritance, polymorphism, encapsulation, and abstraction. These are:
 Inheritance – It allows one to make use of the already existing class without even writing the
code from the very beginning. It thus ensures code reusability in a better way.
 Polymorphism – It allows the writing of code in a certain way to make the object behave in
multiple ways.
 Encapsulation – It combines methods and data into a single unit.
 Abstraction – It allows the writing of a code in a way that hides the details of implementation.
It reduces the complexity. Allows writing the code in a way that hides the implementation
details to reduce complexity.
Core Java also covers concepts like AWT, threading, swing, and collections. AWT and
swing help in building powerful GUIs (Graphical User Interfaces). Threading, furthermore, assists
in the simultaneous execution of multiple processes and the collections allow a user to manipulate
a group of objects. All-in-all, Core Java covers all the basic and fundamental Java programming
language concepts.

When to Use Advanced Java


Java is suitable for building complex, large-scale, and enterprise-level applications. It is ideal for
web development with Servlets and JSP, accessing databases with JDBC, implementing advanced
business logic with EJBs, and leveraging frameworks like Spring and Hibernate for efficient
application development.
At present, the Java Core is defined as having:
 Application monitoring and management
 Basic technologies
 CORBA
 HotSpot VM
 JNDI (Java Naming and Directory Interface)
 Tools API
 XML

Advance Java is used to build a web application and run it smoothly. Few concepts are Hibernate,
Spring, Struts, Web Services etc.

 Advance Java is required to create Web based Application and Enterprise Application.
 It mainly covers more advanced concepts like database accessing and web technologies.
 The J2EE (Java Enterprise Edition) is known as Advanced Java. It covers a wide range of
topics. The Java Database Connectivity or JDBC is a standard Java API that builds
independent connectivity between the language-based applications of Java and the
databases, like MSSQL, MySQL, and Oracle. Apart from this, JSP and Servlets also allow
the development of dynamic web applications.
Difference between Core Java and Advance Java
Criteria Core Java Advance Java
Used for It is used to develop general It is used to develop web-
purpose application. based applications.
Purpose It does not deal with database, It deals with socket
socket programming, etc. programming, DOM, and
networking applications.
Architecture It is a single tier architecture It is two-tier architecture that
that is the reason why it is is client side architecture and
called as ‘stand-alone’ server side or backend
application. architecture.
Edition It is a Java Standard Edition. It is a Java Enterprise Edition.
Package It provides java.lang.* It provides java.servlet.*
package. package.
Features OOP, data types, operators, It has some specific sections
functions, loops, exception for example, database
handling, threading are some connectivity, web services,
of the concepts. servlets and more

Q3. What are Jar Files and what are its uses?
Solution:
 A file with the .JAR file extension is a Java Archive file used for storing Java programs and
games in a single file.
 Some contain files that make them work as standalone apps, and others hold program
libraries for other programs to use.
 JAR files are ZIP compressed and store things like CLASS files, a manifest file, and
application resources like images, sound clips, and security certificates.
 They can hold hundreds or even thousands of files in a compressed format, it's easy to share
and move them.
 JAR is a file format that helps in aggregating Java class file, along with its associated metadata
and resources into a single file.
 It contains the compressed version of .class files, audio files, images files or directories.
 We can imagine a .jar files as a zipped file(.zip) that is created by using WinZip software.
 WinZip software can be used to extract the content of a .jar. so you can use them for task such
as lossless data compression, archiving, decompression and archive unpacking.

Some important points about JAR files in Java:


 This type of archiving is cross-platform in nature.
 This can handle audio and image files as well.
 There is backward compatibility. Without it being backward compatible, developers would
have to rewrite existing applets.
 This is written in Java itself.
 This is a standard of bundling up Java applets.
Functions with JAR file in Java
The basic functions of java JAR file are creating, updating, viewing and extracting.
1. In order to create a JAR file, we have to use the following syntax :
jar cf <jar_package_name> <original_package_name> .
The cf command means create-file. This creates a jar file of the package we are in currently.
Assuming that our package pack is available in c:\ directory to convert it into a jar file, we can
give the command as
C:\> jar cf pack.jar pack
2. In order to view the contents of a JAR file in table view, we can use the syntax:
jar tf <jarfilename>.jar. While displaying you may see the manifest file.
Example, C:\ > jar tf pack.jar
It will show you the following files like:
META- INF/
META- INF/ MANIFEST.MF
pack/ (Sub- Directory)
pack/ class1.class
pack/class2.class (files present in sub-directory called pack)
2. When we need to extract a file with the help of a JAR file, we can use the jar xf
<jarfilename>.jar.
This action will create a MANIFEST file and a package containing the classes.
Example, C:\> jar xf pack.jar
It will show you the
META-INFO
pack
3. If we need to update the contents of the JAR file, we can use jar -uf <jarfilename>.jar
(input_files).
4. If we need to run a JAR file, we can use the command java -jar <jarfilename>.jar

How to Open JAR Files


 The Java Runtime Environment (JRE) must be installed in order to open executable JAR
files, but note that not all JAR files are executables.
 Once installed, you can just double-click the file to open it.
 Some mobile devices have JRE built-in. Once installed, Java applications can be opened in
a web browser, too, like Firefox, Safari, Edge, etc.
 Since JAR files are compressed with ZIP, any file decompressor can open one to see the
contents that are inside. This includes programs like 7-Zip, PeaZip and jZip.
 Another way to open the file is to use the following command in Command Prompt,
replacing yourfile.jar with the name of your own JAR file:

Java Archive apps


Each installation of the Java Development Kit (JDK) includes a JAR utility (named jar.sh
on Unix and jar.exe on Windows) that provides a variety of helpful functions for working with
JAR files, including the ability to:
 create new JAR files with a manifest file;
 extract all of the contents of a JAR file onto the file system;
 update an existing JAR file by adding files to it; and
 update a JAR file's existing manifest file

Q4. Difference between AWT Controls & Swing Controls


Solution:
 AWT and Swing are used to develop window-based applications in Java.
 Awt is an abstract window toolkit that provides various component classes like Label, Button,
TextField, etc., to show window components on the screen. All these classes are part of the
Java.awt package.
 On the other hand, Swing is the part of JFC (Java Foundation Classes) built on the top of AWT
and written entirely in Java.
 The javax.swing API provides all the component classes like JButton, JTextField, JCheckbox,
JMenu, etc.
 The components of Swing are platform-independent, i.e., swing doesn't depend on the
operating system to show the components.
 The Swing's components are lightweight.

AWT: AWT also known as Abstract window toolkit. It is a platform dependent API used for
developing GUI (graphical user interface) or applications that are window based. It was developed
by Sun Microsystems In 1995 and is heavy weighted. It is generated by system’s host operating
system and contains large number of methods and class which are used for creating and managing
UI of an application. The main difference between AWT and Swing is that AWT is purely used
for GUI whereas Swing is used for both, GUI as well as for making web application.

Swing: In Java, a swing is a light-weighted, GUI (graphical user interface) that is used for creating
different applications. It has platform-independent components and enables users to create buttons
as well as scroll bars. It also includes a package for creating applications for desktops. The
components of swing are written in Java and are a part of the Java foundation class.

The main differences between AWT and Swing are given in the following table.

Context AWT Swing

API Package The AWT Component classes are The Swing component classes are
provided by the java.awt package. provided by the javax.swing package.
Operating System The Components used in AWT are The Components used in Swing are not
mainly dependent on the operating dependent on the operating system. It is
system. completely scripted in Java.

Weightiness The AWT is heavyweight since it The Swing is mostly lightweight since it
uses the resources of the operating doesn't need any Operating system object
system. for processing. The Swing Components
are built on the top of AWT.

Appearance The Appearance of AWT The Swing Components are configurable


Components is mainly not and mainly support pluggable look and
configurable. It generally depends feel.
on the operating system's look and
feels.

Number of The Java AWT provides a smaller Java Swing provides a greater number of
Components number of components in components than AWT, such as list, scroll
comparison to Swing. panes, tables, color choosers, etc.

Full-Form Java AWT stands for Abstract Java Swing is mainly referred to as Java
Window Toolkit. Foundation Classes (JFC).

Peers Java AWT has 21 peers. There is Java Swing has only one peer in the form
one peer for each control and one of OS's window object, which provides
peer for the dialogue. Peers are the drawing surface used to draw the
provided by the operating system in Swing's widgets (label, button, entry
the form of widgets themselves. fields, etc.) developed directly by Java
Swing Package.

Functionality and Java AWT many features that are Swing components provide the higher-
Implementation completely developed by the level inbuilt functions for the developer
that facilitates the coder to write less code.
developer. It serves as a thin layer of
development on the top of the OS.

Memory Java AWT needs a higher amount of Java Swing needs less memory space as
memory for the execution. compared to Java AWT.

Speed Java AWT is slower than swing in Java Swing is faster than the AWT.
terms of performance.

Java Swing Example


In the following example, we have created a User form by using the swing component classes
provided by the javax.swing package.
import javax.swing.*;
public class SwingApp {
SwingApp(){
JFrame f = new JFrame();
JLabel firstName = new JLabel("First Name");
firstName.setBounds(20, 50, 80, 20);
JLabel lastName = new JLabel("Last Name");
lastName.setBounds(20, 80, 80, 20);
JLabel dob = new JLabel("Date of Birth");
dob.setBounds(20, 110, 80, 20);

JTextField firstNameTF = new JTextField();


firstNameTF.setBounds(120, 50, 100, 20);
JTextField lastNameTF = new JTextField();
lastNameTF.setBounds(120, 80, 100, 20);
JTextField dobTF = new JTextField();
dobTF.setBounds(120, 110, 100, 20);

JButton sbmt = new JButton("Submit");


sbmt.setBounds(20, 160, 100, 30);
JButton reset = new JButton("Reset");
reset.setBounds(120,160,100,30);
f.add(firstName);
f.add(lastName);
f.add(dob);
f.add(firstNameTF);
f.add(lastNameTF);
f.add(dobTF);
f.add(sbmt);
f.add(reset);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
SwingApp s = new SwingApp();
}
}
Java awt Example
To understand the differences between Awt and Swing, we have created the same example in awt
as well.

import java.awt.*;
public class AwtApp extends Frame {
AwtApp(){
Label firstName = new Label("First Name");
firstName.setBounds(20, 50, 80, 20);

Label lastName = new Label("Last Name");


lastName.setBounds(20, 80, 80, 20);

Label dob = new Label("Date of Birth");


dob.setBounds(20, 110, 80, 20);

TextField firstNameTF = new TextField();


firstNameTF.setBounds(120, 50, 100, 20);

TextField lastNameTF = new TextField();


lastNameTF.setBounds(120, 80, 100, 20);

TextField dobTF = new TextField();


dobTF.setBounds(120, 110, 100, 20);

Button sbmt = new Button("Submit");


sbmt.setBounds(20, 160, 100, 30);

Button reset = new Button("Reset");


reset.setBounds(120,160,100,30);

add(firstName);
add(lastName);
add(dob);
add(firstNameTF);
add(lastNameTF);
add(dobTF);
add(sbmt);
add(reset);

setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
AwtApp awt = new AwtApp();
}
Output

Event Driven Programming using swing


 Change in the state of an object is known as Event, i.e., event describes the change in the state
of the source.
 Events are generated as a result of user interaction with the graphical user interface
components.
 For example, clicking on a button, moving the mouse, entering a character through keyboard,
selecting an item from the list, and scrolling the page are the activities that causes an event to
occur.
 In computer programming, event-driven programming is a programming paradigm in which
the flow of the program is determined by events such as user actions (mouse clicks, key
presses), sensor outputs, or message passing from other programs or threads.
Java Event Listener and Event Source

 In Java event-driven programming, there are two primary components: the event listener and
the event source.
 The event source is the object that generates the event, while the event listener is the object
that receives and processes the event.
 To create an event listener, you must implement the appropriate interface for the event you
want to handle.

For example, to handle action events (such as button clicks), you would implement the
ActionListener interface:

import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){

tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

//register listener
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
} }

Output
Unit -2
Q1. Role of data structure in software project.
Solution:
 A data structure is a collection of data values and the relationships between them.
 Data structures allow programs to store and process data effectively.
 There are many different data structures. Some of the most common data structures are arrays,
lists, trees, and graphs.
 The data structure isn’t a programming language like C, C++, Java, etc.
 It is a set of algorithms that can be used in any programming language to organize the data in the
memory.
Need of Data Structure
As applications are becoming more complex and the amount of data is increasing day by day,
which may cause problems with processing speed, searching data, handling multiple requests etc.
 Organizing: Data structure provides a way of organizing, managing, and storing data efficiently.
 Traversing: With the help of data structure, the data items can be traversed easily.
 Reusability: Data structure provides efficiency, reusability and abstraction.
 Enhancing performance: It plays an important role in enhancing the performance of a program
because the main function of the program is to store and retrieve the user’s data as fast as
possible.
 More on Scalability: Scalability means the quality of an algorithm/system to handle the problem
of larger size.

Example: Consider the problem of setting up a classroom of 50 students. One of the simplest
solutions is to book a room, get a blackboard, a few chalks, and the problem is solved. But what
if the size of the problem increases? What if the number of students increased to 200? The
solution still holds but it needs more resources. In this case, you will probably need a much larger
room (probably a theater), a projector screen and a digital pen.

Here are some key types of data structures commonly used in Java:
1. Arrays:
Arrays are the simplest form of data structures, providing a fixed-size sequential collection of
elements of the same type. They offer fast and direct access to elements but have a fixed size.

Code
int[] myArray = new int[]{1, 2, 3, 4, 5};
2. Linked Lists:
Linked lists allow dynamic memory allocation, overcoming the fixed size limitation of arrays.
Elements, called nodes, are linked together, and each node contains data and a reference to the
next node.

Code
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add(“Java”);
linkedList.add(“Data Structures”);

3. Stacks:
Stacks follow the Last In, First Out (LIFO) principle. Java’s Stack class extends Vector and
provides methods for stack operations like push and pop.
Code
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
int poppedElement = stack.pop(); // Returns 2
4. Queues:
Queues adhere to the First In, First Out (FIFO) principle. The Queue interface in Java
implemented using LinkedList, supports operations like add and remove.

Code
Queue<String> queue = new LinkedList<>();
queue.add(“First”);
queue.add(“Second”);
String removedElement = queue.remove(); // Returns “First”
5. Trees:
Trees are hierarchical structures with a root element and child elements. Java’s TreeSet and
TreeMap classes implement tree structures, providing efficient searching and sorting.

Code
TreeSet<Integer> treeSet = new TreeSet<>();
treeSet.add(5);
treeSet.add(2);

6. Hash Tables:
Hash tables, or HashMaps in Java, store data in key-value pairs. They offer constant-time
complexity for basic operations, making them efficient for tasks like retrieval and insertion.

Code
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put(“One”, 1);
int value = hashMap.get(“One”); // Returns 1

Q2. Java Stream Classes


Solution:
 A stream can be defined as a sequence of data. The InputStream is used to read data from a
source and the OutputStream is used for writing data to a destination.
 InputStream and OutputStream are the basic stream classes in Java.
Why we need Stream classes?
 To perform read and write operations on binary files we need a mechanism to read that binary
data on file/to write binary data (i.e. in the form of byte).
 These classes are capable to read and write one byte on binary files.
 Java provides a new additional package in Java 8 called java.util.stream. This package consists
of classes, interfaces and enum to allows functional-style operations on the elements.

 You can use stream by importing java.util.stream package.

Types of streams:
It is divided into following:

 Byte Stream: It provides a convenient means for handling input and output of byte.
 Character Stream: It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.
1. Byte Stream:
Byte Stream Classes are used to read bytes from an input stream and write bytes to an output
stream.

 InputStream Classes - These classes are subclasses of an abstract class, InputStream and
they are used to read bytes from a source (file, memory or console).
 OutputStream Classes - These classes are subclasses of an abstract class, OutputStream
and they are used to write bytes to a destination (file, memory or console).
These two abstract classes have several concrete classes that handle various devices such as disk
files, network connection etc.
Some important Byte stream classes.

Stream class Description

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.

DataInputStream Contains method for reading java standard datatype

An output stream that contain method for writing java standard data
DataOutputStream
type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

PrintStream Output Stream that contain print() and println() method

These classes define several key methods. Two most important are
1. read() : reads byte of data.

2. write() : Writes byte of data.


OutputStream class

OutputStream class is an abstract class. It is the superclass of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.
Useful methods of OutputStream
InputStream
 Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.
 Java provides I/O Streams to read and write data where, a Stream represents an input source
or an output destination which could be a file, i/o devise, other program etc.
FileInputStream
This class reads the data from a specific file (byte by byte). It is usually used to read the contents
of a file with raw bytes, such as images.
To read the contents of a file using this class −
 First of all, you need to instantiate this class by passing a String variable or a File object,
representing the path of the file to be read.

FileInputStream inputStream = new FileInputStream("file_path");

or,

File file = new File("file_path");


FileInputStream inputStream = new FileInputStream(file);

 Then read the contents of the specified file using either of the variants of read() method −
o int read() − This simply reads data from the current InputStream and returns the read data
byte by byte (in integer format). This method returns -1 if the end of the file is reached.
o int read(byte[] b) − This method accepts a byte array as parameter and reads the contents
of the current InputStream, to the given array. This method returns an integer representing
the total number of bytes or, -1 if the end of the file is reached.
o int read(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and,
its length (int) as parameters and reads the contents of the current InputStream, to the given
array. This method returns an integer representing the total number of bytes or, -1 if the
end of the file is reached.
Java Character Stream Classes
Character stream is also defined by using two abstract class at the top of hierarchy, they are Reader
and Writer. These two abstract classes have several concrete classes that handle unicode character.

Some important Charcter stream classes

Stream class Description


BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

InputStreamReader Input stream that translate byte to character


OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that contain print() and println() method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream output

Reading Console Input


We use the object of BufferedReader class to take inputs from the keyboard.

Reading Characters
read() method is used with BufferedReader object to read characters. As this function returns
integer type value has we need to use typecasting to convert it into char type.
int read() throws IOException
Example: Character input.
Source Code:
import java.io.*;
class Main
{
public static void main( String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the character");
char c = (char)br.read(); //Reading character
System.out.println("The Character is "+ c);
}
}
Output

Reading Strings in Java


To read string we have to use readLine() function with BufferedReader class's object.
String readLine() throws IOException
Example: Program to take String input from Keyboard in Java
Source Code:
import java.io.*;
class Main {
public static void main(String[] args)throws IOException
{
String text;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String");
text = br.readLine(); //Reading String
System.out.println(" The String is "+text);
}
}

Output

Q3. Explain the java collection classes.


Solution:
 A Collection represents a single unit of objects, i.e., a group.
 The Collection in Java is a framework that provides an architecture to store and manipulate the
group of objects.
 Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.
 Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet).
What is a framework in Java?
 It provides readymade architecture.
 It represents a set of classes and interfaces.
 It is optional.
What is Collection framework
The Collection framework represents a unified architecture for storing and manipulating a group
of objects. It has:
 Interfaces and its implementations, i.e., classes
 Algorithm
Hierarchy of Collection Framework
The java.util package contains all the classes and interfaces for the Collection framework.

Methods of Collection interface


There are many methods declared in the Collection interface. They are as follows:
No. Method Description

1 public boolean add(E e) It is used to insert an element in this collection.

2 public boolean addAll(Collection<? It is used to insert the specified collection


extends E> c) elements in the invoking collection.

3 public boolean remove(Object It is used to delete an element from the


element) collection.

4 public boolean It is used to delete all the elements of the


removeAll(Collection<?> c) specified collection from the invoking
collection.

5 public int size() It returns the total number of elements in the


collection.

6 public void clear() It removes the total number of elements from the
collection.

7 public boolean contains(Object It is used to search an element.


element)

8 public boolean isEmpty() It checks if collection is empty.

9 public boolean equals(Object It matches two collections.


element)

10 public int hashCode() It returns the hash code number of the collection.

Iterable Interface
 The Iterator interface of the Java collections framework allows us to access elements of a
collection.
 The Iterable interface is the root interface for all the collection classes.
 The Collection interface extends the Iterable interface and therefore all the subclasses of
Collection interface also implement the Iterable interface.
 It contains only one abstract method. i.e.,
Iterator<T> iterator()
It returns the iterator over the elements of type T.
Note: An interface is an abstract "class" that is used to group related methods with "empty" bodies.
To access the interface methods, the interface must be "implemented" (kind like inherited) by
another class with the implements keyword (instead of extends ).
Collection Interface
 The Collection interface is the interface which is implemented by all the classes in the collection
framework.
 It declares the methods that every collection will have.
 In other words, we can say that the Collection interface builds the foundation on which the
collection framework depends.
 Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll (
Collection c), void clear(), etc. which are implemented by all the subclasses of Collection
interface.
1) List Interface
 List interface is the child interface of Collection interface.
 It is a list type data structure in which we can store the ordered collection of objects.
 It can have duplicate values.
 List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use:
List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();
 There are various methods in List interface that can be used to insert, delete, and access the
elements from the list.
The classes that implement the List interface are given below.
a) ArrayList
 Java ArrayList class uses a dynamic array for storing the elements.
 It is like an array, but there is no size limit.
 We can add or remove elements anytime.
 It is much more flexible than the traditional array.
 It is found in the java.util package.
 It is like the Vector in C++.
 The ArrayList in Java can have the duplicate elements also.
 It implements the List interface so we can use all the methods of the List interface here.
 The ArrayList maintains the insertion order internally.
 It inherits the AbstractList class and implements List interface.

The important points about the 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 the array works on an index basis.
o In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a lot of
shifting needs to occur if any element is removed from the array list.
o We can not create an array list of the primitive types, such as int, float, char, etc. It is required to
use the required wrapper class in such cases. For example:

o Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection<? extends It is used to build an array list that is initialized with the
E> c) elements of the collection c.

ArrayList(int capacity) It is used to build an array list that has the specified initial
capacity.

Methods of ArrayList

Method Description

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

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

E get(int index) It is used to fetch the element from the particular


position of the list.

boolean isEmpty() It returns true if the list is empty, otherwise false.

boolean removeAll(Collection<?> It is used to remove all the elements from the list.
c)

Java Non-generic Vs. Generic Collection


Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic. Java new
generic collection allows you to have only one type of object in a collection.
The old non-generic example of creating a Java collection.
ArrayList list=new ArrayList(); //creating old non-generic arraylist
The new generic example of creating java collection.
ArrayList<String> list=new ArrayList<String>();//creating new generic arraylist

Example:
Source Code:
import java.util.*;
class TestJavaCollection1
{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>(); //Creating arraylist
list.add("Ravi"); //Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
Iterator itr=list.iterator(); //Traversing list through Iterator
while(itr.hasNext()){
System.out.println(itr);
}
}
}

Output:
Ravi
Vijay
Ravi
Ajay

b) LinkedList
LinkedList implements the Collection interface. Java LinkedList class uses a doubly linked list to
store the elements. It provides a linked-list data structure. It inherits the AbstractList class and
implements List and Deque interfaces. If you have more number of insertion/ deletion in a list then
prefer LinkedList. LinkedList is also a class which is implemented the method of stack and Deque.
The important points about Java LinkedList are:
o Java LinkedList class can contain duplicate elements.
o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting needs to occur.
o Java LinkedList class can be used as a list, stack or queue.
LinkedList class declaration
The declaration for java.util.LinkedList class.
public class LinkedList<E> extends AbstractSequentialList<E> implements List<
E>, Deque<E>, Cloneable, Serializable
Constructors of Java LinkedList

Constructor Description

LinkedList() It is used to construct an empty list.

LinkedList(Collection<? It is used to construct a list containing the elements of the


extends E> c) specified collection, in the order, they are returned by the
collection's iterator.

Methods of Java LinkedList


Method Description

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

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

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


addAll(Collection<? collection to the end of this list, in the order that they are
extends E> c) returned by the specified collection's iterator.

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


addAll(Collection<? collection to the end of this list, in the order that they are
extends E> c) returned by the specified collection's iterator.

void addFirst(E e) It is used to insert the given element at the beginning of a


list.

void addLast(E e) It is used to append the given element to the end of a list.

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

Example
Source Code:
import java.util.*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

Output:
Ravi
Vijay
Ravi
Ajay

Disadvantage of LinkedList:
1) It takes lot of time to retrieved the elements.

Highlights
1) add( obj )
2) add(index, obj)
3) addAll(collection c)
4) addFirst(obj)
5) addLast(obj)
6) remove(index)
7) removeAll(collection c)
8) removeFirst( )
9) removeLast( )
10) get(index)
11) getLast( )
12) getFirst( )
13) set(index,obj)
c) Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, it is
synchronized and contains many methods that are not the part of Collection framework.

Example
Source Code
import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

Output:
Ayush
Amit
Ashish
Garima

d) Stack
The stack is the subclass of Vector. The stack is a linear data structure that is used to store the
collection of objects. It is based on Last-In-First-Out (LIFO). Java collection framework
provides many interfaces and classes to store the collection of objects. One of them is the Stack
class that provides different operations such as push, pop, search, etc. The push operation inserts
an element into the stack and pop operation removes an element from the top of the stack.
The stack contains all of the methods of Vector class and also provides its methods like
boolean push(), boolean peek(), boolean push(object o), which defines its properties.
The following table shows the different values of the top.

In Java, Stack is a class that falls under the Collection framework that extends the Vector class. It
also implements interfaces List, Collection, Iterable, Cloneable (Cloneable is an interface that is
used to create the exact copy of an object. It exists in java.lang package. A class must implement
the Cloneable interface ), Serializable (mechanism of writing the state of an object into a byte-
stream. ). It represents the LIFO stack of objects. Before using the Stack class, we must import
the java.util package. The stack class arranged in the Collections framework hierarchy, as shown
below.

Stack Class Constructor


The Stack class contains only the default constructor that creates an empty stack.
public Stack()
Creating a Stack
If we want to create a stack, first, import the java.util package and create an object of the Stack
class.
Stack stk = new Stack();
Or
Stack<type> stk = new Stack<>();
Where type denotes the type of stack like Integer, String, etc.
Methods of the Stack Class
We can perform push, pop, peek and search operation on the stack. The Java Stack class provides
mainly five methods to perform these operations.

Method Modifier Method Description


and Type

empty() Boolean The method checks the stack is empty or not.

push(E item) E The method pushes (insert) an element onto the top of the
stack.

pop() E The method removes an element from the top of the stack
and returns the same element as the value of that function.

peek() E The method looks at the top element of the stack without
removing it.

search(Object Int The method searches the specified object and returns the
o) position of the object.

 Stack Class empty() Method


The empty() method of the Stack class check the stack is empty or not. If the stack is empty, it
returns true, else returns false. We can also use the isEmpty() method of the Vector class.
Syntax
public boolean empty()
Returns: The method returns true if the stack is empty, else returns false.
Example: In the following example, we have created an instance of the Stack class. After that,
we have invoked the empty() method two times. The first time it returns true because we have not
pushed any element into the stack. After that, we have pushed elements into the stack. Again we
have invoked the empty() method that returns false because the stack is not empty.
Source Code:
import java.util.Stack;
public class StackEmptyMethodExample
{
public static void main(String[] args)
{
Sack<Integer> stk= new Stack<>(); //creating an instance of Stack class
System.out.println("Is the stack empty? " + stk.empty( ));
stk.push(78); // pushing elements into stack
stk.push(113);
stk.push(90);
stk.push(120);
System.out.println("Elements in Stack: " + stk); //prints elements of the stack
System.out.println("Is the stack empty? " + stk.empty( ));
}
}

Output:
Is the stack empty? True
Elements in Stack: [78,113,90,120]
Is the stack empty? false

 Stack Class push() Method


The method inserts an item onto the top of the stack. It works the same as the
method addElement(item) method of the Vector class. It passes a parameter item to be pushed into
the stack.
Syntax
public E push(E item)
Parameter: An item to be pushed onto the top of the stack.
Returns: The method returns the argument that we have passed as a parameter.

 Stack Class pop() Method


The method removes an object at the top of the stack and returns the same object. It
throws EmptyStackException if the stack is empty.
Syntax
public E pop()
Returns: It returns an object that is at the top of the stack.

Example
Source Code:
package stack_program;
import java.util.*;
public class Stack_Program {
public static void main(String[] args) {
Stack <Integer> stk= new Stack<Integer>(); //creating an instance of Stack class
System.out.println("Is the stack empty? " + stk.empty());
stk.push(78); // pushing elements into stack
stk.push(113);
stk.push(90);
stk.push(120);
System.out.println("Elements in Stack: " + stk); //prints elements of the stack
System.out.println("Is the stack empty? " + stk.empty());
stk.pop();
System.out.println(stk);
stk.addElement(20);
System.out.println(stk);
}
}

Output:
Is the stack empty? true
Elements in Stack: [78, 113, 90, 120]
Is the stack empty? false
[78, 113, 90]
[78, 113, 90, 20]

 Stack Class peek() Method


It looks at the element that is at the top in the stack. It also throws EmptyStackException if the
stack is empty.
Syntax
public E peek()
Returns: It returns the top elements of the stack.

Example
System.out.println(" The Peek element is"+ stk.peek());

Output
20
2) Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is
used to hold the elements which are about to be processed. There are various classes like
PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.

Queue interface can be instantiated as:


Queue<String> q1 = new PriorityQueue();
Queue<String> q2 = new ArrayDeque();
There are 6 methods used to implements queue which is accessible in two classes (PriorityQueue
& LinkedList:
 add( ): If the element is successfully inserted then it will true otherwise it will return Exception.
 Offer( ): If the element is successfully inserted then it will true otherwise it will return false.
 element( ): It will return the head element from the queue. If the queue is empty then it will
return exception.
 peek( ): It will return the head element from the queue. If the queue is empty then it will return
false.
 remove( ): It will return the head element from the queue and also removed it from the queue.
If the queue is empty, then it will return exception.
 poll( ): It will return the head element from the queue and also removed it from the queue. If
the queue is empty, then it will return Null.
There are various classes that implement the Queue interface, some of them are given below.
a) PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or objects which
are to be processed by their priorities. PriorityQueue doesn't allow null values to be stored in the
queue.
b) Deque Interface
Deque interface extends the Queue interface. In Deque, we can remove and add the elements from
both the side. Deque stands for a double-ended queue which enables us to perform the operations
at both the ends. a deque can be used as a stack or a queue. Deque is an acronym for "double ended
queue".

Deque Interface declaration


public interface Deque<E> extends Queue<E>
Methods of Java Deque Interface

Method Description

boolean It is used to insert the specified element into this deque and return true
add(object) upon success.

Object It is used to retrieve and removes the head of this deque.


remove()
Object peek() It is used to retrieve, but does not remove, the head of this deque, or
returns null if this deque is empty.

Object The method returns the head element of the deque. The method does not
peekFirst() remove any element from the deque. Null is returned by this method,
when the deque is empty.

Object The method returns the last element of the deque. The method does not
peekLast() remove any element from the deque. Null is returned by this method,
when the deque is empty.

c) ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue,
we can add or delete the elements from both the ends. As we know that it is not possible to create
an object of an interface in Java. Therefore, for instantiation, we need a class that implements the
Deque interface, and that class is ArrayDeque. It grows and shrinks as per usage. It also inherits
the AbstractCollection class.

The important points about ArrayDeque class are:


o Unlike Queue, we can add or remove elements from both sides.
o Null elements are not allowed in the ArrayDeque.
o ArrayDeque is not thread safe, in the absence of external synchronization.
o ArrayDeque has no capacity restrictions.
o ArrayDeque is faster than LinkedList and Stack.
ArrayDeque class declaration
The declaration for java.util.ArrayDeque class.
public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>, Clo
neable, Serializable

Example
Source Code
package program_queue;
import java.util.*;
public class Program_ArrayDeque {
public static void main(String[] args) {
ArrayDeque ad = new ArrayDeque();
ad.add(20); //add element in the ArrayDeque
ad.add(30);
ad.addLast(50);
ad.addLast(40);
ad.addFirst(10);
System.out.println("The elements in the ArrayDequeue are: " + ad);
System.out.println("The First elements in the ArrayDequeue are: " + ad.getFirst());
System.out.println("The Last elements in the ArrayDequeue are: " + ad.getLast());
System.out.println("The First elements in the ArrayDequeue is: " + ad.peek()); // get head
element
System.out.println("The elements in the ArrayDequeue are: " + ad);
System.out.println("The Last elements in the ArrayDequeue is: " + ad.peekLast());
System.out.println("The First elements in the ArrayDequeue are: " + ad.poll()); //remove
the head
System.out.println("The Last elements in the ArrayDequeue are: " + ad.pollLast());
System.out.println("The First elements in the ArrayDequeue are: " + ad);
}
}

Output
The elements in the ArrayDequeue are: [10, 20, 30, 50, 40]
The First elements in the ArrayDequeue are: 10
The Last elements in the ArrayDequeue are: 40
The First elements in the ArrayDequeue is: 10
The elements in the ArrayDequeue are: [10, 20, 30, 50, 40]
The Last elements in the ArrayDequeue is: 40
The First elements in the ArrayDequeue are: 10
The Last elements in the ArrayDequeue are: 40
The First elements in the ArrayDequeue are: [20, 30, 50]

3) Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface. It represents
the unordered set of elements which doesn't allow us to store the duplicate items. We can store at
most one null value in Set. Set is implemented by HashSet, LinkedHashSet, and TreeSet.
Set can be instantiated as:
Set<data-type> s1 = new HashSet<data-type>();
Set<data-type> s2 = new LinkedHashSet<data-type>();
Set<data-type> s3 = new TreeSet<data-type>();

a) HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table for
storage. Hashing is used to store the elements in the HashSet. It contains unique items.
The important points about Java HashSet class are:
o HashSet stores the elements by using a mechanism called hashing.
o HashSet contains unique elements only.
o HashSet allows null value.
o HashSet class is non synchronized.
o HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their
hashcode.
o HashSet is the best approach for search operations.
o The initial default capacity of HashSet is 16, and the load factor/fill ratio is 0.75.
Difference between List and Set
A list can contain duplicate elements whereas Set contains unique elements only.
HashSet class declaration
Declaration for java.util.HashSet class.
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable

or
HashSet hs =new HashSet( );
Methods of Java HashSet class
Various methods of Java HashSet class are as follows:

SN Modifier & Method Description


Type
1) Boolean add(E e) It is used to add the specified element to this
set if it is not already present.

2) Void clear() It is used to remove all of the elements from


the set.

3) Object clone() It is used to return a shallow copy of this


HashSet instance: the elements themselves are
not cloned.

4) Boolean contains(Object It is used to return true if this set contains the


o) specified element.

5) Boolean isEmpty() It is used to return true if this set contains no


elements.

6) Iterator<E> iterator() It is used to return an iterator over the


elements in this set.

7) Boolean remove(Object It is used to remove the specified element


o) from this set if it is present.

Example
Source Code:
import java.util.*;
public class TestJavaCollection7{
public static void main(String args[]){
HashSet<String> set=new HashSet<String>(); //Creating HashSet and adding elements
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator(); //Traversing elements
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

Output:
Vijay
Ravi
Ajay
Disadvantage of HashSet
1) Sorting and shuffling is not directly possible.

Q4. Connecting to MySQL Using JDBC Driver


Or
Explain the steps followed to access database using JDBC.
Solution:
Steps to connect a Java Application to Database
The following 5 steps are the basic steps involve in connecting a Java application with Database
using JDBC.
1. Register the Driver
2. Create a Connection
3. Create SQL Statement
4. Execute SQL Statement
5. Closing the connection
1. Register the Driver
It is first an essential part to create JDBC connection. JDBC API provides a
method Class.forName() which is used to load the driver class explicitly. For example, if we want
to load a jdbc-odbc driver then the we call it like following.
Example to register with JDBC-ODBC Driver
Class.forName("con.mysql.jdbc.Driver");
2. Create a Connection
After registering and loading the driver in step1, now we will create a connection
using getConnection() method of DriverManager class. This method has several overloaded
methods that can be used based on the requirement. Basically it require the database name,
username and password to establish connection.
Syntax
getConnection(String url)
getConnection(String url, String username, String password)
getConnection(String url, Properties info)
This is a sample example to establish connection with Oracle Driver
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","username","password");
Example:
Source Code:
import java.sql.*;
class Test {
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver"); //Loading driver
//creating connection
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",
"username", "password");
Statement s = con.createStatement(); //creating statement
ResultSet rs = s.executeQuery("select * from Student"); //executing statement
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}
con.close(); //closing connection
} catch (Exception e) {
e.printStacktrace();
}
}
}
3. Create SQL Statement
In this step we will create statement object using createStatement() method. It is used to execute
the sql queries and defined in Connection class. Syntax of the method is given below.
Syntax
public Statement createStatement() throws SQLException
Example to create a SQL statement
Statement s=con.createStatement();
4. Execute SQL Statement
After creating statement, now execute using executeQuery() method of Statement interface. This
method is used to execute SQL statements. Syntax of the method is given below.
Syntax
public ResultSet executeQuery(String query) throws SQLException
Example to execute a SQL statement
In this example, we are executing a sql query to select all the records from the user table and
stored into resultset that further is used to display the records.
ResultSet rs=s.executeQuery("select * from user");
while(rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
5. Closing the connection
This is final step which includes closing all the connection that we opened in our previous steps.
After executing SQL statement you need to close the connection and release the session.
The close() method of Connection interface is used to close the connection.
Syntax
public void close() throws SQLException
Example of closing a connection
con.close();
Example: All Steps into one placeSource Code:
import java.sql.*;
class Test {
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver"); //Loading driver
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",
"username", "password"); //creating connection
Statement s = con.createStatement(); //creating statement
ResultSet rs = s.executeQuery("select * from Student"); //executing statement
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}
}
}
Q.5 Querying Data From MySQL Using JDBC
Ans: To query data from MySQL, you first need to establish a connection to MySQL using
Connection object.

Connection conn = DriverManager.getConnection(url,username,password);

Code language: Java (java)


We developed a utility class named MySQLJDBCUtil that open a new connection with database
parameters stored in a properties file.

Connection conn = MySQLJDBCUtil.getConnection();


After opening the connection, you need to create a Statement object. JDBC provides several kinds
of statements such as Statement, PreparedStatement and CallableStatement. For querying data,
you just need to use the Statement object as follows:
Statement stmt = conn.createStatement();
Once you have a Statement object created, you can use it to execute any valid MySQL query like
the following:
String sql = "SELECT first_name, last_name, email " + "FROM candidates";
ResultSet rs = stmt.executeQuery(sql)

Code language: SQL (Structured Query Language) (sql)


We have called the executeQuery() method of the Statement object. This method returns a
ResultSet object that contains result of the SQL query. The result is in the form of rows with
columns of data based on the SELECT statement.
The ResultSet object provides you with methods to traverse the result and read the data.
The next() method returns true and move to the next row in the ResultSet if there are rows
available, otherwise it returns false. You must call the next() method at least one before reading
data because before the first next() call, the ResultSet is located before the first row.
To get column data of the current row, you use getDataType() method where DataType is the data
type of the column e.g., int, string, double, etc., You need to pass the column name or column
index to the getDataType() method, for example:
String s = rs.getString("column_name");
int id = rs.getInt(1);

To get the data out of the candidates ResultSet, you do it as follows:


while (rs.next()) {
System.out.println(rs.getString("first_name") + "\t" +
rs.getString("last_name") + "\t" +
rs.getString("email"));
}
You should always close the ResultSet and Statement objects when you complete traversing the
data by calling close() method.
try{
rs.close();
stmt.close();
} catch(SQLException e) {
System.out.println(e.getMessage());
}
If you use the try-with-resource statement, the close() method is automatically called so you don’t
have to explicitly do it. The following is the complete example of querying data from
the candidates table in our sample database.

Example
package org.mysqltutorial;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Main {
public static void main(String[] args) {
String sql = "SELECT first_name, last_name, email " +"FROM candidates";
try (Connection conn = MySQLJDBCUtil.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {

// loop through the result set


while (rs.next()) {
System.out.println(rs.getString("first_name") + "\t" + rs.getString("last_name") + "\t" +
rs.getString("email"));
}
}
catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}

Q6. Java ResultSetMetaData Interface


Ans: The metadata means data about data i.e. we can get further information from the data.
If you have to get metadata of a table like total number of column, column name, column type etc.,
ResultSetMetaData interface is useful because it provides methods to get metadata from the
ResultSet object.
Commonly used methods of ResultSetMetaData interface

Method Description

public int getColumnCount()throws it returns the total number of columns


SQLException in the ResultSet object.

public String getColumnName(int index)throws it returns the column name of the


SQLException specified column index.
public String getColumnTypeName(int it returns the column type name for the
index)throws SQLException specified index.

public String getTableName(int index)throws it returns the table name for the
SQLException specified column index.

How to get the object of ResultSetMetaData:

The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData.


Syntax:
public ResultSetMetaData getMetaData()throws SQLException

Example of ResultSetMetaData interface :


import java.sql.*;
class Rsmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system"
,"oracle");
PreparedStatement ps=con.prepareStatement("select * from emp");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("Total columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Output:
Total columns: 2
Column Name of 1st column: ID
Column Type Name of 1st column: NUMBER

Note:
 Difference between ResultSet Object & ResultSet Meta Data
(Combine Answer 4 and 5)

You might also like