22CS202 Java Unit 4
22CS202 Java Unit 4
proceeding:
This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document through
email in error, please notify the system manager. This document contains
proprietary information and is intended only to the respective group / learning
community as intended. If you are not the addressee you should not disseminate,
distribute or copy through e-mail. Please notify the sender immediately by e-mail
if you have received this document by mistake and delete this document from your
system. If you are not the intended recipient you are notified that disclosing,
copying, distributing or taking any action in reliance on the contents of this
information is strictlyprohibited.
22CS202 Java Programming
4
1. CONTENTS
1 Contents 5
2 Course Objectives 6
3 Pre Requisites 7
4 Syllabus 8
5 Course outcomes 9
7 Lecture Plan 11
9 Lecture Notes 13
10 Assignments 78
12 Part B Questions 86
16 Assessment Schedule 92
Prescribed Text Books & Reference
17 Books 93
22CS202
Java Programming
22CS101
Problem Solving Using C++
4. Syllabus
JAVA PROGRAMMING L T P C
22CS202
(Common to CSE, CSD, EEE, ECE, ME, IT, ADS and CSBS) 3 0 2 4
OBJECTIVES:
The Course will enable learners to:
➢ To explain object oriented programming concepts and fundamentals of Java
➢ To apply the principles of packages, interfaces and exceptions
➢ To develop a Java application with I/O streams, threads and generic programming
➢ To build applications using strings and collections.
➢ To apply the JDBC concepts
An Overview of Java - Data Types, Variables, and Arrays – Operators - Control Statements –
Class Fundamentals – Declaring objects – Methods – Constructors – this keyword - Overloading
methods - Overloading constructors - Access Control – Static – Final.
List of Exercise/Experiments:
1. 1. Develop a Java application to generate Electricity bill. You must use one super class
called EB Bill and must have two sub classes namely Domestic Bill and Commercial Bill.
Create a class with the following members: Consumer no., consumer name, previous month
reading, current month reading, type of EB connection (i.e domestic or commercial).
Compute the bill amount using the following tariff
If the type of the EB connection is domestic, calculate the amount to be paid as follows:
First 100 units - Rs. 1 per unit
101-200 units - Rs. 2.50 per unit
201 -500 units - Rs. 4 per unit
> 501 units - Rs. 6 per unit
If the type of the EB connection is commercial, calculate the amount to be paid as follows:
First 100 units - Rs. 2 per unit
101-200 units - Rs. 4.50 per unit
201 -500 units - Rs. 6 per unit
> 501 units - Rs. 7 per unit
2. Arrays Manipulations: (Use Methods for implementing these in a Class)
Find kth smallest element in an unsorted array
Find the sub array with given sum
Matrix manipulations – Addition, Subtraction, Multiplication
Remove duplicate elements in an Array
Accept an integer value N and print the Nth digit in the integer sequence 1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15 and so on till infinity.
Example: The 11th digit in the sequence 12345678910111213…. is 0.
4. Syllabus Contd...
UNIT II INHERITANCE, INTERFACES AND EXCEPTION HANDLING 15
Inheritance: Inheritance basics, Using super, Method Overriding, Using Abstract Classes,
Using final with Inheritance - Package and Interfaces: Packages, Packages and member
access, Importing Packages, Interfaces, Static Methods in an Interface – Exception
Handling: Exception-Handling Fundamentals, Exception Types, Uncaught Exceptions, Using
try and catch, Multiple catch Clauses, Nested try Statements, throw, throws, finally, Java’s
Built-in Exceptions.
List of Exercise/Experiments:
1. Develop a Java application with Employee class with Emp_name, Emp_id, Address,
Mail_id, Mobile_no as members. Inherit the classes, Programmer, Assistant Professor,
Associate Professor and Professor from employee class. Add Basic Pay (BP) as the
member of all the inherited classes with 97% of BP as DA, 10 % of BP as HRA, 12% of
BP as PF, 0.1% of BP for staff club fund. Generate pay slips for the employees with their
gross and net salary.
2. Design a Java interface for ADT Stack. Implement this interface using array and built-in
classes. Provide necessary exception handling in both the implementations.
3. Write a Java Program to create an abstract class named Shape that contains two
integers and an empty method named print Area(). Provide three classes named
Rectangle, Triangle and Circle such that each one of the classes extends the class Shape.
Each one of the classes contains the methods print Area () that prints the area of the
given shape and Numberofsides() that prints the number of sides of the given shape.
4. Write a Java program to apply built-in and user defined exceptions.
List of Exercise/Experiments:
1. Write a Java program that correctly implements producer consumer problem using the
concept of inters thread communication.
2. Write a Java program to read and copy the content of one file to other by handling all
file related exceptions.
4. Syllabus Contd...
UNIT IV STRING HANDLING AND COLLECTIONS 15
List of Exercise/Experiments:
1. String Manipulation:
a) Reversing a set of words and count the frequency of each letter in the string.
b) Pattern Recognition - Find the number of patterns of form 1[0]1 where [0]
represents any number of zeroes (minimum requirement is one 0) there should
not be any other character except 0 in the [0] sequence in a given binary string.
c) Remove all the occurrences of string S2 in string S1 and print the remaining.
d) Find the longest repeating sequence in a string
e) Print the number of unique string values that can be formed by rearranging the
letters in the string S.
2. Collections:
a) Write a program to perform string operations using ArrayList. Write functions for the
following
b) Append - add at end
c) Insert – add at particular index
d) Search
e) List all string starts with given letter
f) b. Find the frequency of words in a given text.
List of Exercise/Experiments:
1. Mini Project (using JDBC)
4. Syllabus Contd...
OUTCOMES:
Upon completion of the course, the students will be able to:
CO1: Understand the object oriented programming concepts and fundamentals of Java.
CO2: Develop Java programs with the packages, interfaces and exceptions.
CO3: Build Java applications with I/O streams, threads andgenerics programming.
CO4: Apply strings and collections in developing applications.
CO5: Implement the concepts of JDBC.
TEXT BOOK:
1.Herbert Schildt, “Java: The Complete Reference”, 11th Edition, McGraw Hill Education,
2019.
REFERENCES:
1.Cay S. Horstmann, Gary Cornell, “Core Java Volume – I Fundamentals”, 11th Edition,
Prentice Hall, 2019.
2.Paul Deitel, Harvey Deitel, Java SE 8 for programmers, 3rd Edition, Pearson, 2015.
3.Steven Holzner, Java 2 Black book, Dream tech press, 2011.
4.Timothy Budd, Understanding Object-oriented programming with Java, Third Edition,
Pearson Education, 2008.
5.https://infyspringboard.onwingspan.com/web/en/app/
toc/lex_29959473947367270000_shared/overview
LIST OF EQUIPMENTS:
1.Systems with either Netbeans or Eclipse, JDK 1.7 and above, Linux and MySQL
5. COURSE OUTCOME
PSO1
PSO2
PSO3
PO10
PO11
PO12
PO1
PO2
PO3
PO4
PO5
PO6
PO7
PO8
PO9
COs
CO1 3 3 3 3 2 2
CO2 3 2 2 3 3 2
CO3 3 2 2 3 3 2
CO4 3 2 2 3 3 2
CO5 3 2 2 3 3 2
7. Lecture Plan - Unit I
No. of
S. Period Proposed Actual Pertaining Taxonomy Mode of
Topic
No. s Date Lecture CO Level Delivery
Date
Lambda
1 Chalk &
Expressions 1 CO4 K2
Talk
Lambda
2 1 CO4 Chalk &
Expressions K3
Talk
3
String Handling 1 CO4
K2
Chalk &
Talk
4 Collections: 1 CO4
K2
Chalk &
Talk
The Collection
5 1 CO4 Chalk &
Interfaces K2
Talk
The Collection
6 1 CO4 Chalk &
Classes K2
Talk
7 Iterator 1 CO4
K3
Chalk &
Talk
8 Map 1 CO4
K2
Chalk &
Talk
Regular Expression
9 1 CO4 Chalk &
Processing K2
Talk
8. Activity Based Learning
Learning Method Activity
LAMBDA EXPRESSIONS:
Introducing Lambda Expressions
• Lambda expression
• Functional interface.
A lambda expression is an anonymous (that is, unnamed) method. This method is not
executed on its own. Instead, it is used to implement a method defined by a functional
interface. Thus, a lambda expression results in a form of anonymous class. Lambda
expressions are alsocommonly referred to as closures.
A functional interface is an interface that contains one and only one abstract method.
This method specifies the intended purpose of the interface. A functional interface
typically represents a single action. For example, the standard interface Runnable is a
functional interface because it defines only one method: run( ). Therefore, run( )
defines the action of Runnable.
A lambda expression can be used only in a context in which its target type is specified.
One other thing: a functional interface is sometimes referred to as a SAM type, where
SAM stands for Single Abstract Method.
The lambda expression introduced a new syntax element and operator into the Java
language. The new operator, sometimes referred to as the lambda operator or the
arrow operator, is −>. It divides a lambda expression into two parts. The left side
specifies any parameters required by the lambda expression. On the right side is the
lambda body, which specifies the actions of the lambda expression.
Examples
() ----> 123.45
This lambda expression takes no parameters, thus the parameter list is empty. It
returns the constant value 123.45. Therefore, it is similar to the following method:
Of course, the method defined by a lambda expression does not have a name.
Functional Interfaces
interface MyNumber
{
double getValue();
}
In this case, the method getValue() is implicitly abstract, and it is the only method
defined by MyNumber. Thus, MyNumber is a functional interface,and its function
is defined by getValue().
A lambda expression is not executed on its own. It forms the implementation of the
abstract method defined by the functional interface that specifies its target type.
Because the lambda expression assigned to myNum returns the value 123.45,that is
the value obtained when getValue( ) is called.
In order for a lambda expression to be used in a target type context, the type of the
abstract method and the type of the lambda expression must be compatible. For
example, if the abstract method specifies two int parameters, then the lambda must
specify two int parameters.
import j a v a . u t i l . * ; interface
MyNumber {
double getValue();
}
public class LB1 {
public static void main(String[] args) {
MyNumber MyNum;
MyNum = () -> 123.45;
System.out.println("Fixed Value " + MyNum.getValue()); MyNum
= () -> Math.random() * 100; System.out.println("Random Value
" + MyNum.getValue()); System.out.println("Another Random
Value " +
MyNum.getValue());
}
}
Sample output from the program is shown here:
The next example shows the use of a parameter with a lambda expression:
import java.util.*;
interface NumericTest {
boolean test(int n);
}
if (isEven.test(10)) System.out.println("Even
Number ");
if (!isEven.test(9))
System.out.println("Not Even Number ");
if (isNonNeg.test(1))
System.out.println("Non-negative");
if (!isNonNeg.test(-1))
System.out.println("Negative")
;
}
}
The output from this program is shown here:
Even Number
Not Even Number
Non-negative
Negative
The type of n is not specified. Rather, its type is inferred from the context. In this
case, its type is inferred from the parameter type of test( ) as defined by the
NumericTest interface, which is int. It is also possible to explicitly specify the type
of a parameter in a lambda expression. For example,this is also a valid way to write:
Notice that the program defines two different lambda expressions that are compatible
with the test( ) method ofthe functional interface NumericTest. The first, called
isEven, determines if a value is even. The second, called isNonNeg, checks if a
value is non-negative. In each case, the value of the parameter n is tested. Because
each lambda expression is compatible with test(), each can be executed through a
NumericTest reference.
import j a v a . u t i l . * ;
interface NumericTest2 {
boolean t e s t ( i n t n , i n t d ) ;
}
I s a factor
Not a factor
In this program, the functional interface NumericTest2 defines the test( ) method:
boolean test(int n, int d);
In this version, test( ) specifies two parameters. Thus, for a lambda expression to
be compatible with test( ), the lambda expression must also specify two parameters.
Notice how they are specified:
(n, d) -> (n % d) == 0
Block Lambda Expressions
The body of the lambdas shown in the preceding examples consist of a single
expression. These types of lambda bodies are referred to as expression bodies,and
lambdas that have expression bodies are sometimes called expression lambdas. In
an expression body, the code on the right side of the lambda operator must consist
of a single expression.
Java supports a second type of lambda expression in which the code on the right side
of the lambda operator consists of a block of code that can contain more than one
statement. This type of lambda body is called a block body. Lambdas that have block
bodies are sometimes referred to as block lambdas.
A block lambda expands the types of operations that can be handled within a lambda
expression because it allows the body of the lambda to contain multiple statements.
For example, in a block lambda you can declare variables, use loops, specify if and
switch statements, create nested blocks, and so on. A block lambda is easy to create.
Simply enclose the body within braces as you would any other block of statements.
One key difference is that you must explicitly use a return statement to return a
value. This is necessary because a block lambda body does not represent a single
expression.
Here is an example that uses a block lambda to compute and return the factorial of
an int value:
interface NumericFunc {
i n t func(int n ) ;
}
The f a c t o r i a l i s 6
The f a c t o r i a l i s 120
In the program, notice that the block lambda declares a variable called result, uses
a for loop, and has a return statement.
Another example of a block lambda is shown in the following program. Itreverses the
characters in a string.
interface StringFunc {
String func(String n ) ;
}
public class LB5 {
for ( i = s t r. l e n g t h ( ) - 1 ; i >= 0 ; i - - )
result += s t r. c h a r At ( i ) ;
return r e s u l t ;
};
System.out.println("Lambda reversed i s " +
reverse.func("Lambda"));
System.out.println("Expression reversed i s " +
reverse.func("Expression"));
}
In this example, the functional interface StringFunc declares the func( ) method.
This method takes a parameter of type String and has a return type of String. Thus,
in the reverse lambda expression, the type of str is inferred to be String. Notice
that the charAt( ) method is called on str. This is legal because of the inference
that str is of type String.
To understand the value of generic functional interfaces, two previous examples used
two different functional interfaces, one called NumericFunc and the other called
StringFunc. However, both defined a method called func( ) that took one
parameter and returned a result. In the first case, the type of the parameter and
return type was int. In the second case, the parameter and return type was String.
Thus, the only difference between the two methods was the type of data they
required. Instead of having two functional interfaces whose methods differ only in
their data types, it is possible to declare one generic interface that can be used to
handle both circumstances. The following program shows this approach:
interface someFunc<T> {
T func(T t ) ;
}
for ( i = s t r. l e n g t h ( ) - 1 ; i >= 0 ; i - - )
result += s t r. c h a r At ( i ) ;
return r e s u l t ;
};
System.out.println("Lambda reversed i s " +
reverse.func("Lambda"));
System.out.println("Expression reversed i s " +
reverse.func("Expression"));
someFunc<Integer> f a c t o r i a l = ( n ) -> {
i n t result = 1 ;
for ( i n t i = 1 ; i <= n; i ++)
result = i * r e s u l t ;
return r e s u l t ;
};
System.out.println("The f a c t o r i a l i s " + f a c t o r i a l . f u n c ( 3 ) ) ;
System.out.println("The f a c t o r i a l i s " + f a c t o r i a l . f u n c ( 5 ) ) ;
}
}
Here, T specifies both the return type and the parameter type of func( ). It is
compatible with any lambda expression that takes one parameter and returns a value
of the same type.
The SomeFunc interface is used to provide a reference to two different types of
lambdas. The first uses type String. The second uses type Integer. Thus, the same
functional interface can be used to refer to the reverse lambda and the factorial
lambda. Only the type argument passed to SomeFunc differs.
It is a very powerful use because it gives you a way to pass executable code as an
argument to a method. This greatly enhances the expressive power of Java.
To pass a lambda expression as an argument, the type of the parameter receiving
the lambda expression argument must be of a functional interface type compatible
with the lambda.
interface StringFunction {
String func(String n ) ;
}
int i ;
for ( i = s t r. l e n g t h ( ) - 1 ; i >= 0 ; i - - )
result += s t r. c h a r At ( i ) ;
return r e s u l t ;
};
System.out.println("The string reversed: " +
stringOp(reverse, i n S t r ) ) ;
}
}
In the program, first notice the stringOp( ) method. It has two parameters.
The first is of type StringFunc, which is a functional interface. Thus, this parameter
can receive a reference to any instance of StringFunc, including one created by a
lambda expression. The second argument of stringOp( ) is of type String, and this
is the string operated on.
Next, notice the first call to stringOp( ), shown again here:
Next, the program passes a block lambda to stringOp( ). This lambda removes
spaces from a string. It is shown again here:
outStr=stringOp((str)->{
String result="";
int i;
for(i=0;i<str.length();i++)
if(str.charAt(i) != ' ')
result+=str.charAt(i);
return result;
},inStr);
A block lambda is defined that reverses a string. This lambda is assigned to reverse,
which is a reference to a StringFunc instance. Thus, reverse can be used as an
argument to the first parameter of stringOp( ). The program then calls stringOp(
), passing in reverse and the string on which to operate. Because the instance
obtained by the evaluation of each lambda expression is an implementation of
StringFunc, each can be used as the first parameter to stringOp( ).
interface DoubleNumericArrayFunc {
double func(double[] n) throws EmptyArrayException;
}
A lambda expression can use an instance or static variable defined by its enclosing
class. A lambda expression also has access to this (both explicitly and implicitly),
which refers to the invoking instance of the lambda expression’s enclosing class.
When a lambda expression uses a local variable from its enclosing scope, a special
situation is created that is referred to as a variable capture. 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.
It is important to understand that a local variable of the enclosing scope cannot be
modified by the lambda expression.
interface MyFunc {
i n t func(int n ) ;
}
num is effectively final and can be used inside myLambda but if num were to be
modified, this would cause an error, and the program would not compile.
STRING HANDLING:
✓ String is a group of characters. They are objects of type String.
✓ Once a String object is created it cannot be changed. Strings are Immutable.
✓ To get changeable strings use the class called StringBuffer.
✓ String and StringBuffer classes are declared as final, so there cannot be subclasses
of these classes.
Creating Strings:
There are two ways to create String object:
1. By string literal
2. By new keyword (Using constructors
Example:
String str = "abc"; //Using literal
String str = new String(“abc); //Using new keyword
String Methods:
No. Method Description
public char charAt(int It returns char value for the
1. index) particular index
2. public i n t length() It returns string length
public void getChars(int
Copies characters from this string
3. srcBegin, i n t srcEnd, char
into the destination character array.
d s t [ ] , i n t dstBegin)
Converts this string to a new
4. public char[] toCharArray()
character array
Encodes the string into a sequence
of bytes using the platform's default
5. public byte[] getBytes() charset, storing the result into a
new byte array.
public s t a t i c String
6. format(String format, It returns a formatted string.
O b j e c t . . . args)
public s t a t i c String
It returns formatted string with
7. format(Locale l , String given locale.
format, O b j e c t . . . args)
public String substring(int It returns substring for given begin
8.
beginIndex) index.
public String substring(int It returns substring for given begin
9. index and end index.
beginIndex, i n t endIndex)
It returns true or false after
public boolean
10. matching the sequence of char
contains(CharSequence s )
value.
public s t a t i c String
11. join(CharSequence de l i mi te r , It returns a joined string.
CharSequence... elements)
public s t a t i c String
join(CharSequence de l i mi te r ,
12. Iterable<? extends It returns a joined string.
CharSequence> elements)
public boolean equals(Object It checks the equality of string with
13. the given object.
anObject)
public boolean
Compares this string to the
14. contentEquals(StringBuffe r
specified StringBuffer.
sb)
public boolean
Compares this string to the
15. contentEquals(CharSequenc specified CharSequence.
e cs)
Compares two strings
lexicographically.
The result is a negative integer if
the String object lexicographically
precedes the argument string. The
public i n t compareTo(String
16. result is a positive integer if the
anotherString)
String object lexicographically
follows the argument string. The
result is zero if the strings are
equal.
17. public boolean isEmpty() It checks if string is empty.
public String concat(String
18. str) It concatenates the specified string.
public String replace(char It replaces all occurrences of the
19. oldChar, char newChar) specified char value.
public String
It replaces all occurrences of the
20. replace(CharSequence t a r g e t , specified CharSequence.
CharSequence replacement)
Replaces the first substring of this
public String string that matches the given
21. replaceFirst(String regex, regular expression with the given
String replacement)
replacement.
Replaces each substring of this
public String string that matches the given
22. replaceAll(String regex, regular expression with the given
String replacement)
replacement.
public boolean
It compares another string. It
23. equalsIgnoreCase(String doesn't check case.
anotherString)
public S tri ng[] s p l i t ( S t r i n g It returns a split string matching
24. regex.
regex)
public S tri ng[] s p l i t ( S t r i n g It returns a split string matching
25. regex, i n t l i m i t ) regex and limit.
It returns an interned string.
public native String
26. Returns a canonical representation
intern()
for the string object.
It returns the specified char value
27. public i n t indexOf(int ch)
index.
public i n t indexOf(int ch, It returns the specified char value
28. index starting with given index.
i n t fromIndex)
public i n t indexOf(String It returns the specified substring
29. index.
str)
public i n t indexOf(String It returns the specified substring
30. s t r , i n t fromIndex) index starting with given index.
Returns the index within this string
public i n t lastIndexOf(int
31. of the last occurrence of the
ch)
specified character.
Returns the index within this string
of the last occurrence of the
public i n t lastIndexOf(int specified character, searching
32. ch, i n t fromIndex) backward starting at the specified
index.
Returns the index within this string
public i n t of the last occurrence of the
33. lastIndexOf(String s t r )
specified substring.
Returns the index within this string
public i n t of the last occurrence of the
34. lastIndexOf(String s t r , i n t specified substring, searching
fromIndex) backward starting at the specified
index.
public boolean Tests if the substring of this string
35. startsWith(String p r e f i x , beginning at the specified index
int toffset) starts with the specified prefix.
public boolean Tests if this string starts with the
36. specified prefix.
startsWith(String p r e f i x )
public boolean Tests if this string ends with the
37. specified suffix.
endsWith(String s u f f i x )
38. public String toLowerCase() It returns a string in lowercase.
public String It returns a string in lowercase
39. using specified locale.
toLowerCase(Locale locale)
40. public String toUpperCase() It returns a string in uppercase.
public String It returns a string in uppercase
41. using specified locale.
toUpperCase(Locale locale)
It removes beginning and ending
42. public String t r i m ( )
spaces of this string.
public s t a t i c String It converts given type into string. It
43. valueOf(int i ) is an overloaded method.
public boolean Tests if two string regions are
regionMatches(int t o f f s e t , equal. A substring of the String
44. String other, i n t ooffset, object is compared to a substring of
i n t len) the argument other.
public boolean
regionMatches(boolean Tests if two string regions are equal
45. ignoreCase, i n t t o f f s e t , by ignoring case if ignoreCase is
String other, i n t ooffset, true.
i n t len)
46. public i n t hashCode() Returns a hash code for this string.
Tells whether or not this string
public boolean
47. matches the given regular
matches(String regex)
expression.
Example:
import j a va . u t i l . Ar r a ys ;
COLLECTIONS:
✓ Collection is an interface in the java.util package that is used to define a group, or
collection of objects.
✓ Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
✓ Collections framework provide a set of standard utility classes to manage
collections.
✓ SortedSet defines several methods that make set processing more convenient.
✓ The Methods Declared by SortedSet:
ArrayList( )
ArrayList(Collection<? extends E> c)
ArrayList(int capacity)
✓ The third constructor 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:
/ / Demonstrate ArrayList.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// Create an array list.
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " + al.size());
// Add elements to the array list.
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
// Display the array list.
System.out.println("Contents of al: " + al);
// Remove elements from the array list.
al.remove("F"); al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
Output:
I n i t i a l size of a l : 0
Size of a l a f t e r additions: 7
Contents of a l : [C, A2, A, E, B, D, F]
Size of a l a f t e r deletions: 5
Contents of a l : [C, A2, E, B, D]
class ArrayListToArray {
public static void main(String args[]) {
// Create an array list.
ArrayList<Integer> al = new ArrayList<Integer>();
// Add elements to the array list.
al.add(1);
al.add(2);
al.add(3);
al.add(4);
System.out.println("Contents of al: " + al);
// Get the array.
Integer ia[] = new Integer[al.size()]; ia =
al.toArray(ia);
int sum = 0;
// Sum the array.
for (int i : ia)
sum += i;
System.out.println("Sum is: " + sum);
}
}
Output:
Contents of a l : [ 1 , 2 , 3 , 4 ]
Sumi s : 10
Example:
/ / Demonstrate LinkedList.
import java.util.*;
class LinkedListDemo {
public static void main(String args[]) {
// Create a linked list.
LinkedList<String> ll = new LinkedList<String>();
// Add elements to the linked list.
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
// Remove elements from the linked list.
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: " + ll);
//Remove first and last elements.
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: " +
ll);
//Get and set a value.
String val = ll.get(2); ll.set(2, val
+ " Changed");
System.out.println("ll after change: " + ll);
}
}
Output:
Original contents of ll: [A, A2, F, B, D, E, C, Z] Contents of ll
after deletion: [A, A2, D, E, C, Z] ll after deleting first and
last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]
class HashSetDemo {
public s t a t i c void main(String a rgs []) {
/ / Create a hash s e t .
HashSet<String> hs = new HashSet<String>();
/ / Add elements to the hash s e t .
hs.add("Beta");
hs.add("Alpha");
hs.add("Eta");
hs.add("Gamma");
hs.add("Epsilon");
hs.add("Omega");
System.out.p r i n t ln ( hs) ;
}
}
Output:
[Gamma, Eta, Alpha, Epsilon, Omega, Beta]
Example:
/ / Demonstrate HashSet.
import j a v a . u t i l . * ;
class LinkedHashSetDemo {
public s t a t i c void main(String a rgs []) {
/ / Create a hash s e t .
LinkedHashSet<String> hs = new LinkedHashSet<String>();
/ / Add elements to the hash s e t .
hs.add("Beta");
hs.add("Alpha");
hs.add("Eta");
hs.add("Gamma");
hs.add("Epsilon");
hs.add("Omega");
System.out.p r i n t ln ( hs) ;
}
}
Output:
✓ The first form constructs an empty tree set that will be sorted in ascending order
according to the natural order of its elements.
✓ The second form builds a tree set that contains the elements of c.
✓ The third form constructs an empty tree set that will be sorted according to the
comparator specified by comp.
✓The fourth form builds a tree set that contains the elements of ss.
Example:
/ / Demonstrate TreeSet.
import j a v a . u t i l . * ;
class TreeSetDemo {
public s t a t i c void main(String a rgs []) {
/ / Create a tree s e t .
TreeSet<String> t s = new TreeSet<String>();
/ / Add elements to the tree s e t .
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
System.out.p r i n t ln ( ts ) ;
}
}
Output:
[A, B, C, D, E, F]
✓ The first constructor builds an empty queue. Its starting capacity is 11.
✓ The second constructor builds a queue that has the specified initial capacity.
✓ The third constructor specifies a comparator, and the fourth builds a queue with
the specified capacity and comparator.
✓ The last three constructors create queues that are initialized with the elements of
the collection passed in c.
✓ In all cases, the capacity grows automatically as elements are added.
The ArrayDeque Class:
✓ The ArrayDeque class extends AbstractCollection and implements the Deque
interface.
✓ It adds no methods of its own. ArrayDeque creates a dynamic array and has no
capacity restrictions.
Example:
/ / Demonstrate ArrayDeque.
import j a v a . u t i l . * ;
class ArrayDequeDemo {
public s t a t i c void main(String a rgs []) {
/ / Create an array deque.
ArrayDeque<String> adq = new ArrayDeque<String>();
/ / Use an ArrayDeque l i k e a stack.
adq.push("A");
adq.push("B");
adq.push("D");
adq.push("E");
adq.push("F");
System.out.print("Popping the stack: " ) ;
while (adq.peek() != n u l l )
System.out.print(adq.pop() + " " ) ;
System.out.println();
}
}
Output:
Popping the stack: F E DBA
Using an Iterator:
✓ Iterator is an object that enables you to traverse through a collection.
✓ 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:
✓ Has both next() and previous() method to access the next and previous element
in the List.
The Methods Provided by ListIterator:
Example:
/ / Demonstrate iterators.
import java.util.*;
class IteratorDemo {
public static void main(String args[]) {
// Create an array list.
ArrayList<String> al = new ArrayList<String>();
// Add elements to the array list.
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
// Use iterator to display contents of al.
System.out.print("Original contents of al: ");
Iterator<String> itr = al.iterator();
while (itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// Modify objects being iterated.
ListIterator<String> litr = al.listIterator(); while
(litr.hasNext()) {
String element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: "); itr =
al.iterator();
while (itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// Now, display the list backwards.
System.out.print("Modified list backwards: "); while
(litr.hasPrevious()) {
String element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
Output:
Original contents of a l : CAE BDF Modified
contents of a l : C+A+ E+ B+ D+ F+ Modified l i s t
backwards: F+ D+ B+ E+ A+ C+
✓ for-each construct can also be used for iterating through the Collection
✓ Use Iterator instead of the for-each construct when you need to:
o Remove the current element
▪ The for-each construct hides the iterator, so you cannot call
remove
System.out.println(d2.name); }
class ForEachDemo {
public s t a t i c void main(String a rgs []) {
/ / Create an array l i s t for integers.
ArrayList<Integer> vals = new ArrayList<Integer>();
/ / Add values to the array l i s t .
vals.add(1);
vals.add(2);
vals.add(3);
vals.add(4);
vals.add(5);
/ / Use for loop to display the values.
System.out.print("Contents of vals: "); for (int v
: vals)
System.out.print(v + " ");
System.out.println();
// Now, sum the values by using a for loop. int sum
= 0;
for (int v : vals)
sum += v;
System.out.println("Sum of values: " + sum);
}
}
Output:
Contents of vals: 1 2 3 4 5
Sumof values: 15
Spliterators:
✓ A spliterator cycles through a sequence of elements.
✓ It offers substantially more functionality than does either Iterator or
ListIterator.
✓It provide support for parallel iteration of portions of the sequence.
The Methods Declared by Spliterator:
Example:
class SpliteratorDemo {
public static void main(String args[]) {
// Create an array list for doubles.
ArrayList<Double> vals = new ArrayList<>();
// Add values to the array list.
vals.add(1.0);
vals.add(2.0);
vals.add(3.0);
vals.add(4.0);
vals.add(5.0);
//Use tryAdvance() to display contents of vals.
System.out.print("Contents of vals:\n"); Spliterator<Double>
spltitr = vals.spliterator();
while (spltitr.tryAdvance((n) -> System.out.println(n)))
;
System.out.println();
//Create new list that contains square roots. spltitr =
vals.spliterator();
ArrayList<Double> sqrs = new ArrayList<>();
while (spltitr.tryAdvance((n) -> sqrs.add(Math.sqrt(n))))
;
//Use forEachRemaining() to display contents of sqrs.
System.out.print("Contents of sqrs:\n");
spltitr = sqrs.spliterator(); spltitr.forEachRemaining((n) ->
System.out.println(n)); System.out.println();
}
}
Output:
Contents of vals:
1.0
2.0
3.0
4.0
5.0
Contents of sqrs:
1.0
1.4142135623730951
1.7320508075688772
2.0
2.23606797749979
MAPS:
✓ 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 maps can 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:
Example:
import java.util.*;
class TreeMapDemo {
public static void main(String args[]) {
// Create a tree map.
TreeMap<String, Double> tm = new TreeMap<String, Double>();
// Put elements to the map.
tm.put("John Doe", new Double(3434.34));
tm.put("Tom Smith", new Double(123.22));
tm.put("Jane Baker", new Double(1378.00));
tm.put("Tod Hall", new Double(99.22));
tm.put("Ralph Smith", new Double(-19.08));
// Get a set of the entries.
Set<Map.Entry<String, Double>> set = tm.entrySet();
// Display the elements.
for (Map.Entry<String, Double> me : set) {
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account. double balance
= tm.get("John Doe"); tm.put("John Doe",
balance + 1000);
System.out.println("John Doe's new balance: " + tm.get("John
Doe"));
}
}
Output:
Jane Baker: 1378.0
John Doe: 3434.34
Ralph Smith: -19.08
Tod H a l l : 99.22
TomSmith: 123.22
✓ You can also create a LinkedHashMap that returns its elements in the order in
which they were last accessed.
There are two classes that support regular expression processing: Pattern and
Matcher. These classes work together. Use Pattern to define a regular expression.
Match the pattern against another sequence using Matcher.
Pattern
The Pattern class defines no constructors. Instead, a pattern is created bycalling the
compile( ) factory method. One of its forms is shown here:
static Pattern compile(String pattern)
Here, pattern is the regular expression that you want to use. The compile( ) method
transforms the string in pattern into a pattern that can be used for pattern matching
by the Matcher class. It returns a Pattern object that containsthe pattern.
Once you have created a Pattern object, you will use it to create a Matcher.This is
done by calling the matcher( ) method defined by Pattern. It is shownhere:
Matcher matcher(CharSequence str)
Here str is the character sequence that the pattern will be matched against. Thisis
called the input sequence. CharSequence is an interface that defines a read-only
set of characters. It is implemented by the String class, among others.
Thus, you can pass a string to matcher().
Matcher
The Matcher class has no constructors. Instead, you create a Matcher by calling
the matcher() factory method defined by Pattern, as just explained. Once you have
created a Matcher, you will use its methods to perform variouspattern matching
operations. Several are described here.
The simplest pattern matching method is matches( ), which determineswhether the
character sequence matches the pattern. It is shown here:
boolean matches( )
It returns true if the sequence and the pattern match, and false otherwise.
Understand that the entire sequence must match the pattern, not just a subsequence
of it.
To determine if a subsequence of the input sequence matches the pattern,use find(
). One version is shown here:
boolean find( )
It returns true if there is a matching subsequence and false otherwise. This method
can be called repeatedly, allowing it to find all matching subsequences.Each call to
find( ) begins where the previous one left off.
You can obtain a string containing the last matching sequence by calling
group( ). One of its forms is shown here:String group( )
The matching string is returned. If no match exists, then an
IllegalStateException is thrown.
You can obtain the index within the input sequence of the current match bycalling
start( ). The index one past the end of the current match is obtained bycalling end(
). The forms used in this chapter are shown here:
int start( )
int end( )
Both throw IllegalStateException if no match exists.
You can replace all occurrences of a matching sequence with anothersequence by
calling replaceAll( ). One version is shown here:
String replaceAll(String newStr)
Here, newStr specifies the new character sequence that will replace the onesthat match
the pattern. The updated input sequence is returned as a string.
For example, the pattern "x+" will match "x", "xx", and "xxx", among others.As you
will see, variations are supported that affect how matching is performed.
One other point: In general, if you specify an invalid expression, a
PatternSyntaxException will be thrown.
import java.util.regex.*;
The program begins by creating the patternthat contains the sequence "Java". Next,
a Matcher is created for that pattern that has the input sequence "Java". Then, the
matches( ) method is called to determine if the input sequence matches the
pattern. Because the sequence andthe pattern are the same, matches( ) returns
true. Next, a new Matcher is created with the input sequence "Java SE" and
matches( ) is called again. In this case, the pattern and the input sequence differ,
and no match is found. Remember, the matches( ) function returns true only
when the input sequenceprecisely matches the pattern.
You can use find( ) to determine if the input sequence contains a subsequence that
matches the pattern.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegEx2 {
}
}
The output is
Looking for Java in Java SE.
Subsequence found
import java.util.regex.Matcher;
import java.util.regex.Pattern;
The program uses the start( ) method to obtain the index of each match.
The real benefit of regular expression processing is not seen until wildcards and
quantifiers are used. To begin, consider the following example that uses the +
quantifier to match any arbitrarily long sequence of Ws:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Match: W
Match: WW Match:
WWW
The regular expression pattern "W+" matches anyarbitrarily long sequence of Ws.
The next program uses a wildcard to create a pattern that will match any sequence
that begins with e and ends with d. To do this, it uses the dot wildcardcharacter
along with the + quantifier.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
The output is
Match: extend cup end
Only one match is found, and it is the longest sequence that begins with e andends
with d. You might have expected two matches: "extend" and "end". Thereason that
the longer sequence is found is that the pattern "e.+d" matches thelongest sequence
that fits the pattern. This is called greedy behavior.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Match: extend
Match: end
Sometimes you will want to match any sequence that contains one or more
characters, in any order, that are part of a set of characters. For example, to
match whole words, you want to match any sequence of the letters of the
alphabet. One of the easiest ways to do this is to use a character class, which
defines a set of characters.
For example, to match the lowercase characters a through z, use [a-z].
import java.util.regex.Matcher;
import java.util.regex.Pattern;
The output is
Match: this
Match: is Match:
a Match: test
Using replaceAll( )
The replaceAll( ) method supplied by Matcher lets you perform powerful search
and replace operations that use regular expressions. For example, the following
program replaces all occurrences of sequences that begin with "Jon"with "Eric":
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Because the regular expression "Jon.*? " matches any string that begins withJon
followed by zero or more characters, ending in a space, it can be used to match
and replace both Jon and Jonathan with the name Eric.
Using split()
You can reduce an input sequence into its individual tokens by using the split()
method defined by Pattern. One form of the split() method is shown here:String[ ]
split(CharSequence str). It processes the input sequence passed in str, reducing it
into tokens based onthe delimiters specified by the pattern.
For example, the following program finds tokens that are separated by spaces,
commas, periods, and exclamation points:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
If you only need to perform a one-time pattern match, you can use the matches()
method defined by Pattern. It is shown here:
If the invoking string matches the regular expression in pattern, then matches()
returns true. Otherwise, it returns false.
import j a v a . u t i l . r e g e x . * ;
S t r i n g date="1/11/*2020";
S t r i n g date1="1/11/2020";
Matcher matcher = p a t t e rn. m at ch er( d at e);
System.out.p rin tln (date +" : "+ matcher.matches());
Matcher matcher1 = pattern.matcher(date1);
System.out.println(date1 +" : "+ matcher1.matches());
1/11/*2020 : false
1/11/2020 : true
Program for Email Validation:
import java.util.regex.*;
user@domaincom : true
user*domaincom : false
10. ASSIGNMENT
Employee Register
You need to maintain the details of all employees of an Organization.
The following details of the employee needs to be maintained
First Name
Last Name
Mobile Number
Email
Address
There is no higher limit to store the number of employee in our application. Get the
number of employees first before getting all the employee details.
Collect all employee details and store them in an appropriate collection type, so that
when the collection is printed, it prints the employee details sorted by their first name.
Use Generics.
Note:
In case of Java, Use Java Format Specifier:
System.out.format("%-15s %-15s %-15s %-30s %-
15s\n","Firstname","Lastname","Mobile","Email","Address");
Sample Output:
Enter the Number of Employees
2
Enter Employee 1 Details:
Enter the Firstname
Janani
Enter the Lastname
Velmurugan
Enter the Mobile
7890123
Enter the Email
janani.velmurugan@gmail.com
Chennai
Employee List:
The body of the lambdas shown in the preceding examples consist of a single
expression. These types of lambda bodies are referred to as expression bodies, and
lambdas that have expression bodies are sometimes called expression lambdas.
Java supports a second type of lambda expression in which the code on the right side
of the lambda operator consists of a block of code that can contain more than one
statement. This type of lambda body is called a block body. Lambdas that have block
bodies are sometimes referred to as block lambdas.
Example:
Expression Lambda
()->123.45
Block Lambda
(n) -> {
int result = 1;
for (int i=1;i<=n;i++)
result=i*result;
return result;
};
StringBuffer and StringBuilder-Both hold strings that can be modified after they
are created
String(char chars[ ])
String(char chars[ ], int startIndex, int numChars)
String(String strObj)
String str="Hello";
StringBuffer sb=new StringBuffer(str);
StringBuffer revsb=sb.reverse();
if(str.equals(revsb))
System.out.println("Palindrome");
else
System.out.println("Not Palindrome");
Iterator interface provides the facility of iterating the elements in a forward direction
only.
1.Obtain an iterator to the start of the collection by calling the collection’s iterator( )
method.
2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as
hasNext( ) returns true.
✓ The ArrayList class extends AbstractList and implements the List interface.
An Array can be converted into an ArrayList by making use of the asList() method
provided by the Array class. It is a static method that accepts List objects as a
parameter. The toArray() is used to convert ArrayList into an Array.
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework.
14.What is the HashSet class in Java and how does it store elements?
(K1,CO4)
16. What are the advantages of the Collection Framework in Java? (K1,CO4)
The java.util package contains one of Java’s most powerful subsystems: the
Collections Framework.
17. List down the different Collection views provided by the Map interface in
the Java Collection framework? (K1,CO4)
• iterator()
• listiterator()
21. What are the basic interfaces of Java Collections Framework? (K1,CO4)
• List
• Set
• Queue
There are two classes that support regular expression processing: Pattern and
Matcher. These classes work together. Use Pattern to define a regular expression.
Match the pattern against another sequence using Matcher.
12. PART - B
1. Write a program to read a line of text and reverse each word.
2. Explain the various methods available in String with suitable example.
3. Explain the difference between String, StringBuffer and StringBuilder
4. Write a Java program to remove all non-alphanumeric characters from a string using
regular expression.
5. Explain in detail how a Lambda Expression is passed as an argument with suitable
example.
6. Explain in detail how generic programming is applied in Lambda Expression with an
example.
20. Explain the different interfaces and views of Map with all its methods and write a
program to iterate through the Map
1. https://www.hackerrank.com/skills-verification/java_basic
2. https://www.sololearn.com/Course/Java/
3. https://www.coursera.org/specializations/object-oriented-programming
4. https://www.udemy.com/course/java-the-complete-java-developer-course/
[Paid]
5. https://nptel.ac.in/courses/106/105/106105191/ [Paid]
6. https://education.oracle.com/java-se-8-fundamentals/courP_3348 [Paid]
14. REAL TIME APPLICATIONS
1. Regular Expression:
a. Extracting emails from a Text Document
b. Web Scraping (Data Collection)
c. Working with Date-Time features
d. Using Regex for Text Pre-processing (NLP)
2. Collection:
a. Queues in Ticketing systems.
b. TreeMap in Coin changer Application.
c. Hash Search.
d. TreeSet for Binary Search.
15. CONTENT BEYOND SYLLABUS
DICTIONARY
Dictionary is an abstract class that represents a key/value storage repository and operates
much like Map. Given a key and value, you can store the value in a Dictionary object.
Once the value is stored, you can retrieve it by using its key.
Here, K specifies the type of keys, and V specifies the type of values.
1 Enumeration elements( )
Returns an enumeration of the values contained in the dictionary.
3 boolean isEmpty( )
Returns true if the dictionary is empty, and returns false if it contains at
least one key.
4 Enumeration keys( )
Returns an enumeration of the keys contained in the dictionary.
7 int size( )
Returns the number of entries in the dictionary.
To add a key and a value, use the put() method. Use get() to retrieve the value of a given
key. The keys and values can each be returned as an Enumeration by the keys() and
elements ) methods, respectively. The size() method returns the number of key/value
pairs stored in a dictionary, and isEmpty() returns true when the dictionary is empty. You
can use the remove() method to delete a key/value pair.
16. ASSESSMENT SCHEDULE
TEXTBOOK:
1. Herbert Schildt, Java:The complete reference, 11th Edition,McGraw Hill
Education, 2019.
REFERENCES:
5. https://www.tutorialspoint.com/java/index.htm
6. https://www.javatpoint.com/java-tutorial
7. https://www.w3schools.com/java/
8. https://www.geeksforgeeks.org/java-tutorial/
9. https://docs.oracle.com/javase/tutorial/
18. MINI PROJECT
1. A title;
Add instance variables for each of these attributes to the Video class.
3. receiving a rating.
The VideoStore class will contain at least an instance variable that references an array of
videos (say of length 10). The VideoStore will contain the following methods:
1. Add 3 videos: "The Matrix", "Godfather II", "Star Wars Episode IV: A New Hope".
List the inventory after "Godfather II" has been rented out.
Thank you
Disclaimer:
This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.