0% found this document useful (0 votes)
5 views100 pages

22CS202 Java Unit 4

This document outlines the course structure for 'Java Programming' (22CS202) at RMK Group of Educational Institutions, detailing objectives, prerequisites, syllabus, course outcomes, and assessment methods. It covers key topics such as object-oriented programming, inheritance, exception handling, multithreading, JDBC, and includes practical exercises and projects. The document also emphasizes the importance of confidentiality and intended audience for the information provided.

Uploaded by

chan22006.cd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
5 views100 pages

22CS202 Java Unit 4

This document outlines the course structure for 'Java Programming' (22CS202) at RMK Group of Educational Institutions, detailing objectives, prerequisites, syllabus, course outcomes, and assessment methods. It covers key topics such as object-oriented programming, inheritance, exception handling, multithreading, JDBC, and includes practical exercises and projects. The document also emphasizes the importance of confidentiality and intended audience for the information provided.

Uploaded by

chan22006.cd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 100

Please read this disclaimer before

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

Department : Computer Science & Engineering


Batch / Year : 2022 – 2026 / I
Created by : Subject Handling Faculties
Date : 30.04.2023

4
1. CONTENTS

S. No. Contents Page No

1 Contents 5

2 Course Objectives 6

3 Pre Requisites 7

4 Syllabus 8

5 Course outcomes 9

6 CO- PO/PSO Mapping 10

7 Lecture Plan 11

8 Activity based learning 12

9 Lecture Notes 13

10 Assignments 78

11 Part A Questions & Answers 80

12 Part B Questions 86

13 Supportive online Certification courses 88

14 Real time Applications 89

15 Contents beyond the Syllabus 90

16 Assessment Schedule 92
Prescribed Text Books & Reference
17 Books 93

18 Mini Project Suggestions 94


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
22CS202
Java Programming
22CS101
Problem Solving
3. PRE Using C++
REQUISITES

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

UNIT I JAVA FUNDAMENTALS 15

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.

UNIT III MULTITHREADING, I/O AND GENERIC PROGRAMMING 15

Multithreaded Programming: Creating a Thread, Thread Priorities, Synchronization,


Interthread Communication – I/O: I/O Basics, Reading Console Input, Writing Console
Output, Reading and Writing Files – Generics: Introduction, Generic class, Bounded Types,
Generic Methods, Generic Interfaces, Generic Restrictions.

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

Lambda Expressions - String Handling – Collections: The Collection Interfaces, The


Collection Classes – Iterator – Map - Regular Expression Processing.

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.

UNIT V JDBC CONNECTIVITY 15

JDBC – DataSource, Configurations, Connection, Connection Pools, Driver Types, ResultSet,


Prepared Statement, Named Parameter, Embedded SQL (Insert, Update, Delete, Join, union
etc), ResultSet Navigation, Connection Close and Clean up.

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

At the end of this course, the students will be able to:


CO1: Explain the object oriented programming concepts and
fundamentals of Java
CO2: Develop Java programs with the packages, inheritance,
interfaces and exceptions
CO3: Build Java applications with I/O streams, threads and
generics classes

CO4: Apply strings and collections in applications


CO5: Develop interactive Java applications using swings and event
handling mechanism
5. Course 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 and generics
programming.
CO4: Apply strings and collections in developing applications.
CO5: Implement the concepts of JDBC.
6. CO - PO Mapping
POs and PSOs

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

Tutorial Sessions available in


Learn by Solving Problems
iamneo Portal

Quiz / MCQ Using RMK Nextgen


Learn by Questioning
App and iamneo Portal

Practice available in iamneo


Learn by doing Hands-on
Portal
9. LECTURE NOTES

LAMBDA EXPRESSIONS:
Introducing Lambda Expressions

Key to understanding Java’s implementation of lambda expressions are two constructs.

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

Lambda Expression Fundamentals

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.

Java defines two types of lambda bodies.


• A single expression
• A block of code.

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:

double myMeth() { return 123.45; }

Of course, the method defined by a lambda expression does not have a name.

() -> Math.random() * 100

This lambda expression obtains a pseudo-random value from Math.random( ),


multiplies it by 100, and returns the result. It also does not require a parameter.

When a lambda expression requires a parameter, it is specified in the parameter list


on the left side of the lambda operator. Here is a simple example:

(n) -> (n % 2)==0

This lambda expression returns true if the value of parameter n is even.

Functional Interfaces

A functional interface is an interface that specifies only one abstract method.

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.

An example shows how a lambda expression can be used in an assignment context.


First, a reference to the functional interface MyNumber is declared:

// Create a reference to a MyNumber instance.


MyNumber myNum;

Next, a lambda expression is assigned to that interface reference:

// Use a lambda in an assignment context.


myNum = () -> 123.45;

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 declared by the functional
interface. When that method is called through the target, the lambda expression is
executed.
In the preceding example, the lambda expression becomes the implementation for
the getValue() method. As a result, the following displays the value 123.45

