[go: up one dir, main page]

0% found this document useful (0 votes)
14 views37 pages

Mod 4 Chap-1

aa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views37 pages

Mod 4 Chap-1

aa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

OOPJ http://www.youtube.

com/c/EDULINEFORCSE
STUDENTS

MODULE 4
ADVANCED FEATURES OF JAVA
CHAPTER 1
Java Library & Collections framework

Prepared By Mr. EBIN PM, AP, IESCE 1

STRING
• In Java, string is basically an object that represents sequence of
char values. An array of characters works same as Java string. For
example:
char[ ] ch={‘h','a',‘i',‘j',‘a',‘v',‘a'};
String s=new String(ch);
is same as:
String s = “haijava";
• Java String class provides a lot of methods to perform operations
on strings such as compare(), concat(), equals(), split(), length(),
replace(), compareTo(), intern(), substring() etc.
Prepared By Mr.EBIN PM, AP, IESCE EDULINE 2

Prepared By Mr. EBIN PM, AP, IESCE 1


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

 Create a string object


There are two ways to create String object:
• By string literal
• By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
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:
Prepared By Mr.EBIN PM, AP, IESCE EDULINE 3

String s1="Welcome";
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".

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 4

Prepared By Mr. EBIN PM, AP, IESCE 2


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

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

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 5

2) By new keyword
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).

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 6

Prepared By Mr. EBIN PM, AP, IESCE 3


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

String Example

OUTPUT

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 7

STRING CONSTRUCTORS
• The string class supports several types of constructors in Java APIs.
The most commonly used constructors of String class are as
follows:
1. String() : To create an empty String, we will call a default
constructor. For example:
String s = new String();
• It will create a string object in the heap area with no value

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 8

Prepared By Mr. EBIN PM, AP, IESCE 4


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

2. String(String str) : It will create a string object in the heap area


and stores the given value in it. For example:
String s2 = new String(“Hello Java“);
Now, the object contains Hello Java.

3. String(char chars[ ]) : It will create a string object and stores the


array of characters in it. For example:
char chars[ ] = { ‘a’, ‘b’, ‘c’, ‘d’ };
String s3 = new String(chars);
The object reference variable s3 contains the address of the value
stored in the heap area.
Prepared By Mr.EBIN PM, AP, IESCE EDULINE 9

Let’s take an example program where we will create a string object


and store an array of characters in it

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 10

Prepared By Mr. EBIN PM, AP, IESCE 5


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

4. String(char chars[ ], int startIndex, int count)


• It will create and initializes a string object with a subrange of a
character array.
• The argument startIndex specifies the index at which the subrange
begins and count specifies the number of characters to be copied.
For example:
char chars[ ] = { ‘w’, ‘i’, ‘n’, ‘d’, ‘o’, ‘w’, ‘s’ };
String str = new String(chars, 2, 3);
• The object str contains the address of the value ”ndo” stored in the
heap area because the starting index is 2 and the total number of
characters to be copied is 3

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 11

EXAMPLE

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 12

Prepared By Mr. EBIN PM, AP, IESCE 6


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

• In this example program, we will construct a String object that


contains the same characters sequence as another string object.
As you can see the output, s1 and
s2 contain the same string.
Thus, we can create one string
from another string.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 13

5. String(byte byteArr[ ]) : It constructs a new string object by


decoding the given array of bytes (i.e, by decoding ASCII values into
the characters) according to the system’s default character set.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 14

Prepared By Mr. EBIN PM, AP, IESCE 7


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

6. String(byte byteArr[ ], int startIndex, int count)


This constructor also creates a new string object by decoding the
ASCII values using the system’s default character set.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 15

STRING LENGTH
• The java string length() method gives length of the string. It returns
count of total number of characters.
• Internal implementation
public int length() {
return value.length;
}
Signature - The signature of the string length() method is given
below:
public int length()

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 16

Prepared By Mr. EBIN PM, AP, IESCE 8


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

String length() method example - 1

Output

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 17

String length() method example - 2

Output

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 18

Prepared By Mr. EBIN PM, AP, IESCE 9


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

STRING COMPARISON
• We can compare string in java on the basis of content and reference
• There are three ways to compare string in java:
By equals() method
By = = operator
By compareTo() method
String compare by equals() method
• The String equals() method compares the original content of the
string.
• It compares values of string for equality. String class provides two
methods
Prepared By Mr.EBIN PM, AP, IESCE EDULINE 19

public boolean equals(Object another) compares this string to the


specified object.
public boolean equalsIgnoreCase(String another) compares this
String to another string, ignoring case.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 20

Prepared By Mr. EBIN PM, AP, IESCE 10


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

Example 2

Output

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 21

String compare by == operator


• The = = operator compares references not values.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 22

Prepared By Mr. EBIN PM, AP, IESCE 11


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

String compare by compareTo() method


• The String compareTo() method compares values lexicographically
and returns an integer value that describes if first string is less than,
equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
s1 == s2 : 0
s1 > s2 : positive value
s1 < s2 : negative value

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 23

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 24

