Java Unit-4 Student PPT-final
Java Unit-4 Student PPT-final
JAVA PROGRAMMING
UNIT IV
UNIT IV STRING HANDLING AND COLLECTIONS
SYLLABUS
• Lambda Expressions
• String Handling
• Collections
The Collection Interfaces
TheCollection Classes
• Iterator – Map
• Regular Expression Processing
What is lambda expression in Java?
• A lambda expression is a short block of code which takes in
parameters and returns a value.
• Lambda expressions are similar to methods, but they do not need a
name and they can be implemented right in the body of a method.
WITHOUT LAMBDA EXPRESSION WITH LAMBDA EXPRESSION
} };
Thread t1=new Thread(r1);
class ThreadExample{
t1.start();
public static void main(String[] args) {
}
ThreadImpl r1=new ThreadImpl(); }
Thread t1=new Thread(r1);
t1.start();
}
}
Advantage of Lambda Expression?
Reduced code size Where is Lambda Expression?
LAMBDA EXPRESSION
What is Lambda Expression?
• Lambda expressions are similar to methods and are a short block of code that takes
• They are anonymous or unnamed method that does not execute on their own.
• An interface which has only one abstract method is called functional interface.
• Java lambda expression is treated as a function, so compiler does not create .class
file.
LAMBDA EXPRESSION
Syntax
(argument-list) -> {body}
• When a lambda expression occurs in a target type context, an instance of a class is automatically created that
implements the functional interface, with the lambda expression defining the behavior of the abstract method
• When that method is called through the target, the lambda expression is executed
• Inorder for a lambda expression to be used in a target type context, the type of the abstract method and the
Output: double[0]));
}
}
• A lambda expression can use an instance or static variable defined by its enclosing class.
• A lambda expression can explicitly and implicitly access to this, which refers to the invoking instance of the lambda
expression's enclosing class.
• A lambda expression can get or set the value of an instance or static variable and call a method defined by its enclosing
class.
Variable Capture
• A variable capture happens when a lambda expression uses a local variable from its enclosing scope.
• In this case, a lambda expression may only use local variables that are effectively final.
• An effectively final variable is one whose value does not change after it is first assigned.
• There is no need to explicitly declare such a variable as final, although doing so would not be an error.
Example
interface MyFunc {
Note 1: int func(int n);
}
num++ is illegal because it attempts to modify
public class Main {
the value of num. public static void main(String args[])
{
Note 2: // A local variable that can be captured.
error, because it would remove the effectively int num = 10;
• String and StringBuffer classes are declared as final,so there cannot be sub classes of these classes.
Creating Strings:
There are two ways to create String object:
By string literal
By new keyword (Using constructors)
Example:
String str = "abc"; //Using literal
String str = new String(“abc”); //Using new keyword
String class Methods
1) The length() method returns the length of the string.
Eg: System.out.println("Varun".length()); // prints 5
equals() Method- This method is used to compare the invoking String to the
object specified. It will return true, if the argument is not null and it is String
object which contains the same sequence of characters as the invoking String.
• String s1 = “HELLO”;
• String s2 = “HELLO”;
HELLO
3e25ae
s1
3e25ae
s2
Comparing Strings using == operator
What is the output ?
public class StringTest{
public static void main(String[] args){
String s1="Hello";
String
s2="Hello";
if(s1==s2)
System.out.prin
tln("String
objects
referenced
are same");
} else
Output: String objects referenced
System.out.println("String are same
objects referenced
are not same");
}
Comparing Strings using equals method
What is the output ?
public class StringTest{
public static void main(String[] args){
String s1="Hello";
String s2="Hello";
if(s1.equals(s2))
System.out.print
ln("Strings are
equal");
else
System.out.print
ln("Strings are
not equal");
} Output: Strings are equal
}
23
Strings created using new keyword
HELLO
3e25ad
s1
HELLO
3e25ae
s2
Comparing Strings using == operator
What is the output ?
public class StringTest{
public static void main(String[] args){
String s1= new String("Hello");
String s2= new String("Hello");
if(s1==s2)
System.out.println("String objects
referenced
are same ");
else
System.out.println("String objects referenced
are not same");
} }
Output: String objects referenced are not same
Comparing Strings using equals method
What is the output ?
public class StringTest{
public static void main(String[] args){
String s1= new String("Hello");
String s2= new String("Hello");
if(s1.equals(s2))
System.out.println("Strings are
equal");
else
System.out.println("Strings are not
equal");
}
}
Output: Strings are equal
String class Methods
This method is similar to compareTo() method but this does not take
the case of strings into consideration.
String class Methods (Contd.).
It searches for the character represented by ch within this string and returns the index of first
occurrence of this character
It searches for the substring specified by str within this string and returns the index of first
occurrence of this substring
public int indexOf(int ch, int fromIndex)- It searches for the character represented by
ch within this string and returns the index of first occurrence of this character starting from the position
specified by fromIndex
public int indexOf(String str, int fromIndex) - Returns the index within this string of
the first occurrence of the specified substring, starting at the specified index.
lastIndexOf() –It searches for the last occurrence of a particular character or substring
substring() - This method returns a new string which is actually a substring of this string.
It extracts characters starting from the specified index all the way till the end of the string
public String substring(int beginIndex)
Eg: "unhappy".substring(2) returns "happy"
34
String class Methods (Contd.).
– StringBuffer()//empty object
– StringBuffer(int capacity)//creates an empty object with a capacity
for storing a string
– StringBuffer(String str)//create StringBuffer object by using a string
38
String Buffer Operations
• StringBuffer has two main operations methods – append and insert
• Index specifies at which point the string will be inserted into the
invoking StringBuffer object
• delete() - This method is used to delete specified
substring within the StringBuffer object
40
StringBuffer Operations (Contd.).
replace() - This method is used to replace part of this StringBuffer(substring)
with another substring
42
Example
class FullName{
public static void main(String[] args)
{ StringBuffer sb=new StringBuffer();
String surname="Mallapudi";
String lastname="vijaya";
sb.append(surname);
System.out.println("Name: "+sb);
int n=surname.length();
sb.insert(n,lastname);
System.out.println("Full name:
"+sb);
System.out.println("In reverse =
"+sb.reverse());
43 }
StringBuffer Operations (Contd.).
• capacity() – We can find the capacity of the
StringBuffer using this method
•What is capacity ?
• The capacity is the amount of storage available for the characters
that have just been inserted
•public int capacity()
• Java Collections can achieve all the operations that you perform on a
data such as searching, sorting, insertion, manipulation, and deletion.
interface Collection<E>
• Here, E specifies the type of objects that the collection will hold.
• Collection extends the Iterable interface. This means that all collections
can be cycled through by use of the foreach style for loop.
The Methods Declared by Collection Interface:
The Methods Declared by Collection Interface:
The List Interface
• The Collection interface is the foundation upon which the Collections
Framework is built because it must be implemented by any class that
defines a collection.
interface Collection<E>
• Here, E specifies the type of objects that the collection will hold.
• Collection extends the Iterable interface. This means that all collections
can be cycled through by use of the foreach style for loop.
The Methods Declared by List Interface:
The ArrayList Class
• The ArrayList class extends AbstractList and implements the List interface.
• Standard arrays are of fixed size. After arrays are created they cannot grow
or shrink.
ArrayList( )
• Builds an empty array list.
ArrayList(int capacity)
• Builds an array list that has the specified initial capacity.
• The capacity is the size of the underlying array that is used to store the elements.
• The capacity grows automatically as elements are added to an array list.
Example: System.out.println("Size of list after additions: " + list.size());
import java.util.*; // Display the array list.
class ArrayListDemo { System.out.println("Contents of list: " + list);
public static void main(String args[]) { // Remove elements from the array list.
// Create an array list. list.remove("F");
ArrayList<String> list = new ArrayList<String>(); list.remove(2);
System.out.println("Initial size of list: " + list.size()); System.out.println("Size of list after deletions: " + list.size());
// Add elements to the array list. System.out.println("Contents of list: " + list);
list.add("A"); }
list.add("C"); }
list.add("D"); Output:
list.add("E"); Initial size of list: 0
list.add("F"); Size of list after additions: 7
list.add("G"); Contents of list: [A, B, C, D, E, F, G]
list.add(1, "B"); Size of list after deletions: 5
Contents of list: [A, B, D, E, G]
Obtaining an Array from an ArrayList
• LinkedList( )
• Builds an empty linked list.
OUTPUT
[Gamma, Eta, Alpha, Epsilon, Omega,
Beta]
LinkedHashSet Class
• LinkedHashSet class extends HashSet and adds no members of its
own
• Each of the collection classes provides an iterator() method that returns an iterator object to
the start of the collection.
• In general, to use an iterator to cycle through the contents of a collection, follow these steps:
Obtain an iterator to the start of the collection by calling the collection’s iterator()method.
A map is an object that stores associations between keys and values, or key/value pairs.
Given a key, you can find its value. Both keys and values are objects.
The keys must be unique, but the values may be duplicated.
Some map scan accept a null key and null values, others cannot.
Map don’t implement the Iterable interface. This means that you cannot cycle through a map
using a for-each style for loop. Furthermore, you can’t obtain an iterator to a map.
THE MAP INTERFACES:
LinkedHashMap(int capacity)
LinkedHashMap(int capacity, float fillRatio)
Order)
The IdentityHashMap Class:
IdentityHashMap extends AbstractMap and implements the Map interface. It is similar to
HashMap except that it uses reference equality when comparing elements.
The EnumMap Class:
EnumMap extends AbstractMap and implements Map. It is specifically for use with
keys of an enum type.
Topics
Introduction
Matcher class
Regex methods
Basic regexes
String match
String replace
Wildcards and anchors
EXAMPLES
INTRODUCTION
The regular expression package, java.util.regex lets you perform sophisticated pattern matching operations.
Regular expressions (regex) are powerful tools for pattern matching and manipulating strings. In Java, regular
expressions are supported through the java.util.regex package. Regular expressions allow you to define patterns to match, search,
and replace specific text patterns within a larger string.
/[a-zA-Z_\-]+@(([a-zA-Z_\-])+\.)+[a-zA-Z]{2,4}/