// Call getValue(), which is implemented by the previously assigned lambda expression.


System.out.println(myNum.getValue());

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.

Some Lambda Expression Examples

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:

Fixed Value 123.45


Random Value 78.4020074321781
Another Random Value 15.761239017115914

The next example shows the use of a parameter with a lambda expression:
import java.util.*;

interface NumericTest {
boolean test(int n);
}

public class LB2 {


public static void main(String[] args) { NumericTest
isEven = (n) -> (n % 2) == 0;

if (isEven.test(10)) System.out.println("Even
Number ");

if (!isEven.test(9))
System.out.println("Not Even Number ");

NumericTest isNonNeg = (n) -> n >= 0;

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

In the Lambda expression,


(n) -> (n % 2)==0

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:

(int n) -> (n % 2)==0

Here, n is explicitly specified as int.

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

public class LB3 {

public s t a t i c void main(String[] args) {


NumericTest2 isFactor = ( n , d) -> (n % d) == 0 ;
i f (i s Fa c tor. te s t(1 0 , 2 ) )
System.out.println("Is a f a c t o r " ) ;
i f ( !i s F a c t o r. t e s t ( 1 0 , 3 ) )
System.out.println("Not a f a c t o r " ) ;
}
}

The output is shown here:

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

public class LB4 {

public s t a t i c void main(String[] args) {


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

The output is shown here:

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 {

public s t a t i c void main(String[] args) {


StringFunc reverse = ( s t r ) -> {
String result = " " ;
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("Lambda reversed i s " +
reverse.func("Lambda"));
System.out.println("Expression reversed i s " +
reverse.func("Expression"));
}

The output is shown here:

Lambda reversed i s adbmaL


Expression reversed i s noisserpxE

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.

Generic Functional Interfaces

A lambda expression, itself, cannot specify type parameters. Thus, a lambda


expression cannot be generic. But the functional interface associated with a lambda
expression can be generic.

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

public class LB6 {

public s t a t i c void main(String[] args) {


someFunc<String> reverse = ( s t r ) -> {
String result = " " ;
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("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 ) ) ;
}
}

The output is shown here:

Lambda reversed i s adbmaL


Expression reversed i s noisserpxE
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, the generic functional interface SomeFunc is declared asshown


here:

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.

Passing Lambda Expressions as Arguments

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

public class LB7 {


s t a t i c String stringOp(StringFunction s f , String s ) {
return s f . f u n c ( s ) ;
}

public s t a t i c void main(String[] args) {


String inStr = "Lambdas add power to Java";
String outStr;
System.out.println("Here i s input s tri ng: " + i n S t r ) ;
outStr = stringOp((str) -> str.toUpperCase(), i n S t r ) ;
System.out.println("The string i n uppercase: " + outS tr );
outStr = stringOp((str) -> {
String result = " " ;
int i ;

for ( i = 0 ; i < s t r. l e n g t h ( ) ; i ++)


i f ( s t r. c h a r At ( i ) != ' ' )
result += s t r. c h a r At ( i ) ;
return r e s u l t ;
} , inStr);
System.out.println("The string with spaces removed: " +
outStr);

StringFunction reverse = ( s t r ) -> {

String result = " " ;

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

The output is shown here:

Here i s input s tri ng: Lambdas add power to Java The


string i n uppercase: LAMBDASADDPOWERTO JAVA
The string with spaces removed: LambdasaddpowertoJava
The string reversed: avaJ ot rewop dda sadbmaL

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:

outStr = stringOp((str) -> str.toUpperCase(), inStr);

Here, a simple expression lambda is passed as an argument. When this occurs, an


instance of the functional interface StringFunc is created and a reference to that
object is passed to the first parameter of stringOp( ). Thus, the lambda code,
embedded in a class instance, is passed to the method. The target type context is
determined by the type of parameter.

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

Lambda Expressions and Exceptions

A lambda expression can throw an exception. However, it if throws a checked


exception, then that exception must be compatible with the exception(s) listed in the
throws clause of the abstract method in the functional interface. Here isan example
that illustrates this fact. It computes the average of an array of double values. If a
zero-length array is passed, however, it throws the custom exception
EmptyArrayException. As the example shows, this exception is listed in the
throws clause of func( ) declared inside the DoubleNumericArrayFunc functional
interface.

interface DoubleNumericArrayFunc {
double func(double[] n) throws EmptyArrayException;
}

class EmptyArrayException extends Exception {


EmptyArrayException() {
super("Array Empty");
}
}

public class LB8 {

public s t a t i c void main(String[] args) throws EmptyArrayException


{
double[] values = { 1 . 0 , 2 . 0 , 3 . 0 , 4.0 } ;
DoubleNumericArrayFunc average = ( n ) -> {
double sum= 0 ;
i f (n.length == 0 )
throw new EmptyArrayException();
for ( i n t i = 0 ; i < n.length; i ++)
sum+= n [ i ] ;
return sum/ n.length;
};
System.out.println("The average i s " +
average.func(values));
System.out.println("The average i s " + average.func(new
double[0]));
}
}

The output is shown here:

The average i s 2.5


Exception i n thread "main" EmptyArrayException: Array Empty
The first call to average.func( ) returns the value 2.5. The second call, which passes
a zero-length array, causes an EmptyArrayException to be thrown. Remember, the
inclusion of the throws clause in func( ) is necessary. Without it, the program will
not compile because the lambda expression will nolonger be compatible with
func().

Lambda Expressions and Variable Capture

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

public class LB9 {

public s t a t i c void main(String[] args) {


i n t num= 10;
MyFunc myLambda = ( n ) -> {
i n t v = num+ n;
/ / num++; / / I l l e g a l to modify num
return v;

/ / num=10; / / I t w i l l cause an error because numi s


f i n a l can't modify
};
}
}

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

The String Constructors:

public S tri ng()


public String(String o r i g i n a l )
public String(char va l ue [])
public String(char va l u e [ ] , i n t o f f s e t , i n t count)
public String(byte[] bytes)
public String(byte byte s [] , i n t o f f s e t , i n t length)
public String(StringBuffer buffer)
public String(StringBuilder builder)
public S t r i n g ( i n t [ ] codePoints, i n t o f f s e t , i n t count)

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 ;

public class StringDemo {

public s t a t i c void main(String[] args) {


String str1="Java Programming";
String str2="Welcome";
System.out.println("Length: " + s t r 1 . l e n g t h ( ) ) ;
System.out.println(str1.concat(" Class"));
System.out.println("Character a t index 1 i s :
"+str1.charAt(1));
char array[]=new char[5];
str1.getChars(0, 5 , array, 0 ) ;
System.out.print("Character Array:
"+Arrays.toString(array));
System.out.println(str1.substring(5));
System.out.println("Does the string contains
'Java':"+str1.contains("Java"));
S ys te m .out. pri ntl n( s tr 1 . j oi n ("- ", s t r 1 , s t r 2 ) ) ;
System.out.println("Are the strings equal:
"+str1.equals(str2));
System.out.println("Is the string empty: "+str1.isEmpty());
System.out.println("Replace ' e ' with ' E ' :
"+str2.replace('e', ' E ' ) ) ;
String s p l i t t e d S t r i n g [ ] = s t r 1 . s p l i t ( " a " ) ;
System.out.println("Splitted String:
"+Arrays.toString(splittedString ));
System.out.println("Index of ' a ' : "+s tr1 . i nde x O f (' a ' ) );
System.out.println("Uppercase: "+str1.toUpperCase());
}

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.

THE COLLECTION INTERFACES:

The Collections Framework defines several core interfaces.


Hierarchy of Collection Framework:

The Collection 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.
Collection is a generic interface that has this declaration:
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 List Interface:
✓ List interface extends from Collection interface
✓ It stores elements in a sequential manner
✓ Elements in the list can be accessed or inserted based on their position
✓ Starts with zero based index
✓ Can contain duplicate elements
✓ An Iterator can be used to access the elements of the List
The Methods Declared by List Interface:
The Set Interface:
✓ Set interface extends from Collection interface
✓ Set is an unordered collection
✓ It doesn’t allow duplicates
✓ If you add duplicates, it will replace the existing one
✓ It allows you to add only a single null value
✓ An iterator can be used to traverse through the list
✓ List interface has one legacy class called Vector, but Set doesn’t have any legacy
class

✓ Implementation classes for Set are TreeSet, HashSet and LinkedHashSet


The SortedSet Interface:
✓ The SortedSet interface extends Set and declares the behavior of a set sorted in
ascending order.

✓ SortedSet defines several methods that make set processing more convenient.
✓ The Methods Declared by SortedSet:

The NavigableSet Interface:


✓ The NavigableSet interface extends SortedSet and declares the behavior of a
collection that supports the retrieval of elements based on the closest match to a
given value or values.

✓ The Methods Declared by NavigableSet:


The Queue Interface:
The Queue interface extends Collection and declares the behavior of a queue, which
is often a first-in, first-out list.
The methods declared by Queue are:
The Deque Interface:
✓ The Deque interface extends Queue and declares the behavior of a double-
ended queue.
✓ Double-ended queues can function as standard, first-in, first-out queues or as
last-in, firstout stacks.
✓ In addition to the methods that it inherits from Queue, Deque adds the
following methods.
THE COLLECTION CLASSES:
Following core collection classes:

The ArrayList Class:


✓ The ArrayList class extends AbstractList and implements the List interface.
✓ ArrayList supports dynamic arrays that can grow as needed.
✓ Standard arrays are of fixed size. After arrays are created they cannot grow or
shrink.

✓ It provides more powerful insertion and search mechanisms than arrays.


✓ Gives faster Iteration and fast random access.
✓ Ordered Collection (by index), but not Sorted.
ArrayList has the constructors shown here:

ArrayList( )
ArrayList(Collection<? extends E> c)
ArrayList(int capacity)

✓ The first constructor builds an empty array list.


✓ The second constructor builds an array list that is initialized with the elements of
the collection c.

✓ 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]

Obtaining an Array from an ArrayList:


✓ To convert a collection into an array, use toArray( ) method.
✓ There are two versions of toArray( ).
object[ ] toArray( )
<T> T[ ] toArray(T array[ ])
The first returns an array of Object. The second returns an array of elements that have
the same type as T.
Example:

// Convert an ArrayList into an array.


import java.util.*;

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

The LinkedList Class:


✓ The LinkedList class extends AbstractSequentialList and implements the List,
Deque, and Queue interfaces.

✓ It provides a linked-list data structure.


LinkedList has the two constructors shown here:
LinkedList( )
LinkedList(Collection<? extends E> c)
✓ The first constructor builds an empty linked list.
✓ The second constructor builds a linked list that is initialized with the elements of
the collection c.

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]

The HashSet Class:


HashSet extends AbstractSet and implements the Set interface. It creates a collection
that uses a hash table for storage.

The following constructors are defined:


HashSet( )
HashSet(Collection<? extends E> c)
HashSet(int capacity)

HashSet(int capacity, float fillRatio)


✓ The first form constructs a default hash set.
✓ The second form initializes the hash set by using the elements of c.
✓ The third form initializes the capacity of the hash set to capacity. (The default
capacity is 16.)
✓ The fourth form initializes both the capacity and the fill ratio (also called load
capacity) of the hash set from its arguments. The fill ratio must be between 0.0
and 1.0, and it determines how full the hash set can be before it is resized upward.
Example:
/ / Demonstrate HashSet.
import j a v a . u t i l . * ;

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]

The LinkedHashSet Class:


✓ The LinkedHashSet class extends HashSet and adds no members of its own.
✓ LinkedHashSet maintains a linked list of the entries in the set, in the order in
which they were inserted.

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:

[Beta, Alpha, Eta, Gamma, Epsilon, Omega]

The TreeSet Class:


✓ TreeSet extends AbstractSet and implements the NavigableSet interface.
✓ It creates a collection that uses a tree for storage.
✓ Objects are stored in sorted, ascending order.
✓ Access and retrieval times are quite fast
TreeSet has the following constructors:
TreeSet( )
TreeSet(Collection<? extends E> c)
TreeSet(Comparator<? super E> comp)
TreeSet(SortedSet<E> ss)

✓ 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 PriorityQueue Class:


✓ PriorityQueue extends AbstractQueue and implements the Queue interface.
✓ It creates a queue that is prioritized based on the queue’s comparator.
PriorityQueue defines the six constructors shown here:
PriorityQueue( )
PriorityQueue(int capacity)
PriorityQueue(Comparator<? super E> comp) (Added by JDK 8.)
PriorityQueue(int capacity, Comparator<? super E> comp)
PriorityQueue(Collection<? extends E> c)
PriorityQueue(PriorityQueue<? extends E> c)
PriorityQueue(SortedSet<? extends E> c)

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

ArrayDeque defines the following constructors:


ArrayDeque( )
ArrayDeque(int size)

ArrayDeque(Collection<? extends E> c)


✓ The first constructor builds an empty deque. Its starting capacity is 16.
✓ The second constructor builds a deque that has the specified initial capacity.
✓ The third constructor creates a deque that is initialized with the elements of the
collection passed in c.
✓ In all cases, the capacity grows as needed to handle the elements added to the
deque.

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

ACCESSING A COLLECTION VIA AN ITERATOR:


✓ Iterator enables you to cycle through a collection, obtaining or removing
elements.
✓ ListIterator extends Iterator to allow bidirectional traversal of a list, and the
modification of elements.

The Methods Declared by Iterator:

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:

o Obtain an iterator to the start of the collection by calling the collection’s


iterator( ) method.
o Set up a loop that makes a call to hasNext( ). Have the loop iterate as
long as hasNext( ) returns true.
o Within the loop, obtain each element by calling next( ).
ListIterator:

✓ Used for obtaining a iterator for collections that implement List


✓ ListIterator gives us the ability to access the collection in either forward or
backward direction

✓ 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+

Advantage of Iterator over for-each method

✓ 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

o Iterate over multiple collections in parallel.


for(Object o : oa){
Fruit d2 = (Fruit)o;

System.out.println(d2.name); }

The For-Each Alternative to Iterators


/ / Use the for-each for loop to cycle through a c ol l e c ti on.
import j a v a . u t i l . * ;

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:

/ / A simple Spliterator demonstration. import


java.util.*;

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:

The Map Interface:


✓ The Map interface maps unique keys to values.
✓ A key is an object that you use to retrieve a value at a later date.
✓ Given a key and a value, you can store the value in a Map object.
✓ After the value is stored, you can retrieve it by using its key.
The Methods Declared by Map:
The SortedMap Interface:
The SortedMap interface extends Map. It ensures that the entries are maintained in
ascending order based on the keys.

The Methods Declared by SortedMap:


The NavigableMap Interface:
The NavigableMap interface extends SortedMap and declares the behavior of a map
that supports the retrieval of entries based on the closest match to a given key or keys.
The Methods Declared by NavigableMap:
The Map.Entry Interface:
The Map.Entry interface enables you to work with a map entry. Recall that the
entrySet( ) method declared by the Map interface returns a Set containing the map
entries. Each of these set elements is a Map.Entry object.

The Non-Static Methods Declared by Map.Entry:


THE MAP CLASSES:

AbstractMap is a superclass for all concrete map implementations.


The HashMap Class:
The HashMap class extends AbstractMap and implements the Map interface. It uses
a hash table to store the map. This allows the execution time of get( ) and put( ) to
remain constant even for large sets.

The following constructors are defined:


HashMap( )
HashMap(Map<? extends K, ? extends V> m)
HashMap(int capacity)

HashMap(int capacity, float fillRatio)


Example:
import j a v a . u t i l . * ;
class HashMapDemo {
public static void main(String args[]) {
// Create a hash map.
HashMap<String, Double> hm = new HashMap<String, Double>();
// Put elements to the map
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Tod Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));
// Get a set of the entries.
Set<Map.Entry<String, Double>> set = hm.entrySet();
// Display the set.
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 = hm.get("John Doe");
hm.put("John Doe", balance + 1000);
System.out.println("John Doe's new balance: " + hm.get("John
Doe"));
}
}
Output:
Tod H a l l : 99.22
John Doe: 3434.34
Ralph Smith: -19.08
TomSmith: 123.22
Jane Baker: 1378.0

John Doe's new balance: 4434.34

The TreeMap Class:


The TreeMap class extends AbstractMap and implements the NavigableMap
interface. It creates maps stored in a tree structure. A TreeMap provides an efficient
means of storing key/value pairs in sorted order and allows rapid retrieval.
The following TreeMap constructors are defined:
TreeMap( )
TreeMap(Comparator<? super K> comp)
TreeMap(Map<? extends K, ? extends V> m)
TreeMap(SortedMap<K, ? extends V> sm)

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

John Doe's new balance: 4434.34

The LinkedHashMap Class:


✓ LinkedHashMap extends HashMap.
✓ It maintains a linked list of the entries in the map, in the order in which they were
inserted.
✓ This allows insertion-order iteration over the map. That is, when iterating through
a collection-view of a LinkedHashMap, the elements will be returned in the order
in which they were inserted.

✓ You can also create a LinkedHashMap that returns its elements in the order in
which they were last accessed.

LinkedHashMap defines the following constructors:


LinkedHashMap( )
LinkedHashMap(Map<? extends K, ? extends V> m)
LinkedHashMap(int capacity)
LinkedHashMap(int capacity, float fillRatio)
LinkedHashMap(int capacity, float fillRatio, boolean 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.
REGULAR EXPRESSIONS PROCESSING:

The regular expression package, java.util.regex lets you perform sophisticated


pattern matching operations. A regular expression is a string of characters that
describes a character sequence. This general description, called a pattern, can then
be used to find matches in other character sequences. Regular expressions can
specify wildcardcharacters, sets of characters, and various quantifiers.

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.

Regular Expression Syntax


A regular expression is comprised of normal characters, characterclasses (sets of
characters), wildcard characters, and quantifiers. A normal character is matched as-
is. Thus, if a pattern consists of "xy", then the only input sequence that will match it
is "xy". Characters such as newline and tab arespecified using the standard escape
sequences, which begin with a \ . For example, a newline is specified by \n. In the
language of regular expressions, a normal character is also called a literal.
A character class is a set of characters. A character class is specified by putting the
characters in the class between brackets. For example, the class [wxyz] matches w,
x, y, or z. To specify an inverted set, precede the characterswith a ^. For example,
[^wxyz] matches any character except w, x, y, or z. Youcan specify a range of
characters using a hyphen. For example, to specify a character class that will match
the digits 1 through 9, use [1-9].
The wildcard character is the . (dot) and it matches any character. Thus, apattern
that consists of "." will match these (and other) input sequences: "A","a", "x",
and so on.
A quantifier determines how many times an expression is matched. The basic
quantifiers are shown here:

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.

Demonstrating Pattern Matching

import java.util.regex.*;

public class RegEx1 {

public static void main(String[] args) {


Pattern pat;
Matcher mat;
boolean found;
pat=Pattern.compile("Java");
mat=pat.matcher("Java");
found=mat.matches();
System.out.println("Testing Java against Java.");
if(found)
System.out.println("Matches");
else
System.out.println("No Match");
System.out.println();
System.out.println("Testing Java against Java SE.");
mat=pat.matcher("Java SE");
found=mat.matches();
if(found)
System.out.println("Matches");
else
System.out.println("No Match");
}
}

The output from the program is shown here:

Testing Java against Java.Matches

Testing Java against Java SE.No


Match

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 {

public static void main(String[] args) {


Pattern pat=Pattern.compile("Java");
Matcher mat=pat.matcher("Java SE");

System.out.println("Looking for Java in Java SE.");

if(mat.find()) System.out.println("Subsequence found");


else System.out.println("No match");

}
}

The output is
Looking for Java in Java SE.
Subsequence found

In this case, find( ) finds the subsequence "Java".


The find( ) method can be used to search the input sequence for repeated
occurrences of the pattern because each call to find( ) picks up where the previous
one left off. For example, the following program finds two occurrences of the pattern
"test":

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

public class RegEx2 {

public static void main(String[] args) {


Pattern pat=Pattern.compile("test");
Matcher mat=pat.matcher("test 1 2 3 test");

while(mat.find()) System.out.println("test found at index "+mat.start());


}
}
The output is
test found at index 0
test found at index 11

The program uses the start( ) method to obtain the index of each match.

Using Wildcards and Quantifiers

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;

public class RegEx2 {

public static void main(String[] args) {


Pattern pat=Pattern.compile("W+");
Matcher mat=pat.matcher("W WW WWW");

while(mat.find()) System.out.println("Match: "+mat.group());


}
}
The output from the program is shown here:

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;

public class RegEx2 {

public static void main(String[] args) {


Pattern pat=Pattern.compile("e.+d");
Matcher mat=pat.matcher("extend cup end table");

while(mat.find()) System.out.println("Match: "+mat.group());


}
}

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.

By adding the ? to the pattern, causes the shortest matching pattern to be


obtained.

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

public class RegEx2 {

public static void main(String[] args) {


Pattern pat=Pattern.compile("e.+?d");
Matcher mat=pat.matcher("extend cup end table");

while(mat.find()) System.out.println("Match: "+mat.group());


}
}
The output is

Match: extend
Match: end

Working with Classes of Characters

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;

public class RegEx2 {

public static void main(String[] args) {


Pattern pat=Pattern.compile("[a-z]+");
Matcher mat=pat.matcher("this is a test");

while(mat.find()) System.out.println("Match: "+mat.group());


}
}

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;

public class RegEx2 {

public static void main(String[] args) {


String str="Jon Jonathan Frank Ken Todd";
Pattern pat=Pattern.compile("Jon.*? ");
Matcher mat=pat.matcher(str);
System.out.println("Original Sequence: "+str);
str=mat.replaceAll("Eric ");
System.out.println("Modified Sequence: "+str);
}
}
The output is shown here:

Original sequence: Jon Jonathan Frank Ken Todd


Modified sequence: Eric Eric Frank Ken Todd

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;

public class RegEx2 {

public static void main(String[] args) {


String str="Jon Jonathan Frank Ken Todd";
Pattern pat=Pattern.compile("[ ,.!]");
String strs[] = pat.split("One two,alpha9 12!done.");
for(int i=0;i<strs.length;i++)
System.out.println("Next token: "+strs[i]);
}
}

The output is shown here:

Next token: one


Next token: two
Next token: alpha9
Next token: 12
Next token: done

Two Pattern-Matching Options

If you only need to perform a one-time pattern match, you can use the matches()
method defined by Pattern. It is shown here:

static boolean matches(String pattern, CharSequence str)


It returns true if pattern matches str and false otherwise. This method
automatically compiles pattern and then looks for a match. If you will be usingthe
same pattern repeatedly, then using matches( ) is less efficient than compiling the
pattern and using the pattern-matching methods defined by Matcher, as described
previously.
You can also perform a pattern match by using the matches( ) method
implemented by String. It is shown here:

boolean matches(String pattern)

If the invoking string matches the regular expression in pattern, then matches()
returns true. Otherwise, it returns false.

Program for Date Validation:

import j a v a . u t i l . r e g e x . * ;

public class Regex11 {

public s t a t i c void m a i n ( S t r i n g [ ] args) {


S t r i n g regex = " ^ [ 0 - 3 ] ? [ 0 - 9 ] / [ 0 - 3 ] ? [ 0 - 9 ] / ( ? : [ 0 - 9 ] { 2 } ) ? [ 0 -
9]{2}$";

Pattern p a t t e rn = Pattern. compile(rege 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());

The output is:

1/11/*2020 : false
1/11/2020 : true
Program for Email Validation:

import java.util.regex.*;

public class Regex11 {

public static void main(String[] args) {


String emails="user@domaincom";
String emails1="user*domaincom";
String regex = "^(.+)@(.+)$";
Pattern pattern = Pattern.compile(regex);

Matcher matcher = pattern.matcher(emails);


System.out.println(emails +" : "+ matcher.matches());

Matcher matcher1 = pattern.matcher(emails1);


System.out.println(emails1 +" : "+ matcher1.matches());
}

The output is:

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

Enter the Address

Chennai

Employee List:

FirstName SecondName MobileNumber Email Address


Anitha Ramesh 9906699224 anitha.ram@gmail.com Bangalore
Janani Velmurugan 7890123000 janani.vel@gmail.com Chennai
11. PART A
1. Compare expression lambdas and block lambdas? Give an example.
(K1,CO4)

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;

};

2. Define functional interface (K1,CO4)


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

3. What is mutable object and immutable object? Give example (K1,CO4)


When you create a String object, you are creating a string that cannot be changed.
Each time you need an altered version of an existing string, a new String object is
created that contains the modifications. The original string is left unchanged.

StringBuffer and StringBuilder-Both hold strings that can be modified after they
are created

4. What is the main difference between StringBuffer and StringBuilder?


(K1,CO4)

StringBuilder is similar to StringBuffer except for one important difference: it is


not synchronized, which means that it is not thread-safe. The advantage of
StringBuilder is faster performance.

5. What are the different ways of constructing a String object?(K1,CO4)


String s = new String();

String(char chars[ ])
String(char chars[ ], int startIndex, int numChars)

String(String strObj)

6. What is the difference between equals() and == in Java Strings.(K1,CO4)


equals( ) method compares the characters inside a String object. The == operator
compares two object references to see whether they refer to the same instance.

7. Write a java program to check whether a given string is palindrome or not.


(K3,CO4)

public class StringDemo {


public static void main(String[] args) {

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

8. Differentiate between an ArrayList and an LinkedList (K1,CO4)

9. What do you understand by Iterator in the Java Collection Framework?


(K1,CO4)

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.

3. Within the loop, obtain each element by calling next( ).

10. What is the use of the List interface? (K1,CO4)

✓ List interface extends from Collection interface

✓ It stores elements in a sequential manner

✓ Elements in the list can be accessed or inserted based on their position

✓ Starts with zero based index

✓ Can contain duplicate elements


✓ An Iterator can be used to access the elements of the List

11. What is ArrayList in Java? (K1,CO4)

✓ The ArrayList class extends AbstractList and implements the List interface.

✓ ArrayList supports dynamic arrays that can grow as needed.


✓ Standard arrays are of fixed size. After arrays are created they cannot grow or
shrink.

✓ It provides more powerful insertion and search mechanisms than arrays.

✓ Gives faster Iteration and fast random access.

✓ Ordered Collection (by index), but not Sorted.


12.How would you convert an ArrayList to Array and an Array to ArrayList?
(K1,CO4)

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.

13. What is a Vector in Java? (K1,CO4)


Vectors are similar to arrays, where the elements of the vector object can be accessed
via an index into the vector. Vector implements a dynamic array. Also, the vector is
not limited to a specific size, it can shrink or grow automatically whenever required.
It is similar to ArrayList, but with two differences:

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)

• HashSet stores the elements by using a mechanism called hashing.

• HashSet contains unique elements only.

• HashSet allows null value.

• HashSet class is non synchronized.


• HashSet doesn't maintain the insertion order. Here, elements are inserted on the
basis of their hashcode.

• HashSet is the best approach for search operations.

• The initial default capacity of HashSet is 16.

15. What is LinkedHashSet in Java Collections Framework? (K1,CO4)

• Java LinkedList class can contain duplicate elements.

• Java LinkedList class maintains insertion order.

• Java LinkedList class is non synchronized.

• In Java LinkedList class, manipulation is fast because no shifting needs to occur.

• Java LinkedList class can be used as a list, stack or queue.

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.

The Collections Framework is a sophisticated hierarchy of interfaces and classes that


provide state-of-the-art technology for managing groups of objects.

17. List down the different Collection views provided by the Map interface in
the Java Collection framework? (K1,CO4)

The Map interface provides 3 views of key-value pairs which are:

• key set view

• value set view

• entry set view

18. What is Map interface in Java?(K1,CO4)

• A Map doesn't allow duplicate keys,

• but you can have duplicate values.

• HashMap and LinkedHashMap allow null keys and values,

• but TreeMap doesn't allow any null key or value.


19. Why Map doesn’t extend the Collection Interface?(K1,CO4)
• The main reason Map doesn’t extend the Collection interface is that the add(E e)
method of the Collection interface doesn’t support the key-value pair like Map
interface’s put(K, V) method. It might not extend the Collection interface but still
is an integral part of the Java Collections framework.

20. What are different ways to iterate over a list? (K1,CO4)

• iterator()

• for each loop

• listiterator()

21. What are the basic interfaces of Java Collections Framework? (K1,CO4)

• List

• Set

• Queue

22. List out the common Exceptions raised by various collections.(K1,CO4)

• UnsupportedOperationException the operation is not supported by the collection.


• A ClassCastException is generated when one object is incompatible with another,
such as when an attempt is made to add an incompatible object to a collection.

• A NullPointerException is thrown if an attempt is made to store a null object and


null elements are not allowed in the collection.

• An IllegalArgumentException is thrown if an invalid argument is used.


• An IllegalStateException is thrown if an attempt is made to add an element to a
fixed-length collection that is full.

23. What is a regular expression?(K1,CO4)


The regular expression package, java.util.regex lets you perform sophisticated
pattern matching operations. A regular expression is a string of characters that
describes a character sequence. This general description, called a pattern, can
then be used to find matches in other character sequences. Regular expressions
can specify wildcard characters, sets of characters, and various quantifiers.
24. Write down the two classes which supports the regular expression.
(K1,CO4)

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.

7. Explain in detail Regular expression with examples.


8. Write a program to validate the email address using regular expression.
9. List out all the methods in ArrayList with an example.
10. Write a program to insert, delete, search and sort elements in ArrayList.
11. Draw the hierarchy of collection framework and explain.
12. Explain all the methods in the Set interface and write a program to print the unique
elements in a list of elements using collection.
13. List out all the methods in ArrayList and write a Java program to sum and average
of all the elements of an ArrayList

14. Explain the methods in LinkedList class


15. Write a Java program to get the first and last occurrence of the specified elements
in a linked list and print the list in forward and backward order.
16. Write a Java program to compare two linked lists
17. Write a java program to print the list in descending order.
18. Write a Java program to get the first and last occurrence of the specified elements
in a linked list and print the list in forward and backward order.
19. Explain the different interfaces and views of Map with all its methods and write a
Java program to get all keys from the given Map

20. Explain the different interfaces and views of Map with all its methods and write a
program to iterate through the Map

21. Write a program to find the longest repeating sequence in a string


22. Write a program for date validation using regular expression
13. ONLINE CERTIFICATIONS

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.

It is declared as shown here:

class Dictionary<K, V>

Here, K specifies the type of keys, and V specifies the type of values.

Sr.No. Method & Description

1 Enumeration elements( )
Returns an enumeration of the values contained in the dictionary.

2 Object get(Object key)


Returns the object that contains the value associated with the key. If the
key is not in the dictionary, a null object is returned.

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.

5 Object put(Object key, Object value)


Inserts a key and its value into the dictionary. Returns null if the key is not
already in the dictionary; returns the previous value associated with the key
if the key is already in the dictionary.
6 Object remove(Object key)
Removes the key and its value. Returns the value associated with the key.
If the key is not in the dictionary, a null is returned.

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

Tentative schedule for the Assessment During 2022-2023 EVEN

S.No Name of the Start date End date Portion


Assessment
1 Unit Test 1 - - Unit 1
2 IAT1 06.05.23 12.05.23 Unit 1 & 2
3 Unit Test 2 - - Unit 2
4 IAT2 10.06.23 16.06.23 Unit 3 & 4
5 Revision 1 - - Unit 5,1 &
2
6 Revision 2 - - Unit 3 & 4
7 Model 05.07.23 14.07.23 All 5 Units
17. PRESCRIBED TEXT BOOKS AND REFERENCES

TEXTBOOK:
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, Dreamtech press, 2011.


4. Timothy Budd, Understanding Object-oriented programming with Java,
Third Edition, Pearson Education, 2008.

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

A Video Rental Inventory System


The goal of this project is to design and implement a simple inventory control system for
a small video rental store. Define least two classes: a class Video to model a video and a
class VideoStore to model the actual store.

Assume that an object of class Video has the following attributes:

1. A title;

2. a flag to say whether it is checked out or not; and

3. An average user rating.

Add instance variables for each of these attributes to the Video class.

In addition, you will need to add methods corresponding to the following:

1. being checked out;

2. being returned; and

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. addVideo(String): add a new video (by title) to the inventory;

2. checkOut(String): check out a video (by title);

3. returnVideo(String): return a video to the store;

4. receiveRating(String, int) : take a user's rating for a video; and


5. listInventory(): list the whole inventory of videos in the store.
Finally, create a VideoStoreLauncher class with a main() method which will test the
functionality of your other two classes. It should allow the following.

1. Add 3 videos: "The Matrix", "Godfather II", "Star Wars Episode IV: A New Hope".

2. Give several ratings to each video.

3. Rent each video out once and return it.

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.

You might also like