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

JAVA Library

1. A Java library is a collection of pre-written classes that can be included in a Java application to provide additional functionality without having to be written from scratch. Common Java libraries include those for input/output, networking, math, and more. 2. The top 10 Java libraries that every developer should know include the Java standard libraries like Java.util, Java.lang, and Java.io, as well as String, StringBuffer, and common third-party libraries. 3. The String class represents character strings and is one of the most commonly used classes in Java. It is immutable, but StringBuffer can be used to create mutable strings. Both support many useful methods for string manipulation and operations

Uploaded by

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

JAVA Library

1. A Java library is a collection of pre-written classes that can be included in a Java application to provide additional functionality without having to be written from scratch. Common Java libraries include those for input/output, networking, math, and more. 2. The top 10 Java libraries that every developer should know include the Java standard libraries like Java.util, Java.lang, and Java.io, as well as String, StringBuffer, and common third-party libraries. 3. The String class represents character strings and is one of the most commonly used classes in Java. It is immutable, but StringBuffer can be used to create mutable strings. Both support many useful methods for string manipulation and operations

Uploaded by

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

Java Library: A Java library is just a collection of classes that have been written by somebody else

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.

How to create a string object?


There are two ways to create 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).

Java String Example


StringExample.java

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}

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.

No. Method Description

1 char charAt(int index) It returns char value for the particular


index

2 int length() It returns string length

3 static String format(String format, Object... args) It returns a formatted string.

4 static String format(Locale l, String format, Object... It returns formatted string with given
args) locale.

5 String substring(int beginIndex) It returns substring for given begin


index.

6 String substring(int beginIndex, int endIndex) It returns substring for given begin
index and end index.

7 boolean contains(CharSequence s) It returns true or false after matching the


sequence of char value.

8 static String join(CharSequence delimiter, It returns a joined string.


CharSequence... elements)

9 static String join(CharSequence delimiter, Iterable<? It returns a joined string.


extends CharSequence> elements)

10 boolean equals(Object another) It checks the equality of string with the


given object.

11 boolean isEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the specified string.

13 String replace(char old, char new) It replaces all occurrences of the


specified char value.
14 String replace(CharSequence old, CharSequence new) It replaces all occurrences of the
specified CharSequence.

15 static String equalsIgnoreCase(String another) It compares another string. It doesn't


check case.

16 String[] split(String regex) It returns a split string matching regex.

17 String[] split(String regex, int limit) It returns a split string matching regex
and limit.

18 String intern() It returns an interned string.

19 int indexOf(int ch) It returns the specified char value index.

20 int indexOf(int ch, int fromIndex) It returns the specified char value index
starting with given index.

21 int indexOf(String substring) It returns the specified substring index.

22 int indexOf(String substring, int fromIndex) It returns the specified substring index
starting with given index.

23 String toLowerCase() It returns a string in lowercase.

24 String toLowerCase(Locale l) It returns a string in lowercase using


specified locale.

25 String toUpperCase() It returns a string in uppercase.

26 String toUpperCase(Locale l) It returns a string in uppercase using


specified locale.

27 String trim() It removes beginning and ending spaces


of this string.

28 static String valueOf(int value) It converts given type into string. It is an


overloaded method.
StringBuffer
StringBuffer class is used to create a mutable string object. It means, it can be changed after it is created. It
represents growable and writable character sequence.
It is similar to String class in Java both are used to create string, but stringbuffer object can be changed.

Important Constructors of StringBuffer Class


Constructor Description

StringBuffer() It creates an empty String buffer with the initial capacity of 16.

StringBuffer(String str) It creates a String buffer with the specified string..

StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.

Important methods of StringBuffer class

Modifier Method Description


and Type

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 int capacity() It is used to return the current capacity.

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)

What is a mutable String?


A String that can be modified or changed is known as mutable String. StringBuffer and StringBuilder classes
are used for creating mutable strings.

1) StringBuffer Class append() Method


The append() method concatenates the given argument with this String.
StringBufferExample.java
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
Output:
Hello Java
2) StringBuffer insert() Method
The insert() method inserts the given String with this string at the given position.
StringBufferExample2.java
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Output:
HJavaello
3) StringBuffer replace() Method
The replace() method replaces the given String from the specified beginIndex and endIndex.
StringBufferExample3.java
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
Output:
HJavalo
4) StringBuffer delete() Method
The delete() method of the StringBuffer class deletes the String from the specified beginIndex to endIndex.
StringBufferExample4.java
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Output:
Hlo
5) StringBuffer reverse() Method
The reverse() method of the StringBuilder class reverses the current String.

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

7) StringBuffer ensureCapacity() method


