JAVA Library
JAVA Library
already. You download those classes and tell your computer about them, and then you can use those
classes in your code.
For Java developers looking out for Java libraries to learn and grow, we are listing down the top 10 libraries
every Java developer should know.
Java Standard Libraries
It is always best, to begin with, the frameworks and libraries provided by the programming language itself.
This is also true for development tools. The Java standard libraries provided by Java are often overlooked but
have some of the most robust and functional libraries. To name a few:
Java.util
Java.lang
Java.math
Java.net
Java.io /Java.nio
Java standard library helps students and new Java developers to build a strong base which further helps them
to solidify their concepts and learn different third-party libraries efficiently.
Java String
String is an object that represents sequence of characters. In Java, String is represented by String class which
is located into java.lang package
It is probably the most commonly used class in java library. In java, every string that we create is actually an
object of type String. One important thing to notice about string object is that string objects are immutable that
means once a string object is created it cannot be changed.
The Java String class implements Serializable, Comparable and CharSequence interface that we have
represented using the below image.
In Java, CharSequence Interface is used for representing a sequence of characters. CharSequence interface is
implemented by String, StringBuffer and StringBuilder classes. This three classes can be used for creating
strings in java.
What is String in Java?
Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence
of characters. The java.lang.String class is used to create a string object.
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string
already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in
the pool, a new string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string object
with the value "Welcome" in string constant pool that is why it will create a new object. After that it
will find the string with the value "Welcome" in the pool, it will not create a new object but will return
the reference to the same instance.
Note: String objects are stored in a special memory area known as the "string constant pool".
Why Java uses the concept of String literal?
To make Java more memory efficient (because no new objects are created if it exists already in the
string constant pool).
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap
(non-pool).
Output:
java
strings
example
Java String class methods
The java.lang.String class provides many useful methods to perform operations on sequence of char
values.
4 static String format(Locale l, String format, Object... It returns formatted string with given
args) locale.
6 String substring(int beginIndex, int endIndex) It returns substring for given begin
index and end index.
17 String[] split(String regex, int limit) It returns a split string matching regex
and limit.
20 int indexOf(int ch, int fromIndex) It returns the specified char value index
starting with given index.
22 int indexOf(String substring, int fromIndex) It returns the specified substring index
starting with given index.
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.
public append(String s) It is used to append the specified string with this string.
synchronized The append() method is overloaded like append(char),
StringBuffer append(boolean), append(int), append(float),
append(double) etc.
public insert(int offset, String s) It is used to insert the specified string with this string at
synchronized the specified position. The insert() method is
StringBuffer overloaded like insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int, double) etc.
public replace(int startIndex, It is used to replace the string from specified startIndex
synchronized int endIndex, String str) and endIndex.
StringBuffer
public delete(int startIndex, int It is used to delete the string from specified startIndex
synchronized endIndex) and endIndex.
StringBuffer
public reverse() is used to reverse the string.
synchronized
StringBuffer
public void ensureCapacity(int It is used to ensure the capacity at least equal to the
minimumCapacity) given minimum.
public char charAt(int index) It is used to return the character at the specified position.
public int length() It is used to return the length of the string i.e. total
number of characters.
public String substring(int It is used to return the substring from the specified
beginIndex) beginIndex.
public String substring(int It is used to return the substring from the specified
beginIndex, int beginIndex and endIndex.
endIndex)
StringBufferExample5.java
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Output:
olleH
6) StringBuffer capacity() Method
The capacity() method of the StringBuffer class returns the current capacity of the buffer. The default
capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
StringBufferExample6.java
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Output:
16
16
34
In Java, Regular Expressions or Regex (in short) in Java is an API for defining String patterns that
can be used for searching, manipulating, and editing a string in Java. Email validation and
passwords are a few areas of strings where Regex is widely used to define the constraints. Regular
Expressions in Java are provided under java.util.regex package. This consists of 3 classes and 1
interface. The java.util.regex package primarily consists of the following three classes as depicted
below in tabular format as follows:
Regex Classes and Interfaces
Regex in Java provides 3 classes and 1 interface which are as follows:
1. Pattern Class
2. Matcher Class
3. PatternSyntaxException Class
4. MatchResult Interface
More understanding can be interpreted from the image provided below as follows:
S.
No. Class/Interface Description
S.
No. Method Description
}
}
Output
false
Example 1:
import java.util.regex.*;
class USCS {
public static void main(String[] args)
{
Pattern pattern = Pattern.compile("UIT");
Matcher matcher = pattern.matcher("UIT");
boolean letsCheck = matcher.matches();
System.out.println(
" Let us check whether the pattern matches or not:");
if (letsCheck)
System.out.println("Pattern Matched");
else
System.out.println("Pattern does not match");
}
}
Output
Let us check whether the pattern matches or not:
Pattern Matched
Example 2:
import java.util.regex.*;
class UU {
public static void main(String[] args)
{
Pattern pattern = Pattern.compile("USCS");
Matcher matcher = pattern.matcher("USCS is the department of Uttaranchal University");
System.out.println("Checking for USCS in Sentence : ");
if (matcher.find())
System.out.println("USCS found");
else
System.out.println("USCS not found");
}
}
Output
Checking for USCS in Sentence :
USCS found
Matcher class
In Java, Matcher is a class that is implemented by the MatchResult interface, that performs match
operations on a character sequence by interpreting a Pattern.
Below, we can see the declaration of java.util.regex.Matcher in java.lang.Object Class:
public final class Matcher extends Object implements MatchResult
By invoking the pattern’s matcher method, a matcher is created from a pattern. If a matcher is
created once, we can perform three different kinds of match operations on it:
matches(): Try to match the total input sequence against the pattern.
lookingAt(): Try to match the input sequence, against the pattern, starting at the
beginning.
find(): This scans the input sequence and looks for the next subsequence especially
matches the pattern.
Below the methods of the Matcher class are grouped in the table for convenience according to
their functionality.
1. Index Methods:
It provides useful index values. It shows precisely whether the match was found in the input string
or not:
S.
No. Method Name Description
1 public int start() This method returns the start index of the previous match.
public int This method returns the start index of the subsequence captured by the
2
start(int group) given group during the previous match operation.
3 public int end() This method returns the offset after the last character is matched.
public int This method returns the offset after the last character of the subsequence
4
end(int group) captured by the given group during the previous match operation.
2. Study Methods:
It reviews the input string and returns a boolean indicating whether the pattern is found or not:
S.
No. Method Name Description
public boolean This method aims to match the input sequence, starting at the
1
lookingAt() beginning of the region, against the pattern.
public boolean This method aims to find the next subsequence of the input sequence
2
find() that matches the pattern.
Resets this matcher and then tries to find the next subsequence of the
public boolean
3 input sequence which matches the pattern, starting at the specified
find(int start)
index.
public boolean
4 This method aims to match the entire region against the pattern.
matches()
3. Replacement Methods:
S.
No. Method Name Description
public Matcher
This method implements a non-terminal append-
1 appendReplacement(StringBuffer sb,
and-replace step.
String replacement)
Example 1: Here we can see the example GFG.java which count the number of times the word “geek”
appears in the input string using start() and end() :
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Example 2: In this example, we can see GFG.java, the lookingAt() and matches() both attempt to match an
input sequence against a pattern.
// Java program to demonstrate the
// methods of Matcher class in Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
[xyz] x,y or z
Regex Metacharacters
class RegExp
{
public static void main(String args[])
{
//Patern Class
String text="Uttaranchal University";
System.out.println(Pattern.matches("Uttaranchal@University", text));
System.out.println(Pattern.matches("[a-zA-Z]","O"));
System.out.println(Pattern.matches("[a-z && p-y]","o"));
System.out.println(Pattern.matches("[a-z && [^bc]]","c"));
System.out.println(Pattern.matches("[a-z && [^m-p]]","n"));
System.out.println(Pattern.matches("[Uttaranchal]++", "UttaranchalUttaranchal"));
System.out.println(Pattern.matches("[aa]{4,6}", "aaaaaa"));
// Matcher Class
Pattern pattern=Pattern.compile("Uttaran");
Matcher m = pattern.matcher("Uttaranchal University in Uttarankhand");
while(m.find())
{
System.out.println("Pattern start and end from : "+ m.start() + "to" + (m.end()-1));
}
}
}
Output
There are subtle differences among greedy, reluctant, and possessive quantifiers.
Greedy quantifiers are considered "greedy" because they force the matcher to read in, or eat, the entire input string prior to
attempting the first match. If the first match attempt (the entire input string) fails, the matcher backs off the input string by one
character and tries again, repeating the process until a match is found or there are no more characters left to back off from.
Depending on the quantifier used in the expression, the last thing it will try matching against is 1 or 0 characters.
The reluctant quantifiers, however, take the opposite approach: They start at the beginning of the input string, then reluctantly
eat one character at a time looking for a match. The last thing they try is the entire input string.
Finally, the possessive quantifiers always eat the entire input string, trying once (and only once) for a match. Unlike the
greedy quantifiers, possessive quantifiers never back off, even if doing so would allow the overall match to succeed.
The first example uses the greedy quantifier .* to find "anything", zero or more times, followed by the letters "f" "o" "o".
Because the quantifier is greedy, the .* portion of the expression first eats the entire input string. At this point, the overall
expression cannot succeed, because the last three letters ("f" "o" "o") have already been consumed. So the matcher slowly
backs off one letter at a time until the rightmost occurrence of "foo" has been regurgitated, at which point the match succeeds
and the search ends.
The second example, however, is reluctant, so it starts by first consuming "nothing". Because "foo" doesn't appear at the
beginning of the string, it's forced to swallow the first letter (an "x"), which triggers the first match at 0 and 4. Our test harness
continues the process until the input string is exhausted. It finds another match at 4 and 13.
The third example fails to find a match because the quantifier is possessive. In this case, the entire input string is consumed
by .*+, leaving nothing left over to satisfy the "foo" at the end of the expression. Use a possessive quantifier for situations
where you want to seize all of something without ever backing off; it will outperform the equivalent greedy quantifier in cases
where the match is not immediately found.
Regex Description
. Any character
\b Word boundary
// Driver Class
class GFG {
// Main Function
public static void main(String[] args)
{
// Check if all elements are numbers
System.out.println(Pattern.matches("\\d+", "1234"));
S.
No. Method Name Modifier Description
It provides programmatic
StackTraceElement access to the stack trace
3. getStackTrace()
[] information printed
by printStackTrace() method.
S.
No. Method Name Modifier Description
S.
No. Method Name Modifier Description
protected
6. clone() It creates and returns a copy of this object.
Object
Example 1: Create a class “Demo1” to replace all non-alphanumeric characters with space
in the given message using Regular expression.
Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
try {
// Get Pattern class object to compile the
// regular expression.
Pattern pattern = Pattern.compile(REGEX);
Output
PatternSyntaxException:
Description: Dangling meta character '?'
Index: 0
Message: Dangling meta character '?' near index 0
?[^a-zA-Z0-9]
^
Pattern: ?[^a-zA-Z0-9]
In this example, we are trying to replace all the non-alphanumeric characters
with a space.
But in regex, there is ‘?‘ which is causing the error. Whenever we are working
with meta characters like ‘+‘,’*‘,’?‘, we need to be more careful and should use
escape characters.
As it is causing the error, we can see the Exception details with the index and
the regex pattern in the output.
Example 2: Create a class “Demo2” to find the matching pattern in the given message.
Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
Output
PatternSyntaxException:
Pattern: [Geek
Description: Unclosed character class
Message: Unclosed character class near index 4
[Geek
^
Index: 4
Note:
This is a common mistake in which the programmer has forgotten the closing
parenthesis in the regular expression.
So, the output is showing the complete details with the error message and the
index of it.
MatchResult Interface in Java
Interface in java is used to achieve abstraction. It is also considered as the blueprint for the class. An interface
can contain abstract methods only but it might or might not contain variables. In other words, an interface can
contain abstract methods and variables only. Java supports multiple inheritance through interfaces only. Thus,
an interface has a wider scope in Java.
MatchResult Interface:
The MatchResult interface in java signifies the result or conclusion of a match operation. It contains
the definition of certain query methods that can be used to determine the result of the match with a
regular expression. Note that we cannot alter the group/group boundaries and match boundaries using
the MatchResult interface but one can see them easily through the interface. This interface was
introduced in Java version 1.5.
1. start() method: This method is used to return the start index of the match.
Syntax:
int start()
Return Value:
integer: Represents the index of the first character that has a match
Example:
import java.io.*;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class GFG {
// Main method
public static void main(String[] args)
{
// Compiling the given regular expression string
Pattern myPattern
= Pattern.compile(regularExpression);
if (myMatcher.find()) {
Output
Start index of the match: 0
Example:
// Main method
public static void main(String[] args)
{
// Compiling the regular expression string
Pattern myPattern
= Pattern.compile(regularExpression);
// previous match.
System.out.println("First Capturing Group"
+ myResult.group());
// Prints the offset after the last
System.out.println(
"Starting index of the match: "
+ myResult.start());
}
}
}
Output
First Capturing Group: 43
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages. Package in java
can be categorized in two form, built-in package and user-defined package. There are many built-in
packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Here, we will have the detailed
learning of creating and using user-defined packages.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
1. package mypack;
2. public class Simple{
3. public static void main(String args[]){
4. System.out.println("Welcome to package");
5. }
6. }
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
For example
javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep
the package within the same directory, you can use . (dot).
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The
.represents the current folder.
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current
package.
Example of package that import the packagename.*
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now there
is no need to import. But you need to use fully qualified name every time when you are accessing the
class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date
class.
Example of package by import fully qualified name
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}
Output:Hello
If you import a package, all the classes and interface of that package will be imported excluding the
classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.
If you import a package, all the classes and interface of that package will be imported excluding the
classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.
Note: Sequence of the program must be package then import then class.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the package
further.
Let's take an example, Sun Microsystem has definded a package named java that contains many
classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group e.g.
Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes are for
networking etc and so on. So, Sun has subcategorized the java package into subpackages such as lang,
net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket classes in
net packages and so on.
Example of Subpackage
package uttaranchal.uscs.mca;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java
Before exploring various input and output streams lets look at 3 standard or default streams that Java
has to provide which are also most common in use:
Stream
A stream can be described as a data sequence. There are two types of streams available:
InPutStream: The InputStream is used from a source to read data.
OutPutStream: To write data to a destination, the OutputStream is used in Java.
Java offers powerful but flexible file and network I/O support, but this tutorial includes very
fundamental stream and I/O functionality. We'll see one by one the most frequently used instances.
Byte Streams
Java byte streams are used to execute 8-bit bytes input and output. Although there are many classes
linked to byte streams, FileInputStream and FileOutputStream are the most commonly used classes.
Following is an instance to copy an input file into an output file using these two classes.
Example:
import java.io.*;
public class FileCopyExample {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("inputFile.txt");
out = new FileOutputStream("outputFile.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Character Streams
Java Byte streams are used to execute 8-bit bytes input and output while Java Character streams are
used to execute 16-bit Unicode input and output. Although there are many classes associated with
character streams, FileReader and FileWriter are the most commonly used classes. While FileReader
utilizes FileInputStream internally and FileWriter uses FileOutputStream, the main distinction here
is that FileReader reads two bytes at one moment and FileWriter writes two bytes at one moment.
The above instance can be re-written, which makes use of these two classes to copy an input file (with
Unicode characters) into an output file.
import java.io.*;
public class FileCopyExample {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("inputFile.txt");
out = new FileWriter("outputFile.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Standard Streams
All programming languages support standard I/O, where the program of the user can take input from
a keyboard and then generate an output on the screen of the computer. If you are aware of C or C++
programming languages, you must be aware of three standard devices STDIN, STDOUT and
STDERR. Similarly, the following three normal streams are provided by Java.
Standard Input − This is used to feed the data to user's program and usually a keyboard is
used as standard input stream and represented as System.in.
Standard Output − This is used to output the data produced by the user's program and usually
a computer screen is used for standard output stream and represented as System.out.
Standard Error − This is used to output the error data produced by the user's program and
usually a computer screen is used for standard error stream and represented
as System.err.
Example:
import java.io.*;
public class MyFirstReadExample {
public static void main(String args[]) throws IOException {
InputStreamReader cin = null;
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'p' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'p');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
FileInputStream
This stream is used to read file information. The new keyword can be used to create objects and several kinds of
constructors are accessible. A file name is used as a string to produce an input stream object to read the file after
the constructor.
Once you have an InputStream object in hand, a list of helpful methods can be used to read to stream or perform
other activities on the stream.
This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned
end of the file. It throws an IOException.
This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no mo
references to this stream. It throws an IOException.
The file output stream is closed by this method. Releases any file-related system resources. Throws an exception related to the IOE.
Gives the number of bytes that can be read from this file input stream. Returns an int. It throws an IOException.
This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If it is the end of the file, -
returned. It throws an IOException.
FileOutputStream
To generate a file and enter information into it, FileOutputStream is used. If it does not already exist, the flow
would generate a file before opening it for output.
Here are two constructors that can be used to generate an object from FileOutputStream.
To generate an input flow object to write the file, the following constructor requires a file name as a string:
A file object is used to generate an output stream object to write the file after the constructor. First, we use the
File() method to generate a file object as follows:
Once you've got OutputStream object in hand, there's a list of helpful methods that can be used to write to stream
or do other stream activities.
This method cleans up the connection to the file. Ensures that the close method of this file output stream is called
when there are no more references to this stream. It throws an IOException.
Method & Description
This method closes the file output stream. Releases any system resources associated with the file. It throws an
IOException.
Writes w.length bytes from the mentioned byte array to the OutputStream.
This method writes the specified byte to the output stream. It throws an IOException.
Example
Below is the program to demonstrate InputStream and OutputStream in java:
import java.io.*;
public class MyFileStreamProgram {
public static void main(String args[]) {
try {
byte bWrite [] = {121,201,31,140,25};
OutputStream os = new FileOutputStream("mytest.txt");
for(int x = 0; x < bWrite.length ; x++) {
os.write( bWrite[x] );
}
os.close();
InputStream is = new FileInputStream("mytest.txt");
int size = is.available();
for(int i = 0; i < size; i++) {
System.out.print((char)is.read() + " ");
}
is.close();
} catch (IOException e) {
System.out.print("Exception");
}
}
}
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).
The Collection framework represents a unified architecture for storing and manipulating a group of
objects. It has:
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.
List Interface
List interface is the child interface of Collection interface. It inhibits 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.
There are various methods in List interface that can be used to insert, delete, and access the elements
from the list.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate
element of different data types. The ArrayList class maintains the insertion order and is non-
synchronized. The elements stored in the ArrayList class can be randomly accessed. Consider the
following example.
1. import java.util.*;
2. class TestJavaCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }
Output:
Ravi
Vijay
Ravi
Ajay
LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to store the
elements. It can store the duplicate elements. It maintains the insertion order and is not synchronized.
In LinkedList, the manipulation is fast because no shifting is required.
1. import java.util.*;
2. public class TestJavaCollection2{
3. public static void main(String args[]){
4. LinkedList<String> al=new LinkedList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. Iterator<String> itr=al.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
15. Output:
16. Ravi
17. Vijay
18. Ravi
19. Ajay
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.
1. import java.util.*;
2. public class TestJavaCollection3{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();
5. v.add("Ayush");
6. v.add("Amit");
7. v.add("Ashish");
8. v.add("Garima");
9. Iterator<String> itr=v.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ayush
Amit
Ashish
Garima
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., 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.
1. import java.util.*;
2. public class TestJavaCollection4{
3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
7. stack.push("Amit");
8. stack.push("Ashish");
9. stack.push("Garima");
10. stack.pop();
11. Iterator<String> itr=stack.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Ayush
Garvit
Amit
Ashish
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.
There are various classes that implement the Queue interface, some of them are given below.
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.
1. import java.util.*;
2. public class TestJavaCollection5{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue<String>();
5. queue.add("Amit Sharma");
6. queue.add("Vijay Raj");
7. queue.add("JaiShankar");
8. queue.add("Raj");
9. System.out.println("head:"+queue.element());
10. System.out.println("head:"+queue.peek());
11. System.out.println("iterating the queue elements:");
12. Iterator itr=queue.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. queue.remove();
17. queue.poll();
18. System.out.println("after removing two elements:");
19. Iterator<String> itr2=queue.iterator();
20. while(itr2.hasNext()){
21. System.out.println(itr2.next());
22. }
23. }
24. }
Output:
head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj
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.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
1. import java.util.*;
2. public class TestJavaCollection6{
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String>();
6. deque.add("Gautam");
7. deque.add("Karan");
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
14. }
Output:
Gautam
Karan
Ajay
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.
1. import java.util.*;
2. public class TestJavaCollection7{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Vijay
Ravi
Ajay
LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the
HashSet class and implements Set interface. Like HashSet, It also contains unique elements. It
maintains the insertion order and permits null elements.
1. import java.util.*;
2. public class TestJavaCollection8{
3. public static void main(String args[]){
4. LinkedHashSet<String> set=new LinkedHashSet<String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Ravi");
8. set.add("Ajay");
9. Iterator<String> itr=set.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ravi
Vijay
Ajay
SortedSet Interface
SortedSet is the alternate of Set interface that provides a total ordering on its elements. The elements
of the SortedSet are arranged in the increasing (ascending) order. The SortedSet provides the
additional methods that inhibit the natural ordering of the elements.
1. import java.util.*;
2. public class TestJavaCollection9{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> set=new TreeSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Ajay
Ravi
Vijay
References:
1. https://www.geeksforgeeks.org/top-10-libraries-every-java-developer-should-know/
2. https://www.studytonight.com/java/string-handling-in-java.php
3. https://www.javatpoint.com/java-string
4. https://www.javatpoint.com/StringBuffer-
class#:~:text=Java%20StringBuffer%20class%20is%20used,i.e.%20it%20can%20be%20changed.
5. https://www.geeksforgeeks.org/regular-expressions-in-java/
6. https://www.geeksforgeeks.org/matchresult-interface-in-java/
7. https://www.geeksforgeeks.org/patternsyntaxexception-class-in-java/
8. https://www.geeksforgeeks.org/matcher-class-in-java/
9. https://www.geeksforgeeks.org/matcher-class-in-java/
10. https://www.geeksforgeeks.org/pattern-class-in-java/
11. https://www.geeksforgeeks.org/java-io-input-output-in-java-with-examples/
12. https://www.knowledgehut.com/tutorials/java-tutorial/files-and-java-i-o
13. https://www.javatpoint.com/collections-in-java