Prepared By Mr. EBIN PM, AP, IESCE 12


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

Eg:
Output

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 25

SEARCHING STRINGS
String contains()
• The java string contains() method searches the sequence of
characters in this string.
• It returns true if sequence of char values are found in this string
otherwise returns false.
Internal implementation
public boolean contains(CharSequence s) {
return indexOf(s.toString()) > -1;
}
Prepared By Mr.EBIN PM, AP, IESCE EDULINE 26

Prepared By Mr. EBIN PM, AP, IESCE 13


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

Signature
• The signature of string contains() method is given below:
public boolean contains(CharSequence sequence)
Output

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 27

Eg 2 - The contains() method searches case sensitive char sequence.


If the argument is not case sensitive, it returns false. Let's see an
example below.

Output

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 28

Prepared By Mr. EBIN PM, AP, IESCE 14


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

Eg 3 -The contains() method is helpful to find a char-sequence in the


string. We can use it in control structure to produce search based
result. Let us see an example below.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 29

CHARACTER EXTRACTION
String charAt()
• The java string charAt() method returns a char value at the given
index number.
• The index number starts from 0 and goes to n-1, where n is length
of the string.
• It returns StringIndexOutOfBoundsException if given index number
is greater than or equal to this string length or a negative number.
• Signature - The signature of string charAt() method is given below:
public char charAt(int index)

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 30

Prepared By Mr. EBIN PM, AP, IESCE 15


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

Example:

Output
t

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 31

StringIndexOutOfBoundsException with charAt()


• Let's see the example of charAt() method where we are passing
greater index value.
• In such case, it throws StringIndexOutOfBoundsException at run
time.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 32

Prepared By Mr. EBIN PM, AP, IESCE 16


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

Java String charAt() Example 3


• Let's see a simple example where we are accessing first and last
character from the provided string.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 33

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 34

Prepared By Mr. EBIN PM, AP, IESCE 17


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

Java String charAt() Example 4


• Let's see an example where we are accessing all the elements
present at odd index.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 35

Java String charAt() Example 5


• Let's see an example where we are counting frequency of a
character in the string.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 36

Prepared By Mr. EBIN PM, AP, IESCE 18


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

MODIFY STRINGS
• The java string replace() method returns a string replacing all the
old char or CharSequence to new char or CharSequence.
Signature
• There are two type of replace methods in java string.
public String replace(char oldChar, char newChar)
and
public String replace(CharSequence target, CharSequence
replacement)
• The second replace method is added since JDK 1.5.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 37

 String replace(char old, char new) method example


public class ReplaceExample1{
public static void main(String args[]){
String s1="java is a very good language";
// replaces all occurrences of 'a' to 'e'
String replaceString=s1.replace('a','e');
System.out.println(replaceString);
}}
Output
jeve is e very good lenguege

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 38

Prepared By Mr. EBIN PM, AP, IESCE 19


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

String replace(CharSequence target, CharSequence


replacement) method example

Output
my name was khan my name was java

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 39

String replace() Method Example 3

Output

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 40

Prepared By Mr. EBIN PM, AP, IESCE 20


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

• The java string replaceAll() method returns a string replacing all the
sequence of characters matching regex and replacement string.
Internal implementation
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}

Signature
public String replaceAll(String regex, String replacement)

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 41

 String replaceAll() example: replace character


• Let's see an example to replace all the occurrences of a single
character.
public class ReplaceAllExample1{
public static void main(String args[]){
String s1="java is a very good language";
String replaceString=s1.replaceAll("a","e");//replaces all occurrences
of "a" to "e"
System.out.println(replaceString);
}}
Output jeve is e very good lenguege
Prepared By Mr.EBIN PM, AP, IESCE EDULINE 42

Prepared By Mr. EBIN PM, AP, IESCE 21


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

 String replaceAll() example: replace word


• Let's see an example to replace all the occurrences of single word
or set of words.

Output
My name was Khan. My name was Bob. My name was Sonoo.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 43

 String replaceAll() example: remove white spaces


• Let's see an example to remove all the occurrences of white spaces.

Output
MynameisKhan.MynameisBob.MynameisSonoo.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 44

Prepared By Mr. EBIN PM, AP, IESCE 22


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

STRING VALUE OF ( )
• The java string valueOf() method converts different types of values
into string.
• By the help of string valueOf() method, we can convert int to
string, long to string, boolean to string, character to string, float to
string, double to string, object to string and char array to string.
Internal implementation
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 45

 Signature