The ensureCapacity() method of the StringBuffer class ensures that the given capacity is the minimum to the
current capacity. If it is greater than the 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.
StringBufferExample7.java
class StringBufferExample7{
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
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
Output:
16
16
34
34
70
Regular Expressions

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

1. Pattern Class Used for defining patterns

Used for performing match operations on text using


2. Matcher Class
patterns

PatternSyntaxException Used for indicating syntax error in a regular


3.
Class expression pattern

4. MatchResult Interface Used for representing the result of a match operation


Pattern Class
This class is a compilation of regular expressions that can be used to define various types of patterns, providing
no public constructors. This can be created by invoking the compile() method which accepts a regular
expression as the first argument, thus returning a pattern after execution.

S.
No. Method Description

It is used to compile the given regular expression


1. compile(String regex)
into a pattern.

compile(String regex, int It is used to compile the given regular expression


2.
flags) into a pattern with the given flags.

3. flags() It is used to return this pattern’s match flags.

matcher(CharSequence It is used to create a matcher that will match the


4.
input) given input against this pattern.

matches(String regex, It is used to compile the given regular expression


5.
CharSequence input) and attempts to match the given input against it.

It is used to return the regular expression from


6. pattern()
which this pattern was compiled.

It is used to return a literal pattern String for the


7. quote(String s)
specified String.

It is used to split the given input sequence around


8. split(CharSequence input)
matches of this pattern.

It is used to split the given input sequence around


split(CharSequence input,
9. matches of this pattern. The limit parameter
int limit)
controls the number of times the pattern is applied.

It is used to return the string representation of this


10. toString()
pattern.
import java.util.regex.Pattern;
class RegExp
{
public static void main(String args[])
{
String text="Uttaranchal University";
System.out.println(Pattern.matches("Uttaranchal@University", text));

}
}
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.

Methods of Matcher class:

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:

These are useful methods for replacing text in an input string:

S.
No. Method Name Description

public Matcher
This method implements a non-terminal append-
1 appendReplacement(StringBuffer sb,
and-replace step.
String replacement)

public StringBuffer This method implements a terminal append-and-


2
appendTail(StringBuffer sb) replace step.

This method replaces every subsequence of the


public String replaceAll(String
3 input sequence that matches the pattern with the
replacement)
given replacement string.

This method replaces the first subsequence of the


public String replaceFirst(String
4 input sequence that matches the pattern with the
replacement)
given replacement string.
S.
No. Method Name Description

This method returns a literal replacement String


for the specified String, this method also
public static String
5 produces a String which will work in the
quoteReplacement(String s)
appendReplacement method as a literal
replacement of the Matcher class.

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;

public class GFG {

private static final String REGEX = "\\bgeek\\b";


private static final String INPUT = "geek geek geek geekie geeks";
public static void main(String[] args)
{
Pattern pat = Pattern.compile(REGEX);
Matcher mat = pat.matcher(INPUT);
int count = 0;
while (mat.find()) {
count++;
System.out.println("Match number " + count);
System.out.println("start(): " + mat.start());
System.out.println("end(): " + mat.end());
}
}
}
Output
Match number 1
start(): 0
end(): 4
Match number 2
start(): 5
end(): 9
Match number 3
start(): 10
end(): 14

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;

public class GFG {

private static final String REGEX = "geek";


private static final String INPUT = "geeksforgeeks";
private static Pattern pat;
private static Matcher mat;

public static void main(String[] args)


{

// Initialization for pattern and matcher


pat = Pattern.compile(REGEX);
mat = pat.matcher(INPUT);

System.out.println("Current REGEX: " + REGEX);


System.out.println("Current INPUT: " + INPUT);

System.out.println("lookingAt(): " + mat.lookingAt());


System.out.println("matches(): " + mat.matches());
}
}
Output
Current REGEX: geek
Current INPUT: geeksforgeeks
lookingAt(): true
matches(): false
Regex Character classes
Character Class Description

[xyz] x,y or z

[^xyz] Any characters other than x,y or z

[a-zA-Z] characters from range a to z or A to Z.

[a-f[m-t]] Union of a to f and m to t.

All the range of elements intersection


[a-z && p-y] between two ranges

[a-z && [^bc]] a to b union with except b and c

[a-z && [^m-p]] a to z union with except range m to p

Regex Metacharacters

Greedy Reluctant Possessive Meaning


X? X?? X?+ X, once or not at all
X* X*? X*+ X, zero or more times
X+ X+? X++ X, one or more times
X{n} X{n}? X{n}+ X, exactly n times
X{n,} X{n,}? X{n,}+ X, at least n times
X{n,m} X{n,m}? X{n,m}+ X, at least n but not more than m times
import java.util.regex.Pattern;
import java.util.regex.Matcher;

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

Differences Among Greedy, Reluctant, and Possessive Quantifiers

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.

To illustrate, consider the input string xfooxxxxxxfoo.


Enter your regex: .*foo // greedy quantifier
Enter input string to search: xfooxxxxxxfoo
I found the text "xfooxxxxxxfoo" starting at index 0 and ending at index 13.

Enter your regex: .*?foo // reluctant quantifier


Enter input string to search: xfooxxxxxxfoo
I found the text "xfoo" starting at index 0 and ending at index 4.
I found the text "xxxxxxfoo" starting at index 4 and ending at index 13.

Enter your regex: .*+foo // possessive quantifier


Enter input string to search: xfooxxxxxxfoo
No match found.

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.

Java Regex Finder Example

Regex Description

. Any character

\d Any digits, [0-9]

\D Any non-digit, [^0-9]

\s Whitespace character, [\t\n\x0B\f\r]

\S Non-whitespace character, [^\s]

\w Word character, [a-zA-Z_0-9]


Regex Description

\W Non-word character, [^\w]

\b Word boundary

\B Non -Word boundary

Below is the implementation of the Java Regex Finder:

// Java Program to implement regex


import java.io.*;
import java.util.regex.*;

// 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"));

// Check if all elements are non-numbers


System.out.println(Pattern.matches("\\D+", "1234"));

// Check if all the elements are non-numbers


System.out.println(Pattern.matches("\\D+", "Gfg"));

// Check if all the elements are non-spaces


System.out.println(Pattern.matches("\\S+", "gfg"));
}
}
Output
true
false
true
true
PatternSyntaxException Class in Java
Java uses the java.util.regex API for pattern matching with Regular expressions. To indicate any
syntax errors in a regular-expression pattern, Java provides a class called PatternSyntaxException.
PatternSyntaxException Class in Java:
While writing regular expressions, to identify and throw any syntactical errors in the pattern,
PatternSyntaxException class is used. This is an unchecked exception available in java.util.regex
package from java 1.4 version.
Syntax:
public class PatternSyntaxException extends IllegalArgumentException implements Serializable
Hierarchy of PatternSyntaxException class:

