Solved Question Paper
Solved Question Paper
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
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.
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.
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.
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.
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.
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.
import java.awt.*;
public class AwtApp extends Frame {
AwtApp(){
Label firstName = new Label("First Name");
firstName.setBounds(20, 50, 80, 20);
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
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
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
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.
An output stream that contain method for writing java standard data
DataOutputStream
type
These classes define several key methods. Two most important are
1. read() : reads byte of data.
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.
or,
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.
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
Output
6 public void clear() It removes the total number of elements from the
collection.
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.
o Constructor Description
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.
boolean removeAll(Collection<?> It is used to remove all the elements from the list.
c)
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
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.
void addLast(E e) It is used to append the given element to the end of 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.
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.
Output:
Is the stack empty? True
Elements in Stack: [78,113,90,120]
Is the stack empty? false
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]
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.
Method Description
boolean It is used to insert the specified element into this deque and return true
add(object) upon success.
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.
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:
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.
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)) {
Method Description
public String getTableName(int index)throws it returns the table name for the
SQLException specified column index.
Note:
Difference between ResultSet Object & ResultSet Meta Data
(Combine Answer 4 and 5)