• The signature or syntax of string valueOf() method is given below:
public static String valueOf(boolean b)
public static String valueOf(char c)
public static String valueOf(char[] c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
public static String valueOf(Object o)

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 46

Prepared By Mr. EBIN PM, AP, IESCE 23


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

 valueOf() method example

Output
3010

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 47

valueOf(boolean bol) Method Example


This is a boolean version of overloaded valueOf() method. It takes
boolean value and returns a string. Let's see an example.

Output
true
false

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 48

Prepared By Mr. EBIN PM, AP, IESCE 24


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

valueOf(char ch) Method Example


This is a char version of overloaded valueOf() method. It takes
char value and returns a string. Let's see an example.

Output
A
B

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 49

valueOf(float f) and valueOf(double d) Example


This is a float version of overloaded valueOf() method. It takes
float value and returns a string. Let's see an example.

Output
10.05
10.02

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 50

Prepared By Mr. EBIN PM, AP, IESCE 25


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

String valueOf() Complete Examples

 Output

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 51

Immutable String in Java


• In java, string objects are immutable. Immutable simply means
unmodifiable or unchangeable. Once string object is created its
data or state can't be changed but a new string object is created.
Example

Output Sachin
Prepared By Mr.EBIN PM, AP, IESCE EDULINE 52

Prepared By Mr. EBIN PM, AP, IESCE 26


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

It can be understood by the diagram given below. Here Sachin is not


changed but a new object is created with sachintendulkar. That is
why string is known as immutable.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 53

• As you can see in the figure that two objects are created but s
reference variable still refers to "Sachin" not to "Sachin Tendulkar".
• But if we explicitely assign it to the reference variable, it will refer
to "Sachin Tendulkar" object. For example:

Output
Sachin Tendulkar
In such case, s points to the
"Sachin Tendulkar". Please notice
that still sachin object is not
modified.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 54

Prepared By Mr. EBIN PM, AP, IESCE 27


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

Why string objects are immutable in java


• Because java uses the concept of string literal.
• Suppose there are 5 reference variables,all referes to one object
"sachin".
• If one reference variable changes the value of the object, it will be
affected to all the reference variables.
• That is why string objects are immutable in java.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 55

String and StringBuffer

• Java StringBuffer class is used to create mutable (modifiable)


string. The StringBuffer class in java is same as String class except
it is mutable i.e. it can be changed.
Prepared By Mr.EBIN PM, AP, IESCE EDULINE 56

Prepared By Mr. EBIN PM, AP, IESCE 28


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

 Important Constructors of StringBuffer class

Mutable string - A string that can be modified or changed is known


as mutable string. StringBuffer and StringBuilder classes are used
for creating mutable string.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 57

StringBuffer append() method

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 58

Prepared By Mr. EBIN PM, AP, IESCE 29


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

StringBuffer insert() method


The insert() method inserts the given string with this string at the
given position.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 59

StringBuffer replace() method


The replace() method replaces the given string from the specified
beginIndex and endIndex.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 60

Prepared By Mr. EBIN PM, AP, IESCE 30


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

StringBuffer delete() method


The delete() method of StringBuffer class deletes the string from
the specified beginIndex to endIndex.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 61

 StringBuffer reverse() method


The reverse() method of StringBuffer class reverses the current
string.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 62

Prepared By Mr. EBIN PM, AP, IESCE 31


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

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

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 63

Collection in Java - Represents a single unit of objects, i.e., a


group.
framework in Java
• It provides readymade architecture.
• It represents a set of classes and interfaces.
• It is optional.
Collection framework
The Collection framework represents a unified architecture for
storing and manipulating a group of objects. It has:
• Interfaces and its implementations, i.e., classes
• Algorithm
Prepared By Mr.EBIN PM, AP, IESCE EDULINE 64

Prepared By Mr. EBIN PM, AP, IESCE 32


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

Hierarchy of Collection Framework

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 65

The java.util package contains all the classes and interfaces for the
Collection framework.
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.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 66

Prepared By Mr. EBIN PM, AP, IESCE 33


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

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 :

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 67

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


List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();
There are various methods in List interface that can be used to
insert, delete, and access the elements from the list.
The classes that implement the List interface are given below.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic
array to store the duplicate element of different data types.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 68

Prepared By Mr. EBIN PM, AP, IESCE 34


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

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

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 69

Java ArrayList class uses a dynamic array for storing the elements.
It is like an array, but there is no size limit. We can add or remove
elements anytime.
 So, it is much more flexible than the traditional array. It is found in
the java.util package. It is like the Vector in C++.
The ArrayList in Java can have the duplicate elements also. It
implements the List interface so we can use all the methods of List
interface here.
The ArrayList maintains the insertion order internally.
It inherits the AbstractList class and implements List interface.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 70

Prepared By Mr. EBIN PM, AP, IESCE 35


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

The important points about Java ArrayList class are:


• Java ArrayList class can contain duplicate elements.
• Java ArrayList class maintains insertion order.
• Java ArrayList class is non synchronized.
• Java ArrayList allows random access because array works at the
index basis.
• In ArrayList, manipulation is little bit slower than the LinkedList in
Java because a lot of shifting needs to occur if any element is
removed from the array list.

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 71

ArrayList Example

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 72

Prepared By Mr. EBIN PM, AP, IESCE 36


OOPJ http://www.youtube.com/c/EDULINEFORCSE
STUDENTS

Iterating ArrayList using Iterator

Prepared By Mr.EBIN PM, AP, IESCE EDULINE 73

Prepared By Mr. EBIN PM, AP, IESCE 37

You might also like