The constructor of PatternSyntaxException Class:


To construct a new instance of the PatternSyntaxException class.
Syntax:

PatternSyntaxException(String desc, String regex, int index)


Parameters:
 desc: Description of the error.
 regex: The pattern which is incorrect.
 index: The approximate index of the error in the regex pattern, or -1 if the index is not known.
 Methods in PatternSyntaxException Class
S.
No. Method Name Modifier Description

It returns the approximate index of the error in the


1 getIndex() int
pattern, or -1 if the index is not known.

2 getDescription() String It returns the description of the error in the pattern.

It returns the description of the syntax error in the pattern


and its index, the incorrect regular-expression pattern,
3 getMessage() String
and a visual indication of the error-index within the
pattern in a full detailed message.

It returns the regular-expression pattern which is


4 getPattern() String
incorrect.

Inherited Methods From java.lang.Throwable Class


As PatternSyntaxException class extends from Throwable class, below methods are inherited
from it.

S.
No. Method Name Modifier Description

This method is thread-safe


which appends the specified
addSuppressed(Throwable
1. void exception to the exceptions
exception)
that were suppressed in order
to deliver this exception.

It returns the cause of this


2. getCause() Throwable throwable or null if the cause
is nonexistent or unknown.

It provides programmatic
StackTraceElement access to the stack trace
3. getStackTrace()
[] information printed
by printStackTrace() method.
S.
No. Method Name Modifier Description

This method initializes the


4. initCause(Throwable cause) Throwable cause of this throwable to the
specified value.

Method prints this throwable


5. printStackTrace(PrintStream s) void and its backtrace to the
specified print stream.

This method is designed for


use by RPC frameworks and
other advanced systems
which allows the client to
setStackTrace(StackTraceElemen override the default stack
6. void
t[] stackTrace) trace. It sets the stack trace
elements that will be returned
by getStackTrace() and
printed by printStackTrace()
and related methods.

This method records within


this Throwable object
information about the current
7. fillInStackTrace() Throwable
state of the stack frames for
the current thread and fills in
the execution stack trace.

This method creates a


8. getLocalizedMessage() String localized description of this
throwable.

It returns an array containing


all of the exceptions that were
9. getSuppressed() Throwable[]
suppressed in order to deliver
this exception.

It prints this throwable and its


10
printStackTrace() void backtrace to the standard
.
error stream.
S.
No. Method Name Modifier Description

It prints this throwable and its


11
printStackTrace(PrintWriter s) void backtrace to the specified
.
print writer.

It returns a short description


of this throwable with the
name of the class of
12 this object, “: ” (a colon and a
toString() String
. space), and the result of
invoking this
object’s getLocalizedMessage
() method.

Inherited Methods From java.lang.Object Class


As PatternSyntaxException class extends from Object class, below methods are inherited from it.

S.
No. Method Name Modifier Description

equals(Object Indicates whether some other object is “equal to” this


1. boolean
obj) one or not.

It causes the current thread to wait until another


2. wait() void thread invokes the notify() method or the notifyAll()
method for this object.

It causes the current thread to wait until either another


wait(long thread invokes the notify() method or the notifyAll()
3. void
timeout) method for this object, or the amount of time that is
specified in the parameter has elapsed.

It wakes up all the threads that are waiting on this


4. notifyAll() void
object’s monitor.

5. hashCode() int It returns a hash code value for this object.


S.
No. Method Name Modifier Description

protected
6. clone() It creates and returns a copy of this object.
Object

It is called by the garbage collector on an object when


protected garbage collection determines that there are no more
7. finalize()
void references to the object. We can perform cleanup
actions before the object is irrevocably discarded.

It causes the current thread to wait until another


wait(long thread invokes the notify() method or the notifyAll()
8. timeout, int void method for this object, or some other thread interrupts
nanos) the current thread, or a certain amount of real time
that is specified has elapsed.

It wakes up a single thread that is waiting on this


9. notify() void
object’s monitor.

It returns the runtime class of this Object. The


10. getClass() Class<?> returned Class object is the object that is locked by
static synchronized methods of the represented class.

Example 1: Create a class “Demo1” to replace all non-alphanumeric characters with space
in the given message using Regular expression.
 Java

// Java program to demonstrate the working


// of PatternSyntaxException class methods

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class Demo1 {


private static String REGEX = "?[^a-zA-Z0-9]";
private static String MSG
= "Learn/ java? in GeeksforGeeks!!";
private static String REPLACE = " ";
public static void main(String[] args)
{

try {
// Get Pattern class object to compile the
// regular expression.
Pattern pattern = Pattern.compile(REGEX);

// Get a matcher object


Matcher matcher = pattern.matcher(MSG);

// Using matcher object, replace the string


MSG = matcher.replaceAll(REPLACE);

// catch block to handle PatternSyntaxException.


}
catch (PatternSyntaxException pse) {
System.out.println("PatternSyntaxException: ");
System.out.println("Description: "
+ pse.getDescription());
System.out.println("Index: " + pse.getIndex());
System.out.println("Message: "
+ pse.getMessage());
System.out.println("Pattern: "
+ pse.getPattern());
System.exit(0);
}

System.out.println("Output: " + MSG);


}
}

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

// Java program to demonstrate the working


// of PatternSyntaxException class methods

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class Demo2 {

private static String REGEX = "[Geek";


private static String MSG
= "Hi Geek, Welcome to GeeksforGeeks!!";

public static void main(String[] args)


{

Pattern pattern = null;


Matcher matcher = null;
try {
pattern = Pattern.compile(REGEX);
matcher = pattern.matcher(MSG);
}
catch (PatternSyntaxException pse) {
System.out.println("PatternSyntaxException: ");
System.out.println("Pattern: "
+ pse.getPattern());
System.out.println("Description: "
+ pse.getDescription());
System.out.println("Message: "
+ pse.getMessage());
System.out.println("Index: " + pse.getIndex());
System.exit(0);
}
boolean found = false;
while (matcher.find()) {
System.out.println("Found the text at "
+ matcher.start());
found = true;
}
if (!found) {
System.out.println("No match found!");
}
}
}

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.

This interface can be declared by using the below syntax,


Syntax:

public interface MatchResult

Methods of MatchResult Interface


The query methods of the MatchResult interface are discussed in detail below.

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 {

// Initializing regular expression string


private static final String regularExpression
= "(.*)(\\d+)(.*)";

// Initializing input string


private static final String input
= "Hello World!, 41346, these are the numbers.";

// Main method
public static void main(String[] args)
{
// Compiling the given regular expression string
Pattern myPattern
= Pattern.compile(regularExpression);

// Applying matcher operation


Matcher myMatcher = myPattern.matcher(input);

if (myMatcher.find()) {

// Retrieve the MatchResult Object


MatchResult myResult
= myMatcher.toMatchResult();

// Printing the starting index of the match


System.out.println(
"Starting index of the match: "
+ myResult.start());
}
}
}

Output
Start index of the match: 0
Example:

// Java program to illustrate the working of end() method


import java.io.*;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class GFG {

// Initializing the regular expression string


private static final String regularExpression
= "(.*)(\\d+)(.*)";

// Initializing the input string


private static final String input
= "Hello World!, 41346, these are the numbers.";

// Main method
public static void main(String[] args)
{
// Compiling the regular expression string
Pattern myPattern
= Pattern.compile(regularExpression);

// Applying the matcher operation


Matcher myMatcher = myPattern.matcher(input);
if (myMatcher.find()) {
// Retrieve the MatchResult object
MatchResult myResult
= myMatcher.toMatchResult();

// Prints the offset following the last


// character matched
System.out.println("First Capturing Group: "
+ myResult.end());
// Prints the number of capturing groups in this
// match result's pattern.
System.out.println(
"The number of capturing groups is equal to: "
+ myResult.groupCount());
// Prints the input subsequence that was held

// by the given group during the last match


// occurred.
System.out.println(
"Second Capturing Group - Match String: "
+ myResult.group(1));
// Prints the input sequence matched by the

// previous match.
System.out.println("First Capturing Group"
+ myResult.group());
// Prints the offset after the last

// character of the sequence held by


// the given group at the time of match.
System.out.println("Second Capturing Group: "
+ myResult.end(1));
// Prints the start index of the sequence

// that was held by the given group during the


// match.
System.out.println("Second Capturing Group: "
+ myResult.start(1));
// Printing the starting index of the match

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.

Simple example of java package


The package keyword is used to create a package in java.

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:

1. javac -d directory javafilename

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).

How to run java package program


You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
Output:Welcome to package

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.

Example of package by import package.classname


//save by A.java

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

To Run: java uttaranchal.uscs.mca.Simple

Output: Hello subpackage

Java IO: Input-output in Java with Examples


Java brings various Streams with its I/O package that helps the user to perform all the input-output
operations. These streams support all the types of objects, data-types, characters, files etc to fully
execute the I/O operations.

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();
}
}
}
}

Reading and Writing Files


A stream can be defined as a series of information as outlined above. To read data from a source,
the InputStream is used, while OutputStream is used to write data to a destination.
Below is a class hierarchy to handle input and output streams in Java.

FileInputStream and FileOutputStream are two significant streams in java.

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.

InputStream inputStream = new FileInputStream("C:/java/test");


It requires a file object to generate an input stream object after the constructor to read the file. First, we use the
File () method to generate a file object as follows:

File file = new File("C:/java/test");

InputStream inputStream = new FileInputStream(f);

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.

Method & Description

public int read(int r)throws IOException{}

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.

protected void finalize()throws 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.

public void close() throws IOException{}

The file output stream is closed by this method. Releases any file-related system resources. Throws an exception related to the IOE.

public int available() throws IOException{}

Gives the number of bytes that can be read from this file input stream. Returns an int. It throws an IOException.

public int read(byte[] r) throws IOException{}


Method & Description

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:

OutputStream outputStream = new FileOutputStream("C:/java/test")

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:

File file = new File("C:/java/test");

OutputStream outputStream = new FileOutputStream(f);

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.

Method & Description

protected void finalize()throws 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 more references to this stream. It throws an IOException.
Method & Description

public void close() throws IOException{}

This method closes the file output stream. Releases any system resources associated with the file. It throws an
IOException.

public void write(byte[] w)

Writes w.length bytes from the mentioned byte array to the OutputStream.

public void write(int w)throws IOException{}

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");
}
}
}

Collections framework in Java


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


o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and manipulating a group of
objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm

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.

To instantiate the List interface, we must use :

1. List <data-type> list1= new ArrayList();


2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. 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.

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.

Consider the following example.

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.

Consider the following example.

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.

Consider the following example.

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.

Queue interface can be instantiated as:

1. Queue<String> q1 = new PriorityQueue();


2. Queue<String> q2 = new ArrayDeque();

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.

Consider the following example.

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.

Deque can be instantiated as:

1. Deque d = new ArrayDeque();


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.

ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.

Consider the following example.

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.

Set can be instantiated as:

1. Set<data-type> s1 = new HashSet<data-type>();


2. Set<data-type> s2 = new LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-type>();
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.

Consider the following example.

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.

Consider the following example.

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.

The SortedSet can be instantiated as:

1. SortedSet<data-type> set = new TreeSet();


TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet
also contains unique elements. However, the access and retrieval time of TreeSet is quite fast. The
elements in TreeSet stored in ascending order.

Consider the following example:

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

You might also like