Professional - Programming in Java - Trainer Guide
Professional - Programming in Java - Trainer Guide
nl
O
se
Professional
rU
Programming in Java
te
en
C
h
ec
pt
rA
Fo
y
Professional Programming in Java
nl
Trainer’s Guide
O
© 2016 Aptech Limited
se
All rights reserved.
rU
No part of this book may be reproduced or copied in any form or by any means – graphic, electronic or
mechanical, including photocopying, recording, taping, or storing in information retrieval system or sent
te
or transferred without the prior written permission of copyright owner Aptech Limited.
en
APTECH LIMITED
C
se
but a lot of ignorance is just as bad.
rU
te
en
C
h
ec
pt
rA
Fo
Preface
The book 'Professional Programming in Java' Trainer’s Guide aims to teach the students the
advanced concepts and impelmentation of object-oriented features in Java. The faculty/trainer
should teach the concepts in the theory class using the slides. This Trainer’s Guide will provide
guidance on the flow of the module and also provide tips and additional examples wherever
necessary. The trainer can ask questions to make the session interactive and also to test the
understanding of the students.
y
This book is the result of a concentrated effort of the Design Team, which is continuously
nl
striving to bring you the best and the latest in Information Technology. The process of design
has been a part of the ISO 9001 Certification for Aptech-IT Division, Education Support Services.
O
As part of Aptech’s quality drive, this team does intensive research and curriculum enrichment
to keep it in line with industry trends.
se
We will be glad to receive your suggestions.
rU Design Team
te
en
C
h
ec
pt
rA
Fo
“ Practice is the best of
“
all instructors.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
Table of Contents
Sessions
1. Exceptions and Assertions
2. java.lang Package
y
3. Collections API
nl
4. Generics
O
5. File Handling in Java
se
6. New Features in File Handling
7. Introduction to Threads
nl
O
we do in the present.
se
rU
te
en
C
h
ec
pt
rA
Fo
Session 1 – Exceptions and Assertions
1.1.1 Objectives
By the end of this session, the learners will be able to:
y
nl
Describe exception
Explain the use of try-catch-finally blocks
O
Explain throwing and handling exceptions
Explain handling multiple exceptions in a single catch block
se
Explain the use of try-with-resources
Describe creation and use of custom exceptions
Explain assertions and its types
Java.
C
You should teach the concepts in the theory class using the images provided. For teaching in
the class, you are expected to use slides and LCD projectors.
h
ec
Tips:
It is recommended that you test the understanding of the students by asking questions in
between the class.
pt
In-Class Activities:
rA
©Aptech Limited
Overview of the Session:
Then give the students the overview of the current session in the form of session objectives.
Show the students slide 2 of the presentation.
y
nl
O
se
Tell the students that this session introduces the concept of creation and use of exceptions
rU
in Java which deals with creation of user-defined exceptions and throwing exceptions from a
method in the class. Also introduce them with the concept and use of Assertions.
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
1.2 In-Class Explanations
Slide 3
Let us understand how Java handles exceptions.
y
nl
O
se
rU
Using slide 3, explain an introduction to exception handling in Java.
te
Tell the students that every code even though it is well written, it is prone to behave
erroneously. This means that when the code is executing, it can result to some unexpected
en
To resolve this situation, modern object-oriented languages such as Java provide the ability
C
to handle unexpected events in the program. This mechanism to handle unexpected events
or errors in a program is referred to as exception handling.
h
ec
With the help of exception handling, the developer can ensure that the user gets a proper
message in case some error occurs in the program. It also helps to ensure that in case of an
error, the data and processes that the program is using do not get affected adversely.
pt
rA
Fo
©Aptech Limited
Slide 4
Let us understand the exceptions.
y
nl
O
se
Using slide 4, explain the exceptions.
Exception rU
te
An exception is an event occurring during program execution that leads to disruption of the
normal flow of the program’s instructions. Exception handling in Java is a way for ensuring
en
program. Exceptions can be raised because of a fault in the code or unexpected conditions
the common language runtime encounters and so on.
h
An exception does not always indicate an error but also signal some unusual event in your
ec
program. A major benefit of having an error signaled by an exception is that it separates the
code that deals with errors from the code that is executed. Exception provides a way of
pt
To handle the exceptions, Java provides the try-catch-finally blocks. Using these blocks, the
developer can check the program statements for errors and handle them in case they occur.
Fo
In-Class Question:
After you finish explaining the exceptions, you will ask the students an In-Class question.
This will help you in reviewing their understanding of the topic.
©Aptech Limited
Slides 5 to 9
Let us understand try-catch-finally block.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
rU
te
en
C
In order to handle exceptions, the developer needs to identify the statements that may lead
to exceptions and enclose them within a try block. Next, exception handlers need to be
associated with a try block by providing one or more catch blocks directly after the try
pt
block.
rA
Then, explain the code snippet that shows an example of try-catch block mentioned in
slides 6 and 7. Explain them that in the code, line 1 might raise an exception when the value
of num2 is set to 0. Therefore, a catch block is provided to handle the exception. The
class that will handle the exception is ArithmeticException. When the exception
occurs, it will be raised in the try block and handled by the catch block.
The statement within the catch block will be executed to inform the user of the error.
The statement provides a user-friendly message along with a built-in error message using
the getMessage() method.
©Aptech Limited
The finally block is executed even if an exception occurs in the try block. It helps the
programmer to ensure that the cleanup code does not get accidentally bypassed by a
break, continue, or return statement in the try block.
Then, explain the code snippet that demonstrates the use of the finally block
mentioned in slides 8 and 9. In the code, an object of the PrintWriter class is created
with the file name MyFile.txt as an argument. Now, during execution, when the
PrintWriter tries to access the file MyFile.txt, it might throw an exception if the file
does not denote an existing, writable, regular file, and a new regular file of that name
cannot be created, or if some other error occurs while opening or creating the file. To
y
inform the user of the situation, a corresponding catch block is provided that handles the
nl
FileNotFoundException. Also, to ensure that after the exception is caught, the
PrintWriter object is not left open, the finally block is provided in which the
O
PrintWriter object is closed. Thus, the cleanup code is executed despite of an
exception as it was written in the finally block.
se
Tips:
rU
The finally block is useful to clean up resources in the event of the try block executing
without an exception and in case when there is an exception. The finally block appears
directly after the last catch block.
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 10 to 15
Let us understand throw and throws keywords.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
Tell them that many a time; it might be required to let a method transfer the control further
up to the call stack to handle the exception.
©Aptech Limited
For example, while making connection to servers, one might not be able to anticipate the
type of format in which the server id will be provided by the user. In this case, it is advisable
not to catch the exception and to allow a method further up the call stack to handle it.
The throws clause is written to throw the exception to the calling method in the method
stack. It is written after the method name and argument list and before the opening brace
of the method.
Explain the code snippet that shows the modified writeToFile() method with the
throws clause mentioned in slides 11 and 12.
y
Explain the code snippet, the writeToFile() method is made to throw the
nl
FileNotFoundException mentioned in slides 13 to 15.
O
The throws clause declares that your method is capable of throwing an exception, but it
does not handle the exception that must be specified by using throws clause with the
se
method declaration.
rU
When a user-defined exception is to be raised, throw keyword is used. The throw
keyword should be defined in either try-catch block or the method should be defined
using throws keyword.
te
Tips:
en
You cannot throw multiple exceptions, whereas you can declare multiple exceptions using
throws keyword.
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 16 and 17
Let us understand throwing exceptions from methods.
y
nl
O
se
rU
te
en
C
h
ec
Tell them that it is appropriate for the code to catch exceptions within the method itself.
rA
However, sometimes the method can throw the exception up in the hierarchy in the
method call stack to handle the exception.
Fo
Explain the code snippet mentioned in slides 16 and 17 that shows how to throw
ArithmeticException is thrown by the method in the Calculator class.
Tell them that, in the code, the divide() method declares the
ArithmeticException in the throws clause.
Now, if the value of denominator b is set to 0 at runtime, the method throws the
ArithmeticException using the throw statement. Thus, the exception is thrown
from the method to be handled by another method further up in the call stack. Here, the
main() method consists of the catch block to handle the exception and print the
appropriate message to the user.
©Aptech Limited
Tips:
The throw statement requires a single argument, a throwable object. Throwable
objects are instances of any subclass of the Throwable class. Following example shows
the throw statement:
throw someThrowableObject;
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 18 to 20
Let us understand handling multiple exceptions in a single catch block.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
Using slides 18 to 20, explain handling multiple exceptions in a single catch block.
©Aptech Limited
Tell them that with Java SE 7 and later versions, a programmer can write a code to handle
more than one exception in a single catch block. This feature helps to reduce code
duplication and prevent the use of a much generalized exception.
Prior to Java SE 7, if you want to catch two exceptions you need to provide two catch
blocks and if you have same code to run on these two blocks, then either you need to use
finally block or just duplicate the code on two catch blocks.
To create a multiple exception catch block, specify the types of exceptions that catch
block can handle separated by a vertical bar (|) as follows:
y
catch (ExceptionType1|ExceptionType2 ex) {
nl
// statements
}
O
For example, in the catch block, you can specify the types of exceptions which the catch
se
clause can handle.
catch (ArithmeticException|NumberFormatException ex) {
throw ex;
} rU
Since, the catch block handles more than one type of exception, then the catch parameter
te
that is ex, is implicitly final. Therefore, one cannot assign any values to it within the
catch block.
en
C
Then, explain the code snippet that shows an example of handling multiple exceptions in a
single catch block mentioned in slides 19 and 20.
h
ec
pt
rA
Fo
©Aptech Limited
Slides 21 to 26
Let us understand using try-with-resources and AutoCloseable interface.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Prior to Java SE 7, the finally block was used to ensure that a resource is closed
regardless of whether the try statement completes normally or abruptly.
y
destination of data that can be closed. The close() method is invoked to release
nl
resources that the object is holding, such as open files.
O
The close() method of the Closeable interface throws exceptions of type
IOException, while the close() method of the AutoCloseable interface throws
exceptions of type Exception. Consequently, subclasses of the AutoCloseable
se
interface can override this behavior of the close() method to throw specialized
exceptions, such as IOException, or no exception at all.
rU
Then, explain the code snippet mentioned in slide 23 that explains that use of try-with-
resources statement.
te
In the code, an object of the Writer class has been created and initialized with the
en
reference of BufferedWriter that writes a line to the file specified by the variable path.
Here, BufferedWriter is a resource that must be closed after the program is finished
C
using it. The declaration statement appears within the parenthesis immediately after the
try keyword. In Java SE 7 and later, the class BufferedWriter implements the
AutoCloseable interface. Since the BufferedWriter instance is declared in a try-
h
Then, explain the code snippet shows an example that uses a finally block instead of a
try-with-resources statement to close the resources mentioned in slide 24.
rA
Explain the code snippet that shows an example that declares more than one resource in a
single try-with-resources statement mentioned in slides 25 and 26.
©Aptech Limited
In-Class Question:
After you finish explaining using try-with-resources and AutoCloseable
interface, you will ask the students an In-Class question. This will help you in reviewing their
understanding of the topic.
y
Tips:
nl
In try-with-resources statement, the catch and finally blocks are optional.
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 27
Let us understand enhancements in exceptions in Java SE 7.
y
nl
O
se
Using slide 27, explain enhancements in exceptions in Java SE 7.
rU
Catching Multiple Exception Types and Rethrowing Exceptions - A single catch block can
handle more than one type of exception. In addition, the compiler performs more precise
te
analysis of rethrown exceptions than earlier releases of Java SE. This enables you to specify
more specific exception types in the throws clause of a method declaration.
en
The try-with-resources statement ensures that each resource is closed at the end of
ec
©Aptech Limited
Slide 28
Let us understand user-defined exceptions.
y
nl
O
se
Using slide 28, explain user-defined exceptions.
rU
Most of the time while developing applications in Java, you feel a need to create and throw
your own exceptions. These exceptions are known as user-defined exceptions or custom
te
exceptions.
en
other vendors.
The code throws more than one related exception.
h
ec
User-defined exceptions inherit the Exception class in order to act as an exception. You
don’t have to implement anything inside it and no methods are required.
pt
rA
Fo
©Aptech Limited
Slides 29 and 30
Let us understand creating a user-defined exception.
y
nl
O
se
rU
te
en
C
h
ec
To create a user-defined exception class, the class must inherit from the Exception class.
rA
The code snippet explains creation of a user-defined exception class mentioned in slides 29
and 30. In the code, ServerException is a user-defined exception class that inherits from the
Fo
built-in Exception class. The getMessage() method of the Exception class has been
overridden in the ServerException class to print a user-defined message “Connection
Failed”.
©Aptech Limited
Slides 31 and 32
Let us understand throwing user-defined exceptions.
y
nl
O
se
rU
te
en
C
h
ec
To raise a user-defined exception, a method must throw the exception at runtime. The
rA
exception is transferred further up in the call stack and handled by the caller of the method.
The code snippet mentioned in slides 31 and 32 explains how to throw a user-defined
Fo
exception.
In the code, the MyConnection class consists of a constructor that accepts the ip address
and port number of the server and initializes the respective instance variables.
The connectToServer() method declares that it throws the ServerException by using the
throws clause on line 1. Inside the method, the value of ip and port variables is verified. If
the values do not match the pre-defined values, the method throws the ServerException on
line 2.
©Aptech Limited
Now, in the class TestConnection, an object of MyConnection is created with incorrect
values for ip and port within the try block. Next, on line 3, the connectToServer() method
has been invoked. Also, the statement has been included within a catch block to handle the
user-defined exception, ServerException. The statement, ex.getMessage() is used to invoke
the overridden getMessage() method of the ServerException class to print the user-defined
error message.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 33 to 37
Let us understand wrapper exceptions.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
rU
te
en
C
h
1.4.
rA
Most of Java’s built-in exceptions have constructors that can take a ‘cause’ parameter. They
also provide a getCause() method that will return the wrapped exception. The main
reason for using exception wrapping is to prevent the code further up the call stack from
Fo
knowing about every possible exception in the system. Also, one may not want the top level
components to know anything about the bottom level components and the exceptions they
throw.
The code snippet explains the use of wrapper exceptions mentioned in slides 34 to 37.
In the code, a user-defined exception class named CalculatorException is created. The class
has two overloaded constructors that take the Throwable object and a message string as
parameters. Next, on line 2, another class named Calculator is created. It consists of the
divide() method that throws the CalculatorException.
©Aptech Limited
Within the method, a try-catch block is provided that catches the actual exception, that is,
ArithmeticException when b is set to 0. However, within the catch block, the
ArithmeticException object is wrapped with a custom message string into the
CalculatorException object on line 4 and then the CalculatorException object is thrown.
Next, the TestCalculator class is created with the main() method. Within main(), the divide()
method is invoked inside the try block. In the catch block, the CalculatorException is
handled. However, the actual cause of the CalculatorException was
ArithmeticException. So, to retrieve the cause, the getCause() method is used on
line 5 and the cause is retrieved in the Throwable object.
y
Lastly, both the message and the cause are printed on lines 6 and 7.
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 38 to 43
Let us understand assertions.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
An assertion is a statement in Java that allows the programmer to test his/her assumptions
about the program.
©Aptech Limited
While executing assertion, it is believed to be true. If it fails, JVM will throw an error named
AssertionError. It is mainly used for testing purpose.
Each assertion is composed of a boolean expression that is believed to be true when the
assertion executes. If it is not true, the system will throw an error. By verifying that the
boolean expression is indeed true, the assertion confirms the assumptions about the
behavior of the program. This helps to increase the programmer’s confidence that the code
is free of errors.
Then, explain the syntax of assertion statement which has the following two forms:
y
assert <boolean_expression>;
nl
or
assert <boolean_expression> : <detail_expression> ;
O
To ensure that assertions do not become a performance liability in deployed applications,
se
assertions can be enabled or disabled when the program is started. Assertions are disabled
by default. Disabling assertions removes their performance related issues entirely. By
rU
default, assertion checking is disabled in the Java program.
Then, explain the steps mentioned in slides 41 to 43 to enable assertions in NetBeans IDE.
C
Assertions provide an effective way to detect and correct the programming errors. They can
be enable or disable at runtime. Assertion in Java guarantees that at a certain point on
h
function, your assumption or certain condition is true, otherwise, it would not have come to
that point and would have been terminated with AssertionError.
ec
Assertion can be used in data validation where assert keyword validate the data passed
pt
to the method. However, assertion should not be used to check arguments in the public
methods because it could result in appropriate runtime exception.
rA
In-Class Question:
After you finish explaining assertions, you will ask the students an In-Class question. This will
Fo
©Aptech Limited
Then, tell them that one can use assertions to document and verify the assumptions and
internal logic of a single method in the following ways:
Internal Invariants
Control flow Invariants
Precondition and Postcondition
Class Invariants
Tips:
Programmers might wish to ensure that assertions are not disabled in the field. Following
static initialization prevents a class from being initialized if its assertions have been disabled:
y
static {
boolean assertsEnabled = false;
nl
assert assertsEnabled = true; // Intentional side effect
O
if (!assertsEnabled)
throw new RuntimeException("Asserts must be enabled!!!");
se
}
©Aptech Limited
Slides 44 to 46
Let us understand internal invariants.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Earlier, where assertions were not available, many programmers used comments to indicate
their assumptions concerning a program’s behavior.
For example, one might have written a comment as shown in the code snippet to explain
the assumption about an else clause in an if...else statement mentioned in slide 44.
The code states that the else statement should be executed only if a is equal to zero, but not
if a>0. However, at runtime, this can be missed out since no error will be raised even if a
negative number is specified at runtime.
y
For such invariants, one can use assertion as shown in the code snippet mentioned in slides
45 and 46.
nl
O
When your code contains a construct that assert an invariant, you should change it into
assert.
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 47 to 49
Let us understand control flow invariants.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Assertions can also be applied to control flow invariants such as a switch statement that
has no default case. The absence of a default case is indicative of the belief that one of
the cases will always be executed.
An assertion can be placed at any location where control will not be reached. This technique
should be used with discretion. If a statement is unreachable, you will see a compile-time
error, if you try to assert that it is unreached.
The assumption that a particular variable will surely have any one of a small set of values is
an invariant that needs to be checked with an assertion.
y
Suppose a switch statement appears in a program that checks days of a week as shown in
nl
the code snippet mentioned in slides 48 and 49.
O
The code probably indicates an assumption that the day variable will have only one of the
seven values.
se
To test this assumption, one can add the following:
default case:
default:
assert false : day + “ is incorrect”;
rU
te
If the day variable takes on any other value and assertions are enabled, the assertion will
en
©Aptech Limited
Slides 50 to 56
Let us understand preCondition, postCondition, and class invariants.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
y
nl
O
Using slides 50 to 56, explain PreCondition, PostCondition, and Class Invariants.
se
While the assert construct is not a complete help in itself, it can help support an informal
design-by-contract style of programming.
Preconditions:
C
Explain the code given in the Code Snippet mentioned in slide 51. In the code, the method
setRate() takes the refresh rate as a parameter and checks if the value is less than zero and
pt
One can use an assertion to test a precondition of a non-public method that is believed to
be true no matter what a user does with the class.
Fo
©Aptech Limited
Postconditions:
Postconditions can be checked with assertions in both public and non-public methods.
The public method pop() in the Code Snippet that uses an assert statement to check a
postcondition mentioned in slides 53 and 54. In the code, a pop() method is used to pop
elements from a list. First, the size of the list is determined on line 1 with the help of the
size() method. Next, if the size equals zero, the RuntimeException is thrown.
Further, the code to pop the element is provided. Now, before popping the next element, a
check is made using assertion on line 2. Here, if the size() method does not return a
y
value equal to size-1, the assertion fails and throws an AssertionError.
nl
Class Invariants:
O
A class invariant is a type of internal invariant that is applied to every instance of a class. It is
applicable at all times except when the instance is transiting from one consistent state to
se
another.
rU
A class invariant can be used to specify the relationships among multiple attributes. Also, it
should be true before and after any method completes. The assertion mechanism does not
adopt any specific style for checking invariants.
te
However, it is sometimes convenient and advisable to combine the expressions that verify
en
the required constraints into a single internal method that can be called by assertions.
Then discuss the example of a balanced tree, it would be better to implement a private
C
method that checked that the tree was indeed balanced as per the rules of the data
structure as shown in the Code Snippet mentioned in slide 56.
h
Tips:
ec
It is advisable to include class invariant checks at the head of methods in classes whose state
is modifiable by other classes.
pt
rA
Fo
©Aptech Limited
Slides 57 and 58
Let us summarize the session.
y
nl
O
se
rU
te
en
C
h
ec
Using slides 57 and 58, summarize the session. End the session with a brief summary of
pt
package.
Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the OnlineVarsity site to
gain additional information related to the topics covered in the next session. You can also
connect to online tutors on the Online Varsity site to ask queries related to the sessions.
©Aptech Limited
Session 2 – java.lang Package
Here, you can ask students the key topics they can recall from previous session. Prepare a
question or two which will be a key point to relate the current session objectives.
y
nl
2.1.1 Objectives
By the end of this session, the learners will be able to:
O
Describe the java.lang package
se
Explain the various classes of java.lang package
Explain how to use and manipulate Strings
Explain regular expressions, pattern, and matcher
rU
Explain String literal and Character classes
Explain the use of quantifiers, capturing groups, and boundary matchers
te
2.1.2 Teaching Skills
en
To teach this session, you should be well-versed with java.lang package and its classes. You
should be familiar with the strings, regular expressions, pattern and matcher, and the use of
C
You should teach the concepts in the theory class using the images provided. For teaching in the
h
Tips:
pt
It is recommended that you test the understanding of the students by asking questions in
between the class.
rA
In-Class Activities:
Follow the order given here during In-Class activities.
Fo
©Aptech Limited
Overview of the Session:
Then give the students the overview of the current session in the form of session objectives.
Show the students slide 2 of the presentation.
y
nl
O
se
rU
Tell the students that this session introduces the java.lang package and its classes. Also
introduce them with the strings, regular expressions, pattern and matcher, and the use of String
literal and character classes.
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
2.2 In-Class Explanations
Slide 3
Let us understand about the java.lang package.
y
nl
O
se
rU
Using slide 3, explain about the java.lang package.
te
While writing programs in Java, it is often required to perform certain tasks on the data specified
en
by the user. The data could be in any format such as strings, numbers, characters, and so on.
To manipulate such data, special classes, and methods are required. The Java language provides a
C
©Aptech Limited
Slide 4
Let us understand overview of the java.lang package.
y
nl
O
se
Using slide 4, explain overview of the java.lang package.
rU
The java.lang package provides classes that are fundamental for the creation of a Java
program. This includes the root classes that form the class hierarchy, basic exceptions, types tied
te
to the language definition, threading, math functions, security functions, and information on the
underlying native system.
en
The java.lang contains classes and interfaces that are essential and core to Java language. As
C
the classes are so essential, the java.lang package is implicitly imported by every Java source
file. Hence, an explicit import statement is not required for using this package.
h
Error, Exception, and RuntimeException: These are base classes for each
Fo
exception type.
String: It is the class used for creating and manipulating strings and string literals.
©Aptech Limited
StringBuffer and StringBuilder: These classes are used for performing string
manipulation.
Iterable: This is an interface that allows generic iteration using the enhanced for
loop.
y
classes provide system operations for managing the creation of external processes,
nl
dynamic loading of classes.
O
Math: This class provides basic math functions such as square root, sine, cosine, and so on.
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 5 to 7
Let us understand working with Garbage Collection.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 5 to 7, explain working with Garbage Collection.
se
Following figure shows the JVM architecture:
rU
te
en
C
h
ec
There are three components of the JVM that are focused on deciding the performance of the
code execution. The heap is where your object data is stored. This area is then managed by the
pt
garbage collector selected at startup. Most performance tuning options relate to sizing the heap
and choosing the most appropriate garbage collector for your situation.
rA
The JIT compiler also has a big impact on performance but rarely requires tuning with the newer
versions of the JVM.
Fo
Garbage Collection:
Automatic garbage collection is the process of looking at heap memory, identifying which objects
are in use and which are not, and deleting the unused objects. An in use object, or a referenced
object, means that some part of your program still maintains a pointer to that object. An unused
object, or unreferenced object, is no longer referenced by any part of your program. So the
memory used by an unreferenced object can be reclaimed.
©Aptech Limited
In a programming language like C, allocating and deallocating memory is a manual process. In
Java, process of deallocating memory is handled automatically by the garbage collector. Garbage
collector is an automatic memory management program.
Garbage collection helps to avoid the problem of dangling references. Garbage collection also
y
solves the problem of memory leak problem.
nl
Then, discuss the following parameters must be studied while designing or selecting a garbage
O
collection algorithm:
Serial versus Parallel - With serial collection, only one thing happens at a time. For example,
se
even when multiple CPUs are available, only one will be utilized to perform the collection.
Whereas, in parallel collection, the task of garbage collection is divided into subparts that are
rU
executed simultaneously on different CPUs. The simultaneous collection is speedy but leads
to additional complexity and potential fragmentation.
te
Concurrent versus Stop-the-world - In the stop-the-world garbage collection approach,
during garbage collection, application execution is completely suspended. Whereas, in
en
concurrent approach, one or more garbage collection tasks can be executed concurrently,
that is, simultaneously, with the execution of the application. However, this incurs some
overhead on the concurrent collectors and affects performance due to larger heap size
C
requirement.
h
garbage collector has determined which objects in memory are garbage, it can compact the
memory by moving all the live objects together and completely reclaiming the memory of the
unreferenced objects. After compaction, it becomes easier and quicker to allocate a new
pt
object at the first free location. This can be done by using a simple pointer to keep track of
the next location available for object allocation.
rA
In contrast, a non-compacting collector releases the space utilized by garbage objects in-
place. That is, it does not move all live objects together to create a large reclaimed region like
Fo
a compacting collector does. The benefit is faster completion of garbage collection, but the
drawback is potential fragmentation.
Then, explain the metrics that can be utilized to evaluate the performance of a garbage collector
as mentioned on slide 5.
The Object class in the java.lang package provides the finalize() method. The
finalize() method is called by the garbage collector on an object when it is identified to have
no more references pointing to it. A subclass overrides the finalize() method for disposing
©Aptech Limited
the system resources or to perform other cleanup. The finalize() method is never invoked
more than once by a Java virtual machine for any given object. Also, any exception thrown by the
finalize() method leads to suspension of the finalization of this object. The finalize()
method throws the Throwable exception.
Explain the Code Snippet that shows an example of automatic garbage collection mentioned in
slides 6 and 7.
Tips:
Generally, an object becomes eligible for garbage collection in Java when all the references of
y
that object explicitly set to null. Object is created inside a block and reference goes out of scope
once control exit that block. Parent object set to null, if an object holds reference of another
nl
object and when you set container object’s reference null, child or contained object automatically
O
becomes eligible for garbage collection.
In-Class Question:
se
After you finish explaining working with Garbage Collection, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
rU
Why subclass overrides the finalize() method?
te
Answer:
en
A subclass overrides the finalize() method for disposing the system resources or to perform
other cleanup.
C
Tips:
There are methods such as System.gc() and Runtime.gc() which are used to send
h
request of Garbage collection to JVM. They run the garbage collector. Calling these method
ec
suggests that the JVM put efforts toward recycling unused objects, in order to make the memory
available for quick reuse.
pt
When control returns from the method call, the virtual machine has made its best effort to
rA
©Aptech Limited
Slide 8
Let us understand wrapper classes.
y
nl
O
se
Using slide 8, explain wrapper classes.
rU
A wrapper class represents a primitive type, as if it were an object. The wrapper classes such as
Boolean, Character, Integer, Float, Long, and Double are used to manage primitive
te
values as objects. Each of these classes wraps a primitive data types within a class. The wrapper
classes also provide a number of methods for processing variables of specified data type to
en
another type. For example, an object of type Integer is a wrapper on the primitive data type
int.
C
Wrapper class wraps around a data type and gives it an object appearance. Wherever, the data
type is required as an object, this object can be used. In addition, wrapper classes include
h
methods to unwrap the object and give back the data type. All the wrapper classes are defined as
ec
Following table lists the data types and their corresponding wrapper classes:
Fo
©Aptech Limited
Note that the wrapper classes of all the primitive data types except int and char have the
same name as that of the data type.
For example, to retrieve the value stored in the Integer object intObject, we use the following
y
statement:
nl
int x = intObject.intValue();
O
Similarly, we have methods for the other seven wrapper classes: byteValue(),
shortValue(), longValue(), floatValue(), doubleValue(),
se
charValue(), and booleanValue().
Auto boxing refers to an implicit call to the constructor. Therefore, a new wrapper object can be
created by specifying the value to be wrapped just as we would do for a primitive data type
variable.
C
class Boxing{
h
System.out.println(a2+" "+a3);
}
rA
The automatic conversion of wrapper class type into corresponding primitive type, is known as
Fo
unboxing.
class Unboxing{
public static void main(String args[]){
Integer i= 50; // Autoboxing
int a=i; // Unboxing
System.out.println(a);
}
}
©Aptech Limited
Slides 9 to 12
Let us understand Math class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
Using slides 9 to 12, explain Math class.
The Math class contains methods for performing basic mathematical/numeric operations such as
rU
square root, trigonometric functions, elementary exponential, logarithm, and so on. By default,
many of the Math methods simply call the equivalent method of the StrictMath class for
their implementation.
te
It is not necessary to create an instance of the Math class in order to use its constants and
en
methods. In fact, the Math class does not define any public constructors, so it cannot be
instantiated.
C
Unlike some of the numeric methods of class StrictMath, all implementation of the
equivalent functions of class Math are not defined to return the bit-for-bit same results. This
h
required.
pt
Explain the list of the commonly used methods of the Math class mentioned in slide 9.
rA
Explain the Code Snippet that shows the use of some of the methods of Math class mentioned in
slides 10 to 12.
Fo
©Aptech Limited
Slides 13 to 15
Let us understand System class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 13 to 15, explain System class.
se
The System class provides several useful class fields and methods. However, it cannot be
instantiated. It provides several facilities such as standard input, standard output, and error
rU
output streams, a means of loading files and libraries, access to externally defined properties and
environment variables, and a utility method for quickly copying a part of an array.
te
Explain the list of the commonly used methods of the System class mentioned in slide 13.
en
Explain the Code Snippet that shows the use of some of the methods of System class mentioned
in slides 14 and 15. The code shows the use of the currentTimeMillis(), arraycopy(),
C
All the variables and methods in the System class are static. The System class does not define
any public constructors, so it cannot be instantiated.
ec
In-Class Question:
pt
After you finish explaining System class, you will ask the students an In-Class question. This will
help you in reviewing their understanding of the topic.
rA
Fo
Which of the method in System class terminates the currently time in milliseconds?
Answer:
exit()
©Aptech Limited
Slides 16 to 18
Let us understand Object class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 16 to 18, explain Object class.
se
Object class is the root of the class hierarchy. Every class has Object as a superclass. All
objects, including arrays, implement the methods of the Object class.
rU
Explain the list of the commonly used methods of the Object class mentioned in slide 16.
te
Explain the Code Snippet that shows the use of some of the methods of Object class mentioned
in slides 17 and 18. The code shows the use of the toString() and equals() methods of
en
Tips:
Although it is possible to create an instance of the Object class, this is rarely done because it is
h
more useful to create specialized objects. However, it is often useful to declare a variable that
contains a reference to an object, because such a variable can contain a reference to an object of
ec
©Aptech Limited
Slides 19 and 20
Let us understand Class class.
y
nl
O
se
rU
te
en
C
h
ec
pt
In an executing Java program, instances of the Class class represent classes and interfaces. An
array belongs to a class that is reflected as a Class object that is shared by all arrays with the
Fo
The primitive Java data types such as boolean, byte, and char also represented as Class objects.
Class objects are constructed automatically by the JVM, as the classes are loaded and by calling
the defineClass() method in the class loader.
Explain the list of the commonly used methods of the Class class mentioned in slide 19.
©Aptech Limited
Explain the Code Snippet that shows the use of some of the methods of Class class mentioned
in slide 20.
A class object provides considerable information about the data type. If a class object describe a
class or interface type, there are numerous methods that return information about the fields,
methods, and constructors of the type.
Tips:
The Class class has no public constructors, it cannot be explicitly instantiated. Class objects
are normally created by the ClassLoader in the JVM.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 21
Let us understand ThreadGroup class.
y
nl
O
se
Using slide 21, explain ThreadGroup class.
rU
A thread group represents a set of threads. The thread groups form a tree in which all the thread
group except the initial thread group has a parent.
te
Explain the list of some of the commonly used methods of the ThreadGroup class mentioned
en
in slide 21.
C
The ThreadGroup class implements a grouping scheme for threads. A ThreadGroup object
can own Thread objects and other ThreadGroup objects. This class provides methods that
allow a ThreadGroup object to control its Thread and ThreadGroup objects as a group.
h
ec
When a Java program starts, a ThreadGroup object is created to own the first thread. Any
additional ThreadGroup objects are explicitly created by the program.
pt
rA
Fo
©Aptech Limited
Slide 22
Let us understand Runtime class.
y
nl
O
se
Using slide 22, explain Runtime class.
rU
There is a single instance of class Runtime for every Java application allowing the application to
interface with the environment in which it is running. The current runtime is obtained by invoking
te
the getRuntime() method. An application cannot create its own instance of this class.
en
The Runtime class provides access to various information about the environment in which a
program is running. The Java run-time environment creates a single instance of this class that is
C
associated with a program. The Runtime class does not have any public constructors, so a
program cannot create its own instances of the class.
h
Explain the list of some of the commonly used methods of the Runtime class mentioned in slide
ec
22.
pt
rA
Fo
©Aptech Limited
Slide 23
Let us understand the concept of strings.
y
nl
O
se
Using slide 23, explain the concept of strings.
rU
Strings are widely used in Java programming. Strings are nothing but a sequence of characters. In
the Java programming language, strings are objects. The Java platform provides the String
te
class to create and manipulate strings. Whenever a string literal is encountered in a code, the
compiler creates a String object with its value.
en
In this case, “John” is a string literal, that is, a series of characters enclosed in double quotes.
pt
rA
Fo
©Aptech Limited
Slide 24
Let us understand String class.
y
nl
O
se
Using slide 24, explain String class.
rU
The String class represents character strings. All string literals in Java programs, such as ‘xyz’,
are implemented as instances of the String class.
te
The syntax of String class is as follows:
en
Comparable<String>, CharSequence
The String class has 13 overloaded constructors that allow specifying the initial value of the
h
Tell them that String is an immutable class in Java. An immutable class is simply a class whose
pt
instances cannot be modified. All information in an instance is initialized when the instance is
created and the information cannot be modified.
rA
The String class represents the sequence of characters. String class includes a number of utility
methods, such as methods for fetching individual characters, for translating characters to upper
Fo
or lowercase, for searching strings, and for parsing numeric values in strings.
The Java language provides support for the string concatenation operator (+), and the conversion
of other objects to strings. String concatenation can also be implemented through the
StringBuilder or StringBuffer class and it’s append method.
StringBuffer class represents a sequence of characters that can be modified. Its objects are
used to perform computations on String objects.
©Aptech Limited
Slide 25
Let us understand String methods.
y
nl
O
se
Using slide 25, explain String methods.
rU
Explain the list of String methods mentioned in slide 25.
te
Tips:
en
String pool is a special storage area in method area. String is created and if the string already
exists in the pool, the reference of the existing string will be returned, instead of creating a new
C
As the immutable objects cannot be changed, they can be shared among multiple threads freely.
©Aptech Limited
Slides 26 to 29
Let us understand StringBuilder and StringBuffer classes.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
Using slides 26 to 29, explain StringBuilder and StringBuffer classes.
StringBuilder objects are same as String objects, except that they are mutable.
rU
Internally, the runtime treats these objects similar to variable-length arrays containing a
sequence of characters. The length and content of the sequence can be modified at any point
through certain method calls. It is advisable to use String unless StringBuilder offer an
te
advantage in terms of simpler code or better performance.
en
The StringBuilder class also has a length() method that returns the length of the
character sequence in the builder.
C
Explain the list of the constructors of StringBuilder class mentioned in slide 26.
h
The Code Snippet explains the use of StringBuilder mentioned in slides 27 and 28.
ec
StringBuffer:
pt
The StringBuffer creates a thread-safe, mutable sequence of characters. Since JDK 5, this
rA
class has been supplemented with an equivalent class designed for use by a single thread,
StringBuilder. The StringBuilder class should be preferred over StringBuffer, as
it supports all of the same operations, but it is faster since it performs no synchronization.
Fo
The StringBuffer class represents a variable-length sequence of characters. Its objects are
used in computations that involve creating new String objects. When a StringBuffer
object is created, the constructor determines the initial contents and capacity of the
StringBuffer.
©Aptech Limited
The capacity of a StringBuffer is the number of characters that its internal data structure
can hold. However, it can vary. When a StringBuffer object is asked to hold more characters
than its current capacity allows, then the StringBuffer enlarges its data structure.
In-Class Question:
After you finish explaining StringBuilder and StringBuffer classes, you will ask the
students an In-Class question. This will help you in reviewing their understanding of the topic.
y
Which class does not perform synchronization?
Answer:
nl
StringBuilder class.
O
Tips:
Need for Synchronization - If your code is executing in multi-threaded environment, you
se
need synchronization for objects, which are shared among multiple threads, to avoid any
corruption of state or any kind of unexpected behavior.
rU
Synchronization in Java will only be needed if shared object is mutable. If your shared object is
either read only or immutable object, then you don't need synchronization, despite running
te
multiple threads. Same is true with what threads are doing with object if all the threads are only
reading value, then you don't require synchronization in Java. JVM guarantees that Java
en
©Aptech Limited
Slides 30 to 32
Let us understand parsing of text using StringTokenizer class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 30 to 32, explain parsing of text using StringTokenizer class.
se
There are different ways of parsing text:
String.split() method rU
StringTokenizer and StreamTokenizer classes
Scanner class
te
Pattern and Matcher classes, which implement regular expressions
For the most complex parsing tasks, tools such as JavaCC can be used
en
The StringTokenizer class belongs to the java.util package and is used to break a string
C
Then, explain the constructor and member methods of the StringTokenizer class as
mentioned in slides 30 and 31.
pt
A StringTokenizer object behaves in one of the following ways, depending on the value of the
returnDelims flag, when it was created:
rA
If the flag is false, delimiter characters serve to separate tokens. A token is a maximal sequence
Fo
Explain the Code Snippet that shows the use of StringTokenizer mentioned in slides 31 and
32.
©Aptech Limited
Slide 33
Let us understand regular expressions.
y
nl
O
se
Using slide 33, explain regular expressions.
rU
Regular expressions are used to describe a set of strings based on the common characteristics
shared by individual strings in the set. They are used to edit, search, or manipulate text and data.
te
In Java, one can use java.util.regex API to create regular expressions. A regular expression
en
is a special sequence of characters that helps you to match or fine other strings or sets of strings,
using a specialized syntax held in a pattern.
C
Tips:
Regular expressions are supported by many languages such as Perl, Python, PHP, and so on. They
h
are also the part of the shell commands such as grep, awk, and so on executed in the Linux
ec
environment. The syntax of the regular expressions provided in the java.util.regex API is
similar to Perl. It basically consist of three classes namely, Pattern, Matcher, and
pt
PatternSyntaxException.
rA
Fo
©Aptech Limited
Slides 34 and 35
Let us understand regular expression API.
y
nl
O
se
rU
te
en
C
h
ec
pt
There are primarily three classes in the java.util.regex package that are required for
creation of regular expression. They are as follows:
Pattern
Fo
Matcher
PatternSyntaxExpression
©Aptech Limited
In-Class Question:
After you finish explaining Regular Expression API, you will ask the students an In-Class question.
This will help you in reviewing their understanding of the topic.
Which of the following class acts as an engine that intercepts the pattern in the
java.util.regex package?
Answer:
Matcher
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 36
Let us understand Pattern class.
y
nl
O
se
Using slide 36, explain Pattern class.
rU
The Pattern class is the main access point of the Java regular expression API. Any regular
expression that is specified as a string must first be compiled into an instance of the Pattern
te
class. The resulting Pattern object can then be used to create a Matcher object. Once the
Matcher object is obtained, the Matcher object can then match arbitrary character sequences
en
against the regular expression. All the different state involved in performing a match resides in
the matcher, so several matchers can share the same pattern.
C
Tips:
ec
The fastest way to check if a regular expression pattern matches a text is to use the
static Pattern.matches() method.
pt
Following code snippet shows how to work with the Pattern class:
rA
String text = "This is the text to be searched for occurrences of the http://” +
“pattern.";
Fo
©Aptech Limited
Slides 37 to 42
Let us understand Matcher class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
A Matcher object is created from a pattern by invoking the matches() method on the
Pattern object. A Matcher object is the engine that performs the match operations on a
character sequence by interpreting a pattern.
Explain them that a Matcher object can be used to perform three different types of match
operations using the following methods:
y
The matches() method is used to match the entire input sequence against the pattern. You
nl
cannot use the matches() method to search for multiple occurrences of a regular
expression in a text. For that, you need to use the find(), start(), and end() methods.
O
The lookingAt() method is used to match the input sequence, from the beginning,
against the pattern. If the regular expression matches the beginning of a text, but not the
se
whole text, lookingAt() will return true, whereas matches() will return false.
rU
The find() method is used to scan the input sequence looking for the next subsequence
that matches the pattern. If multiple matches can be found in the text, the find() method
te
will find the first, and then for each subsequent call to find(), it will move to the next
match.
en
The return type of each of these methods is a boolean indicating success or failure. Additional
information about a successful match can be obtained by querying the state of the matcher.
C
Then, explain the list of important methods of the Matcher class mentioned in slide 38. Some of
h
provide useful index values that can be used to indicate exactly where the match was found in
rA
The methods start() and end() will give the indexes into the text where the found match
Fo
starts and ends. Actually, end() returns the index of the character just after the end of the
matching section. Thus, you can use the return values of start() and end() inside
a String.substring() call.
Following code snippet show how to search a pattern based on the string index:
String text = "This is the text which is to be searched for occurrences of” +
©Aptech Limited
String patternString = "is";
int count = 0;
while(matcher.find()) {
y
count++;
nl
System.out.println("found: " + count + " : "
O
+ matcher.start() + " - " + matcher.end());
se
}
reset() rU
The reset() method helps the matcher to be explicitly reset. If a new input sequence is
te
desired, the reset(CharSequence) method can be invoked. The reset operation on a
en
matcher discards its explicit state information and sets the append position to zero. Instances of
the Matcher class are not safe for use by multiple concurrent threads.
C
Group()
h
Imagine you are searching through a text for URL's, and you would like to extract the found URL's
out of the text. Of course you could do this with the start() and end() methods, but it is
ec
easier to do so with the group functions. Groups are marked with parentheses in the regular
expression. For example, (Hello).
pt
This regular expression matches the text, Hello. The parentheses are not part of the text that is
rA
matched. The parentheses mark a group. When a match is found in a text, you can get access to
the part of the regular expression inside the group.
Fo
Then, discuss the Code Snippet that shows the use of Pattern and Matcher for creating and
evaluating regular expressions mentioned in slides 40 to 42.
©Aptech Limited
In-Class Question:
After you finish explaining Matcher Class, you will ask the students an In-Class question. This
will help you in reviewing their understanding of the topic.
What is the use of the index methods provided in the Matcher class?
Answer:
It provides useful index values that can be used to indicate exactly where the match was found in
the input string.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 43
Let us understand String Literal.
y
nl
O
se
Using slide 43, explain String Literal.
rU
The most basic form of pattern matching supported by the java.util.regex API is the
match of a string literal. A String literal is a sequence of characters used by Java programmers to
te
populate String objects or display text to a user. The characters could be letters, numbers or
symbols and are enclosed within two quotation marks.
en
The match will succeed when the regular expression is found in the string. Note that in the
C
match, the start index is counted from 0. By convention, ranges are inclusive of the beginning
index and exclusive of the end index.
h
Each character in the string resides in its own cell, with the index positions pointing between each
ec
©Aptech Limited
Slide 44
Let us understand Metacharacters.
y
nl
O
se
Using slide 44, explain the metacharacters.
rU
This API also supports many special characters. This affects the way a pattern is matched. The
match still succeeds, even though the dot ‘.’ is not present in the input string. This is because the
te
dot is a metacharacter, that is, a character with special meaning as interpreted by the matcher.
en
For the matcher, the metacharacter ‘.’ stands for ‘any character’. This is why the match succeeds
in the example. The metacharacters supported by the API are: <([{\^-=$!|]})?*+.>
C
One can force metacharacters to be treated as an ordinary character in one of the following
ways:
h
ec
placed at any location within the expression. However, the \Q must comes first.
rA
Fo
©Aptech Limited
Slide 45
Let us understand Character classes.
y
nl
O
se
Using slide 45, explain the Character classes.
rU
The word ‘class’ in ‘Character class’ phrase does not mean a .class file. With respect to regular
expressions, a character class is a set of characters enclosed within square brackets. It indicates
te
the characters that will successfully match a single character from a given input string.
en
Explain the table which summarizes the supported regular expression constructs in ‘Character
Classes’ mentioned in slide 45.
C
The Character class provides an object wrapper for a char value. This is useful when you need to
treat a char value as an object. For example, there are number of utility methods that take a
h
reference to an Object as one of their arguments. You cannot specify a char value for one of
ec
these arguments, but you can provide a reference to a Character object that encapsulates the
char value.
pt
rA
Fo
©Aptech Limited
Slide 46
Let us understand Simple classes.
y
nl
O
se
Using slide 46, explain the Simple classes.
rU
This is the most basic form of a Character class. It is created by specifying a set of characters side-
by-side within square brackets. For example, the regular expression [fmc]at will match the
te
words ‘fat’, ‘mat’, or ‘cat’. This is because the class defines a Character class accepting either
en
©Aptech Limited
Slide 47
Let us understand Negation.
y
nl
O
se
Using slide 47, explain the Negation.
rU
Negation is used to match all characters except those listed in the brackets. The ‘^’
metacharacter is inserted at the beginning of the Character class to implement Negation.
te
The figure shows the use of Negation in slide 47.
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 48
Let us understand Ranges.
y
nl
O
se
Using slide 48, explain the Ranges.
rU
At times, it may be required to define a character class that includes a range of values, such as
the letters ‘a to f’ or numbers ‘1 to 5’. A range can be specified by simply inserting the ‘-’
te
metacharacter between the first and last character to be matched. For example, [a-h] or [1-5]
can be used for a range.
en
One can also place different ranges next to each other within the class in order to further expand
C
the match possibilities. For example, [a-zA-Z] will match any letter of the alphabet from a to z
(lowercase) or A to Z (uppercase).
h
It is a class to represent ranges of values. A range is defined to contain all the values between the
ec
minimum and maximum values, where the minimum or maximum value can be considered either
included or excluded from the range.
pt
A Range can be unbounded at either or both of its ends. An unbounded end is specified by
rA
passing null for the value of that end. A Range that unbounded at both of its ends represents a
range of all possible values for the Class of elements in that Range.
Fo
Tips:
Ranges define the boundaries around a contiguous span of values of some Comparable type, for
example, integers from 1 to 100 inclusive.
©Aptech Limited
Slide 49
Let us understand Unions.
y
nl
O
se
Using slide 49, explain the Unions.
rU
Unions can be used to create a single character class comprising two or more separate Character
classes. This can be done by simply nesting one class within the other. For example, the union
te
[a-d[f-h]] creates a single character class that matches the characters a, b, c, d, f, g, and h.
en
©Aptech Limited
Slide 50
Let us understand Intersections.
y
nl
O
se
Using slide 50, explain the Intersections.
rU
Intersection is used to create a single character class that matches only the characters which are
common to all of its nested classes. This is done by using the &&, such as in [0-6&&[234]]. This
te
creates a single character class that will match only the numbers common to both character
classes, that is, 2, 3, and 4.
en
©Aptech Limited
Slide 51
Let us understand Subtraction.
y
nl
O
se
Using slide 51, explain the Subtraction.
rU
Subtraction can be used to negate one or more nested character classes, such as [0-
6&&[^234]]. In this case, the character class will match everything from 0 to 6, except the
te
numbers 2, 3, and 4.
en
©Aptech Limited
Slide 52
Let us understand Pre-defined Character classes.
y
nl
O
se
rU
Using slide 52, explain Pre-defined Character classes.
Explain the table that lists the pre-defined character classes mentioned in slide 52.
te
The pattern API contains a number of useful pre-defined character classes, which offer
convenient shorthand for commonly used regular expressions. Pre-defined classes should be
en
used whenever possible. It makes the code easier to read and eliminate errors introduced by
malformed character classes.
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 53
Let us understand Quantifiers.
y
nl
O
se
Using slide 53, explain the Quantifiers.
rU
Quantifiers can be used to specify the number of occurrences to match against. At first glance, it
may appear that the quantifiers X?, X??, and X?+ do exactly the same thing, since they all
te
promise to match X, once or not at all. However, there are subtle differences so far as
implementation is concerned between each of these quantifiers.
en
Explain the table that shows the greedy, reluctant, and possessive quantifiers in slide 53.
C
Quantifiers enable you to match a given expression or sub expression multiple times. The *
h
character is a quantifier that means zero or more times. There is also a + quantifier meaning one
or more times and a ? quantifier meaning zero or one time.
ec
pt
rA
Fo
©Aptech Limited
Slide 54
Let us understand differences among the Quantifiers.
y
nl
O
se
Using slide 54, explain differences among the Quantifiers.
rU
Quantifiers can be either “reluctant”, “greedy”, or “possessive”. A reluctant quantifier will match
te
as little as possible of the input text. A greedy quantifier will match as much as possible of the
input text. A possessive quantifier will match as much as possible, even if it makes the rest of the
en
expression not match anything, and the expression to fail finding a match.
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 55
Let us understand about capturing groups.
y
nl
O
se
Using slide 55, explain about capturing groups.
rU
Capturing groups allows the programmer to consider multiple characters as a single unit. This is
done by placing the characters to be grouped inside a set of parentheses. For example, the
te
regular expression (bat) creates a single group. The group contains the letters ‘b’, ‘a’, and ‘t’.
en
The part of the input string that matches the capturing group will be saved in memory to be
recalled later using back references.
C
Capturing groups are an extremely useful feature of regular expression matching that allows us to
query the Matcher to find out what the part of the string was that matched against a particular
h
Tips:
pt
In advance use of capturing groups, there are exceptions where we can actually refer to a
captured group from inside the expression itself.
rA
Fo
©Aptech Limited
Slides 56 and 57
Let us understand Numbering.
y
nl
O
se
rU
te
en
C
h
ec
pt
Capturing groups are numbered by counting their opening parentheses from left to right. For
example, in the expression ((X)(Y(Z))), there are four such groups namely, ((X)(Y(Z))), (X), (Y(Z)),
and (Z).
Fo
The groupCount() method can be invoked on the matcher object to find out how many
groups are present in the expression. This method will return an int value indicating the number
of capturing groups present in the matcher’s pattern.
There is another special group, group 0, which always represents the entire expression. However,
this group is not counted in the total returned by groupCount(). Groups beginning with the
character ‘?’ are pure, non-capturing groups as they do not capture text and also do not count
towards the group total.
©Aptech Limited
Explain the Code Snippet which is an example of using groupCount() mentioned in slide 57.
A numbered capturing group groups the selected tokens together and stores their part of the
match in a numbered back reference. Numbered capturing groups are automatically numbered
from left to right, starting with number one.
In-Class Question:
After you finish explaining about the Numbering, you will ask the students an In-Class question.
This will help you in reviewing their understanding of the topic.
y
nl
What int value of groupCount() method indicate?
O
Answer:
The number of capturing groups present in the matcher’s pattern
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 58
Let us understand Backreferences.
y
nl
O
se
Using slide 58, explain the Backreferences.
rU
The portion of the input string that matches the capturing group(s) is saved in memory for later
recall with the help of backreference.
te
A backreference is specified in the regular expression as a backslash (\) followed by a digit
en
indicating the number of the group to be recalled. For example, the expression (\d\d) defines
one capturing group matching two digits in a row, which can be recalled later in the expression by
C
Explain the figure that shows an example for using backreferences mentioned in slide 58.
h
ec
For nested capturing group, backreferencing works in same way. Just specify a backslash followed
by the number of groups to be recalled.
pt
rA
Fo
©Aptech Limited
Slide 59
Let us understand boundary matchers.
y
nl
O
se
Using slide 59, explain the boundary matchers.
rU
Explain the table that lists the boundary matchers in slide 59.
te
You can make your pattern matches more precise by specifying such information with boundary
matchers. For example, you are interested in finding a particular word, but only if it appears at
en
the beginning or end of a line. Or maybe you want to know if the match is taking place on a word
boundary, or at the end of the previous match.
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 60
Let us understand additional methods of the Pattern class.
y
nl
O
se
Using slide 60, explain additional methods of the Pattern class.
rU
One can also use advanced techniques such as creating patterns with flags and using embedded
flag expressions. Also, one can use the additional useful methods of the Pattern class.
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 61
Let us understand creating a pattern with flags.
y
nl
O
se
Using slide 61, explain how to create a pattern with flags.
rU
The Pattern class provides an alternate compile() method that accepts a set of flags. These
flags affect the way the pattern is matched.
te
The flags parameter is a bit mask including any of the public static fields mentioned in
en
slide 61.
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 62
Let us understand embedded flag expressions.
y
nl
O
se
Using slide 62, explain embedded flag expressions.
rU
Embedded flag expressions can also be used to enable various flags. They are an alternative to
the two-argument version of compile() method. They are specified in the regular expression
te
itself.
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 63
Let us understand the matches(String CharSequence) method.
y
nl
O
se
Using slide 63, explain the matches(String CharSequence) method.
rU
The Pattern class defines the matches() method that allows the programmer to quickly
check if a pattern is present in a given input string. Similar, to all public static methods, the
te
matches() method is invoked by its class name, that is,
Pattern.matches(“\\d”,”1”);. In this case, the method will return true, because the
en
In-Class Question:
h
After you finish explaining the matches(String CharSequence) method, you will ask the
ec
students an In-Class question. This will help you in reviewing their understanding of the topic.
pt
rA
©Aptech Limited
Slides 64 to 66
Let us understand the split(String) method.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
The split() method of Pattern class is used for obtaining the text that lies on either side of
the pattern being matched.
©Aptech Limited
This method has two variants and splits this string around matches of the regular expression. The
parameters are regex which is the delimiting regular expression and the limit which is the result
threshold which means how many strings to be returned.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 67
Let us understand other useful methods.
y
nl
O
se
Using slide 67, explain other useful methods.
Returns the String representation of this pattern. This method returns itself a string. No
parameters are there.
h
ec
pt
rA
Fo
©Aptech Limited
Slides 68 and 69
Let us summarize the session.
y
nl
O
se
rU
te
en
C
h
ec
pt
Using slides 68 and 69, summarize the session. End the session with a brief summary of what has
been taught in the session.
rA
You should familiarize yourself with the topics of the next session which is Collections API.
Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the OnlineVarsity site to gain
additional information related to the topics covered in the next session. You can also connect to
online tutors on the Online Varsity site to ask queries related to the sessions.
©Aptech Limited
Session 3 – Collections API
Here, you can ask students the key topics they can recall from previous session. Prepare a question
or two which will be a key point to relate the current session objectives.
y
3.1.1 Objectives
nl
By the end of this session, the learners will be able to:
O
Explain java.util package
Explain List classes and interfaces
se
Explain Set classes and interfaces
Explain Map classes and interfaces
Explain Queues and Arrays
You should teach the concepts in the theory class using the images provided. For teaching in
the class, you are expected to use slides and LCD projectors.
C
Tips:
h
It is recommended that you test the understanding of the students by asking questions in
ec
In-Class Activities:
pt
©Aptech Limited
Overview of the Session:
Then give the students the overview of the current session in the form of session objectives.
Show the students slide 2 of the presentation.
y
nl
O
se
rU
Tell the students that this session introduces the Collection API which is a unified
architecture for representing and manipulating collections. The session also teaches the
concept of Queues and Arrays which are a collection for storing objects in Java.
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
3.2 In-Class Explanations
Slide 3
Let us understand the overview of the collection framework.
y
nl
O
se
rU
Using slide 3, explain the overview of the collection framework.
Tell them that before Java 2, Java API provided classes such as Dictionary, Vector, Stack,
te
and Properties to store and manipulate groups of objects. Although these classes were
quite useful, they lacked a central, unifying theme. Thus, the way that you used Vector was
en
With Java 2, the collections framework was designed to meet several goals that are as
follows:
Extending and/or adapting a collection had to be easy.
h
fundamental collections such as dynamic arrays, linked lists, trees, and hashtables are
highly efficient.
pt
The framework had to allow different types of collections to work in a similar manner
and with a high degree of interoperability.
rA
The collections framework consists of collection interfaces which are primary means by
collections are manipulated.
Fo
©Aptech Limited
Slide 4
Let us understand the java.util package.
y
nl
O
se
Using slide 4, explain the java.util package.
rU
The java.util package contains the definition of a number of useful classes providing a
broad range of functionality. The package mainly contains collection classes that are useful
te
for working with groups of objects.
en
The package also contains the definition of classes that provides date and time facilities and
many other utilities, such as calendar and dictionary. It also contains a list of classes and
C
Internationalization
Utility classes such as StringTokenizer, Random, and so on
rA
Fo
©Aptech Limited
Slide 5
Let us understand collections framework.
y
nl
O
se
Using slide 5, explain collections framework.
rU
A collection is a container that helps to group multiple elements into a single unit.
Collections help to store, retrieve, manipulate, and communicate data. The Collections
te
Framework represents and manipulates collections.
en
Java collections framework is a set of classes and interfaces that implement commonly
pt
reusable collection data structure. In this, the interfaces are the abstract data types that
represent the collection and the implementations are the concrete implementations of the
rA
collection interface. Algorithms are the methods that perform useful computations such as
searching and sorting on object that implements collection interface.
Fo
Tips:
The various implementations of each interface are interchangeable, so programs can be
easily tuned by switching collection implementations. Hence, Collections framework
provides high-performance and high-quality implementations of useful data structures and
algorithms.
©Aptech Limited
Slide 6
Let us understand collection interfaces.
y
nl
O
se
Using slide 6, explain collection interfaces.
rU
Collections framework consists of interfaces and classes for working with group of objects.
At the top of the hierarchy, Collection interface lies. The collection interface helps to
te
convert the collection’s type.
en
The core collection interfaces that provide different types of collections are shown in the
following figure:
C
h
ec
pt
rA
Fo
These interfaces are the foundation to the Java collections framework and are implemented
in the collections framework to help the programmers to create and use the collection
easily.
©Aptech Limited
Some of the implemented collection classes are as follows:
HashSet
LinkedHashSet
TreeSet
Tips:
y
The description of the core collection interfaces are as follows:
nl
Collection — The root of the collection hierarchy. A collection represents a group of
objects known as its elements. The Collection interface is the least common
O
denominator that all collections implement and is used to pass collections around and to
manipulate them when maximum generality is desired.
se
Some types of collections allow duplicate elements, and others do not. Some are
ordered and others are unordered. The Java platform doesn't provide any direct
rU
implementations of this interface but provides implementations of more specific sub
interfaces, such as Set and List.
te
Set — A collection that cannot contain duplicate elements. This interface models the
mathematical set abstraction and is used to represent sets, such as the cards comprising
en
a poker hand, the courses making up a student's schedule, or the processes running on a
machine.
C
where in the list each element is inserted and can access elements by their integer index
ec
(position). If you've used Vector, you're familiar with the general flavor of List.
©Aptech Limited
Slide 7
Let us understand methods of Collection Interface.
y
nl
O
se
Using slide 7, explain methods of Collection Interface.
rU
The Collection interface is used to pass around collections of objects.
te
The Collection interface provides methods that perform basic operations on the
en
iterator().
h
The add method is defined so that it makes sense for collections that allow duplicates as
well as those that don't. It guarantees that the Collection will contain the specified
pt
Similarly, the remove method is designed to remove a single instance of the specified
element from the Collection, assuming that it contains the element to start with. It
return true, if the Collection was modified as a result.
Fo
Tips:
It also contains methods that operate on entire collections, such as boolean
containsAll(Collection<?> c),boolean addAll(Collection<?
extends E> c), boolean removeAll(Collection<?> c), boolean
retainAll(Collection<?> c), and void clear().
©Aptech Limited
Slides 8 and 9
Let us understand traversing the collections.
y
nl
O
se
rU
te
en
C
h
ec
pt
Explain the code that illustrates the use of the for-each construct to print out each
element of a collection on a separate line.
©Aptech Limited
Using Iterator
These help to traverse through a collection. They also help to remove elements from the
collection selectively. The iterator() method is invoked to obtain an Iterator for a
collection.
Use Iterator instead of for-each construct when you need to remove the current
element. The for-each construct hides the iterator so you cannot call remove method.
y
Also iterator can be used to iterate over multiple collections in parallel.
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 10
Let us understand bulk operations.
y
nl
O
se
Using slide 10, explain bulk operations.
rU
Bulk operations perform shorthand operations on an entire Collection using the basic
operations.
te
en
Explain the table that describes the methods for bulk operations in slide 10.
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 11
Let us understand the List interface.
y
nl
O
se
Using slide 11, explain the List interface.
rU
Tell the students that a List is an ordered Collection (sometimes called a sequence). The
List interface extends Collection and declares the behavior of a collection that stores
te
a sequence of elements.
The features of List interface are as follows:
en
Elements can be inserted or accessed by their position in the list, using a zero-based
C
index.
The List interface uses an index for ordering the elements while storing them in a list. It
has methods that allow access to elements based on their position, search for a specific
element, and return their position, in addition to performing arbitrary range operations. It
pt
also provides the List iterator to take advantage of its sequential nature.
rA
The Java platform contains two general purpose List implementations. ArrayList,
which is usually the better-performing implementation, and LinkedList which offers
better performance under certain circumstances.
Fo
©Aptech Limited
Slide 12
Let us understand methods of the List interface.
y
nl
O
se
Using slide 12, explain methods of the List interface.
rU
The List interface uses an index for ordering the elements while storing them in a list. In
addition to the operations inherited from Collection, the List interface includes
te
operations for the following:
en
Positional access — Manipulates elements based on their numerical position in the list.
This includes methods such as get, set, add, addAll, and remove.
C
Search — Searches for a specified object in the list and returns its numerical position.
Search methods include indexOf and lastIndexOf.
Iteration — Extends Iterator semantics to take advantage of the list's sequential
h
Range-view — The subList method performs arbitrary range operations on the list.
pt
Next, explain the methods of the List interface. The methods supported by the List
interface are as follows:
rA
the list.
public void add(int index, Object o)
©Aptech Limited
get(int index)
The method retrieves element from the specified index position.
public Object get(int index)
remove(int index)
y
The method removes the element at given index position from the list.
nl
public Object remove(int index)
O
subList(int start, int end)
The method returns a list containing elements from start to end –1 of the invoking list.
se
public List subList(int start, int end)
indexOf(Object o)
rU
The method returns the index of the first occurrence of the specified element in the list,
or returns -1, in case the list does not contain the given element.
public int indexOf(Object o)
te
en
lastIndexOf(Object o)
The method returns the index of the last occurrence of the specified element in the list,
or returns -1, in case the list does not contain the given element.
C
©Aptech Limited
Slides 13 and 14
Let us understand the ArrayList class.
y
nl
O
se
rU
te
en
C
h
ec
pt
Tell the students that the java.util.ArrayList class provides resizable-array and
implements the List interface.
Fo
The list cannot store primitive values such as double. In Java, standard arrays are of fixed length
and they cannot grow or reduce its size dynamically. Array lists are created with an initial size.
Later, as the elements are added, the size increases and the array grow as needed.
The ArrayList class includes all elements, including null. In addition to implementing the
methods of the List interface, this class provides methods to change the size of the array that
is used internally to store the list.
©Aptech Limited
ArrayList class is best suited for random access without inserting or removing elements
from any place other than the end.
An instance of ArrayList can be created using any one of the following constructors:
ArrayList()
The constructor creates an empty list having an initial capacity of 10.
ArrayList(int initialCapacity)
y
The constructor creates an empty array list with the specified capacity. The size will grow
nl
automatically as elements are added to the array list.
O
Explain the Code Snippet that displays the creation of an instance of the ArrayList class
in slide 14.
se
The ArrayList object is created and the first 10 numbers are added to the list as objects.
The primitive int data type is wrapped by the respective wrapper class.
Tips:
rU
It implements all optional list operations and permits all elements, including null. In addition
te
to implementing the List interface, this class provides methods to manipulate the size of
the array that is used internally to store the list.
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 15
Let us understand methods of the ArrayList class.
y
nl
O
se
Using slide 15, explain methods of the ArrayList class.
add(E obj)
rU
te
The method adds a specified element to the end of this list.
Syntax:
public boolean add(Object E obj)
en
trimToSize()
C
The method trims the size of the ArrayList to the current size of the list.
Syntax:
public void trimToSize()
h
ec
ensureCapacity(int minCap)
The method is used to increase the capacity of the ArrayList and ensures that it can
hold the least number of specified elements.
pt
Syntax:
public void ensureCapacity(int minCap)
rA
clear()
The method removes all the elements from this list.
Fo
Syntax:
public void clear()
contains(Object obj)
The method returns true if this list contains the specified element.
Syntax:
public boolean contains(Object obj)
©Aptech Limited
size()
The method returns the number of elements in this list.
Syntax:
public int size()
Explain the Code Snippet that displays the use of ArrayList class in slide 15. In the code,
an empty ArrayList object is created and the initial size of the ArrayList object is
printed. Then, objects of type String are added to the ArrayList and the element present
at the fifth position is replaced with the specified element and displayed using the get()
method.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 16 to 18
Let us understand the Vector class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 16 to 18, explain the Vector class.
se
The Vector class is similar to an ArrayList as it also implements dynamic array.
Vector class stores an array of objects and the size of the array can increase or decrease.
rU
The elements in the Vector can be accessed using an integer index.
The difference between Vector and ArrayList class is that, the methods of Vector are
C
synchronized and are thread-safe. This increases the overhead cost of calling these methods.
Unlike ArrayList, Vector class also contains legacy methods which are not part of
h
Collections framework.
ec
The constructor creates an empty vector with an initial array size of 10.
public Vector()
rA
The elements are stored in the order it was returned by the collection’s iterator.
public Vector(Collection<? extends E> c)
Vector(int initCapacity)
The constructor creates an empty vector whose initial capacity is specified in the
variable initCapacity.
public Vector(int initCapacity)
©Aptech Limited
Vector(int initCapacity, int capIncrement)
The constructor creates a vector whose initial capacity and increment capacity is
specified in the variables, initCapacity and capIncrement respectively.
public Vector(int initCapacity, int capIncrement)
Following Code Snippet displays the creation of an instance of the Vector class:
. . .
Vector vecObj = new Vector();
. . .
y
Explain the Code Snippet that displays the use of the Vector class in slide 18.
nl
The Vector class implements a growable array of objects. It contains components that can
O
be accessed using an integer index. However, the size of Vector can grow or shrink as
needed to accommodate adding and removing items after the Vector has been created.
se
The important methods in the Vector class are as follows:
addElement(E obj) rU
The method adds an element at the end of the vector and increases the size of the
Vector by 1. The capacity of the Vector increases if the size is greater than capacity.
te
public void addElement(E obj)
en
capacity()
The method returns the capacity of the vector.
public int capacity()
C
toArray()
h
The method returns an array containing all the elements present in the Vector, in
ec
correct order.
public Object[] toArray()
pt
elementAt(int pos)
The method retrieves the object stored at the specified location.
rA
removeElement(Object obj)
Fo
The method removes the first occurrence of the specified object from the vector.
public boolean removeElement(Object obj)
clear()
The method removes all the elements.
public void clear()
©Aptech Limited
Slides 19 and 20
Let us understand the LinkedList class.
y
nl
O
se
rU
te
en
C
h
ec
pt
LinkedList class implements the List interface. An array stores objects in consecutive
memory locations, whereas a linked list stores object as a separate link. It provides a linked
Fo
A linked list is a list of objects having a link to the next object. There is usually a data
element followed by an address element that contains the address of the next element in
the list in a sequence. Each such item is referred as a node.
Linked lists allow insertion and removal of nodes at any position in the list, but do not allow
random access. There are several different types of linked lists - singly-linked lists, doubly-
linked lists, and circularly-linked lists.
©Aptech Limited
Java provides the LinkedList class in the java.util package to implement linked
lists.
LinkedList():
The LinkedList() constructor creates an empty linked list.
y
nl
Explain the code snippet that displays the creation of an instance of the LinkedList class
in slide 20.
O
In-Class Question:
After you finish explaining LinkedList class, you will ask the students an In-Class
se
question. This will help you in reviewing their understanding of the topic.
rU
What are the different types of linked lists?
te
Answer:
en
singly-linked lists
C
doubly-linked lists
circularly-linked lists
h
ec
pt
rA
Fo
©Aptech Limited
Slide 21
Let us understand methods of the LinkedList class.
y
nl
O
se
Using slide 21, explain methods of the LinkedList class.
addFirst(E obj)
rU
te
This method adds the given object at the beginning of the list.
Syntax:
en
addLast(E obj)
This method appends the given object at the end of the list.
h
ec
Syntax:
public Object addLast(E obj)
pt
getFirst()
rA
getLast()
The method retrieves the last element from the list.
Syntax:
public E getLast()
©Aptech Limited
removeFirst()
The method removes and returns the first element from the list.
Syntax:
public E removeFirst()
removeLast()
The method removes and returns the last element from the list.
Syntax:
y
public E removeLast()
nl
Explain the Code Snippet that displays the use of the methods of the LinkedList class in
O
slide 21.
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 22
Let us understand autoboxing and unboxing.
y
nl
O
se
Using slide 22, explain autoboxing and unboxing.
rU
The autoboxing and unboxing feature automates the process of using primitive value into a
collection. Note that collections hold only object references. So, primitive values, such as int
te
from Integer, have to be boxed into the appropriate wrapper class.
en
If an int value is required, the integer value must be unbox using the intValue()
method. The autoboxing and unboxing feature helps to reduce the clutter in the code.
C
The automatic conversion of primitive data types into its equivalent wrapper type is known
as boxing and opposite operation is known as unboxing. This is a feature where Java
h
Autoboxing and unboxing allow developers to write cleaner code, making it easier to read.
pt
rA
Fo
©Aptech Limited
Slide 23
Let us understand the Set interface.
y
nl
O
se
Using slide 23, explain the Set interface.
rU
The Set interface creates a list of unordered objects. It models the mathematical set
abstraction and does not contain duplicate elements in the collection. The Set interface
te
inherits all the methods from the Collection interface, except those methods that allow
duplicate elements.
en
The Java platform contains three general-purpose Set implementations. They are as
C
follows:
h
HashSet - HashSet stores its elements in a Hashtable, and does not guarantee the
order of iteration.
ec
TreeSet - TreeSet stores its elements in a tree, and orders its elements based on
their values.
pt
elements and thus, is different from HashSet. Linked list iterates through the elements in
the orders in which they were inserted into the set (insertion-order).
Fo
Next, explain the difference between List and Set is that, the Set does not permit
duplication of elements. Set is used to create non-duplicate list of object references.
Therefore, add() method returns false if duplicate elements are added.
Great care must be exercised if mutable objects are used as set elements. The behavior of a
set is not specified, if the value of an object is changed in a manner that affects equals
comparisons while the object is an element in the set. It is not permissible foe a set to
contain itself as an element.
©Aptech Limited
Slide 24
Let us understand methods of the Set interface.
y
nl
O
se
Using slide 24, explain methods of the Set interface.
rU
Tell the students that the Set interface is best suited for carrying out bulk operations. The bulk
operation methods supported by the Set interface are to be explained to the students in
te
details.
en
containsAll(Collection<?> obj)
This method returns true if the invoking set object contains all the elements of the
h
specified collection.
ec
retainAll(Collection<?> obj)
This method retains in the invoking set only those elements which are contained in the
specified collection.
Syntax: public boolean retainAll(Collection<?> obj)
©Aptech Limited
removeAll(Collection<?> obj)
This method removes all the elements from the invoking set that are contained in the
specified collection.
Syntax: public boolean removeAll(Collection<?> obj)
Tips:
Two Set instances are considered equal when they contain the same elements.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 25 and 26
Let us understand the SortedSet interface.
y
nl
O
se
rU
te
en
C
h
ec
pt
The SortedSet interface extends the Set interface and its iterator traverses its elements
in the ascending order. Elements can be ordered by natural ordering, or by using a
Fo
SortedSet is used to create sorted lists of non-duplicate object references. The ordering
of a sorted set should be consistent with equals() method. A sorted set performs all
element comparisons using the compareTo() or compare() method.
©Aptech Limited
In addition to the normal Set operations, the SortedSet interface provides operations for
the following:
Range view — allows arbitrary range operations on the sorted set
Endpoints — returns the first or last element in the sorted set
Comparator access — returns the Comparator, if any, used to sort the set
Typically, sorted set implementation classes provide the following standard constructors:
No argument (void) constructor
Single argument of type Comparator constructor
Single argument of type Collection constructor
y
Single argument of type SortedSet constructor
nl
O
Some of the methods in this interface are as follows:
first()
last()
se
headSet(E endElement)
subSet(E startElement, E endElement)
tailSet(E fromElement)
rU
te
Several methods of SortedSet throw a NoSuchElementException when no items
are contained in the invoking set. Another exception which is ClassCastException is
en
©Aptech Limited
Slide 27
Let us understand the HashSet class.
y
nl
O
se
Using slide 27, explain the HashSet class.
rU
HashSet class implements the Set interface and creates a collection that makes use of a
hash table for data storage. This HashSet class allows null element. The HashSet class
te
provides constant time performance for the basic operations.
en
The constructor creates a hash set based on the elements given in the specified collection.
HashSet(int size)
ec
The constructor builds a hash set with given size and fill ratio. A fill ratio determines how full
the set can be before it is resized upward.
rA
Explain the Code Snippet that displays the creation of an instance of HashSet class in slide
27.
Fo
Tips:
Hash table stores information by using a mechanism known hashing. In hashing, the
informational content of a key is used to determine a unique value called hash code.
This class makes no guarantees as to the iteration order of the set; in particular, it does not
guarantee that the order will remain constant over time. This class permits null element.
©Aptech Limited
Slide 28
Let us understand the LinkedHashSet class.
y
nl
O
se
Using slide 28, explain the LinkedHashSet Class.
rU
LinkedHashSet class creates a list of elements and maintains the order of the elements
added to the set. This class includes the following features:
te
It provides all of the optional Set operations.
It permits null elements.
en
It provides constant-time performance for the basic operations such as add and
remove.
C
specified collection.
LinkedHashSet(int initial capacity)
rA
The constructor constructs a new, empty linked hash set with the specified initial
capacity.
Fo
LinkedHashSet maintains a linked list of the entries in the set, in the order in which they
were inserted. This allows insertion-order iteration over the set. That is, when cycling
through a LinkedHashSet using an iterator, the elements will be returned in the order in
which they are inserted.
The hash code is then used as the index at which the data associated with the key is stored.
The transformation of the key into its hash code is perform automatically.
©Aptech Limited
Slide 29
Let us understand the TreeSet class.
y
nl
O
se
Using slide 29, explain the TreeSet class.
rU
TreeSet class implements the NavigableSet interface and uses a tree structure for
data storage. The elements can be ordered by natural ordering or by using a Comparator
te
provided at the time of Set creation. Objects are stored in ascending order and therefore
en
TreeSet is used when elements needs to be extracted quickly from the collection in a
C
sorted manner.
h
The constructor creates an empty tree set with the elements sorted in ascending order.
TreeSet(Collection<? extends E> c)
pt
The constructor creates a new tree set containing the elements of the specified
collection, sorted according to the elements order.
rA
TreeSet(SortedSet s)
The constructor creates a new tree set containing the elements of the specified
SortedSet in the same order.
Explain the Code Snippet that creates an instance of TreeSet in slide 29. Access and
retrieval times are quite fast which makes TreeSet an excellent choice, when storing large
amounts of sorted information that must be found quickly. TreeSet class is not
synchronized.
©Aptech Limited
Slide 30
Let us understand the Map interface.
y
nl
O
se
Using slide 30, explain the Map interface.
rU
A Map is an object that maps keys to values. A map cannot contain duplicate keys. Each key
can map to at most one value.
te
A Map object stores data in the form of relationships between keys and values. Each key
en
map to at least a single value. If key information is known, its value can be retrieved from
the Map object. Keys should be unique, but values can be duplicated. The Map interface
C
Maps have their own hierarchy, for maintaining the key-value associations. The interface
describes a mapping from keys to values, without duplicate keys.
ec
HashMap
TreeMap
rA
HashMap is used for inserting, deleting, and locating elements in a Map. TreeMap is
used to arrange the keys in a sorted order.
Fo
©Aptech Limited
A NullPointerException is thrown, if an attempt is made to use a null object and
null is not allowed in the map.
An UnsupportedOperationException is thrown, when an attempt is made to
change an unmodifiable map.
y
nl
get(Object key)
The method returns the value associated with the given key in the invoking map object.
O
V get(Object key)
se
containsKey(Object key)
The method returns true if this map object contains a mapping for the specified key.
public boolean containsKey(Object key)
containsValue(Object value) rU
The method returns true if this map object maps one or more keys to the specified
te
value.
public boolean containsValue(Object value)
en
size()
The method returns the number of key-value mappings in this map.
C
values()
The method returns a collection view of the values contained in this map.
ec
Collection<V> values()
pt
rA
Fo
©Aptech Limited
Slides 31 to 34
Let us understand the HashMap class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
rU
te
en
C
h
ec
The HashMap class implements the Map interface and inherits all its methods. An instance
pt
of HashMap has two parameters, initial capacity and load factor. Initial capacity determines
rA
the number of objects that can be added to the HashMap, at the time of the hash table
creation. The load factor determines how full the hash table can get, before its capacity is
automatically increased.
Fo
The HashMap is very similar to the Hashtable with two main differences:
The HashMap is not synchronized making access faster.
The HashMap allows null values to be used as values or keys, which are disallowed in
the Hashtable implementation. HashMap class does not guarantee the order of
the map and it does not guarantee that the order will remain constant over time.
©Aptech Limited
The constructors of this class are as follows:
HashMap()
The constructor constructs an empty HashMap with the default initial capacity and load
factor of 17 and 0.75 respectively.
HashMap(int initialCapacity)
The constructor constructs an empty HashMap with the specified initial capacity and
default load factor of 0.75.
HashMap(int initialCapacity, float loadFactor)
The constructor constructs an empty HashMap with the specified initial capacity and load
factor.
HashMap(Map<? extends K,? extends V> m)
y
The constructor constructs a HashMap similar to the specified map m.
nl
Explain the Code Snippet that displays the use of the HashMap class in slides 32 to 34. Tell
O
the students that in the code snippet, an EmployeeData class and a MapTest class is
created. In the MapTest class, an instance of HashMap class is created. In the HashMap
se
object, data of the EmployeeData class is added, removed, and retrieved.
In-Class Question:
rU
After you finish explaining HashMap class, you will ask the students an In-Class question.
This will help you in reviewing their understanding of the topic.
te
en
Answer:
Initial capacity
h
Load factor
ec
pt
rA
Fo
©Aptech Limited
Slides 35 and 36
Let us understand the Hashtable class.
y
nl
O
se
rU
te
en
C
h
ec
pt
Tell the students that Hashtable was part of the original java.util and is a concrete
implementation of a Dictionary.
Fo
However, in Java 2, Hashtable was upgraded, so that it also implements the Map interface.
Thus, Hashtable is now integrated into the Collections framework. It is similar to HashMap,
but is synchronized.
The Hashtable class implements the Map interface but stores elements as a key/value
pairs in the hash table. While using a Hashtable, a key is specified to which a value is
linked. The key is hashed and then the hash code is used as an index at which the value is
stored. The class inherits all the methods of the Map interface.
©Aptech Limited
To retrieve and store objects from a hash table successfully, the objects used as keys must
implement the hashCode() and equals() methods.
y
Hashtable(Map<? extends K, ? extends V> m)
nl
The constructor constructs a new hash table containing the same entries as the given Map.
O
Explain the Code Snippet that displays the use of the Hashtable class in slide 36. The
put() and get() methods are used to insert and retrieve values from the hash table.
se
The isEmpty() method checks whether the hash table is empty and the
containsKey() method is used to check whether a particular key exists or not.
rU
To obtain all the book details, an Enumeration object is used. The keys are retrieved by
using the nextElement() method of the Enumeration interface and later, using the
keys, the value associated with each key are retrieved.
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 37 and 38
Let us understand the TreeMap class.
y
nl
O
se
rU
te
en
C
h
ec
pt
A TreeMap provides an efficient means of storing key/value pairs in sorted order and
allows rapid retrieval. If there is no need to retrieve Map elements sorted by key, then the
Fo
©Aptech Limited
TreeMap(Comparator<? super K> c)
The constructor constructs a tree map, where the keys are sorted according to the given
comparator.
TreeMap(Map<? extends K,? extends V> m)
The constructor constructs a new tree map containing the same entries as the given
map m.
TreeMap(SortedMap<K,? extends V> m)
The constructor constructs a new tree map containing the same entries as the given
SortedMap and uses the same comparator as the given SortedMap.
Next, explain the methods of the TreeMap class. The important methods of the TreeMap
y
class are as follows:
nl
firstKey()
The method returns the first key in this sorted map.
O
public K firstKey()
lastKey()
se
The method returns the last key in this sorted map.
public K lastKey()
headMap(K toKey)
Explain the Code Snippet that displays the use of the TreeMap class in slide 38. Data is
h
added in the TreeMap and retrieved. The function firstKey() and lastKey() is used
to obtain the first and the last key.
ec
pt
rA
Fo
©Aptech Limited
Slide 39
Let us understand the LinkedHashMap class.
y
nl
O
se
Using slide 39, explain the LinkedHashMap class.
rU
LinkedHashMap class extends HashMap and maintains a linked list of the entries in the
map, in the order in which they were inserted.
te
This allows insertion-order iteration over the map. That is, when iterating a
en
LinkedHashMap, the elements will be returned, in the order in which they were inserted.
One can also create a LinkedHashMap that returns its elements, in the order in which
C
In other words, LinkedHashMap class implements the concept of hash table and the
h
linked list in the Map interface. Since, LinkedHashMap maintains the values in the order
ec
they were inserted, so that the key/values will be returned in the same order that they were
added to this Map.
pt
LinkedHashMap()
The constructor creates an empty LinkedHashMap with the default capacity and
load factor of 16 and 0.75 respectively.
Fo
LinkedHashMap(int initialCapacity)
The constructor creates an empty LinkedHashMap with the user-defined initial
capacity.
LinkedHashMap(int initialCapacity, float loadFactor)
The constructor creates an empty LinkedHashMap with the user-defined initial
capacity and load factor.
©Aptech Limited
LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)
The constructor creates an empty LinkedHashMap with the user-defined initial
capacity, load factor, and ordering mode. The variable accessOrder defines the
ordering mode. A boolean value of true specifies that the ordering mode is based on
access-order, and false specifies that ordering mode is based on insertion-order.
LinkedHashMap(Map<? extends K,? extends V> m)
The constructor creates a LinkedHashMap with the same mappings as the
specified map and whose ordering mode is based on insertion-mode.
Next, explain the methods of this class. The important methods in LinkedHashMap class
y
are as follows:
clear()
nl
The method removes all mappings from the invoking map.
O
public void clear()
containsValue(Object value)
The method returns true if the invoking map maps one or more keys to the specified
se
value.
public boolean containsValue(Object value)
get(Object key)
rU
The method returns the value to which the key is mapped.
public V get(Object key)
te
removeEldestEntry(Map.Entry<K, V> eldest)
The method returns true if the map should remove its eldest key.
en
In-Class Question:
After you finish explaining the features and functionalities of LinkedHashMap class, you
h
will ask the students an In-Class question. This will help you in reviewing their understanding
of the topic.
ec
pt
Answer:
Map interface
Fo
©Aptech Limited
Slide 40
Let us understand the Stack interface.
y
nl
O
se
Using slide 40, explain the Stack interface.
rU
In the Stack class, the stack of objects results in a Last-In-First-Out (LIFO) behavior. It
extends the Vector class to consider a vector as a stack.
te
Stack only defines the default constructor that creates an empty stack. It includes all the
en
empty(): This tests if the stack is empty and returns a boolean value of true and false.
peek(): This views the object at the top of the stack without removing it from the stack.
ec
pop(): This removes the object at the top of this stack and returns that object as the value
of the function.
pt
stack.
stack.push("1");
stack.push("2");
stack.push("3");
©Aptech Limited
// Look at top object ("3"), without taking it off the stack.
Object obj3 = stack.pop(); //the string "3" is at the top of the stack.
Object obj2 = stack.pop(); //the string "2" is at the top of the stack.
Object obj1 = stack.pop(); //the string "1" is at the top of the stack.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 41
Let us understand the Queue Interface.
y
nl
O
se
Using slide 41, explain the Queue Interface.
rU
Tell the students that a Queue is a collection for holding elements prior to processing.
Besides basic Collection operations, queues provide additional insertion, removal, and
te
inspection operations.
en
In Queue, the elements are normally ordered in First In First Out (FIFO) order. The priority
queue orders the element according to their values. A queue can be arranged in other
C
orders too. Queues support the standard collection methods and also provide additional
methods to add, remove, and review queue elements.
h
Whatever ordering is used, the head of the queue is the element that would be removed by
ec
a call to remove or poll. In a FIFO queue, all new elements are inserted at the tail of the
queue. Other kinds of queues may use different placement rules. Every Queue
pt
It is possible for a Queue implementation to restrict the number of elements that it holds;
such queues are known as bounded. Some Queue implementations in
java.util.concurrent are bounded, but the implementations in java.util are
Fo
not.
©Aptech Limited
peek()
The method returns the value of the head of the queue, but does not remove the
head from the queue. The method returns null if the queue is empty.
E peek()
remove()
The method returns the value of the head of the queue and removes the head from
the queue. It throws an exception if the queue is empty.
E remove()
offer(E obj)
The method inserts the specified element into the queue and returns true, if it was
y
possible to add the element, else it returns false.
public boolean offer(E obj)
nl
element()
O
The method returns the value of the head of the queue, but does not remove the
head from the queue. The method throws an exception if the queue is empty.
E element()
se
Tips:
rU
Each Queue method exists in two forms: (1) one throws an exception if the operation fails,
and (2) the other returns a special value if the operation fails (either null or false, depending
on the operation).
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 42
Let us understand Deque.
y
nl
O
se
Using slide 42, explain Deque.
rU
A double ended queue is commonly called deque. It is a linear collection that supports
insertion and removal of elements from both ends. Usually, Deque implementations have
te
no restrictions on the number of elements to include.
en
A deque when used as a queue results in FIFO behavior. The Deque interface and its
implementations when used with the Stack class provides a consistent set of LIFO stack
C
operations.
In-Class Question:
pt
After you finish explaining Deque, you will ask the students an In-Class question. This will
help you in reviewing their understanding of the topic.
rA
Fo
Tips:
Deque interface does not provide support for indexed access to elements.
©Aptech Limited
Slides 43 to 45
Let us understand the PriorityQueue class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 43 to 45, explain the PriorityQueue class.
se
Tell the students that the priority queues are similar to queues, but the elements are not
arranged in FIFO structure. They are arranged in a user-defined manner. The elements are
rU
ordered either by natural ordering or according to a comparator. A priority queue neither
allows adding of non-comparable objects nor does it allow null elements. A priority queue is
unbound and allows the queue to grow in capacity.
te
The java.util.PriorityQueue class is an unbounded priority queue based on a
en
priority heap.
C
comparable objects.
rA
©Aptech Limited
PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
The constructor creates a PriorityQueue with the specified initial capacity that
orders its elements according to the specified comparator.
PriorityQueue(PriorityQueue<? extends E> c)
The constructor creates a PriorityQueue containing elements from the specified
collection. The initial capacity of the queue is 110% of the size of the specified collection.
PriorityQueue(SortedSet<? extends E> c)
The constructor creates a PriorityQueue containing the elements from the
specified collection. The initial capacity of the queue is 110% of the size of the specified
collection or 1 if the collection is empty.
y
nl
Then, explain the methods of the PriorityQueue class.
add(E e)
O
The method adds the specific element to the priority queue and returns a boolean value.
clear()
The method removes all elements from the priority queue.
se
comparator()
The method returns the comparator used to order this collection. The method will
contains(Object o) rU
return null if this collection is sorted according to its elements natural ordering.
The method returns a boolean value of true if the queue contains the specified
te
element.
iterator()
en
Explain the Code Snippet that displays the use of the PriorityQueue class in slide 45. In
h
the code snippet, a PriorityQueue instance is created which will store String
objects. The offer() method is used to add elements to the queue. The poll() and
ec
remove() methods are used to retrieve and return the values from the queue. The
peek() method retrieves the value but does not remove the head of the queue. When at
pt
the end, the element() method is used to retrieve the value, an exception is raised as
the queue is empty.
rA
Fo
©Aptech Limited
Slide 46
Let us understand the Arrays class.
y
nl
O
se
Using slide 46, explain the Arrays class.
rU
Tell the students that the java.util.Arrays class contains a static factory that allows
arrays to be viewed as lists.
te
Following are the important points about Arrays:
en
This class contains various methods for manipulating arrays (such as sorting and
searching).
C
Arrays class provides a number of methods for working with arrays such as searching,
ec
sorting, and comparing arrays. The class has a static factory method that allows the array to
be viewed as lists. The methods of this class throw an exception if the array reference is null.
pt
Each of the methods that are listed has an overloaded version that differs according to the
type of the array or array arguments.
rA
The method compares two specified arrays of the same type for equality. The method
returns true if each array holds the same number of elements and each element in the
first array is equals to the corresponding value in the second array. There is one method
of this type for each primitive data type and for Object.
public static boolean equals(byte[] a, byte[] b)
©Aptech Limited
fill(<type>[] array, <type> value)
The method initializes an array by assigning the specified value to all elements in the
array. There is one method of this type for each primitive data type and for Object.
public static void fill(boolean[] a, boolean v)
y
sort(<type>[] array)
nl
The method sorts the array in ascending order. There is no sort for boolean data types.
public static void sort(byte[] a)
O
sort(<type> [] array, int startIndex, int endIndex)
se
The method sorts the elements in the array between the given indices.
void sort(boolean[] array, int startIndex, int endIndex)
toString()
rU
The method returns a string representation of the contents of an array.
public String toString()
te
In-Class Question:
en
After you finish explaining features and functionalities of Queues and Arrays in Java,
you will ask the students an In-Class question. This will help you in reviewing their
C
Answer:
pt
©Aptech Limited
Slide 47
Let us understand about sorting the collections.
y
nl
O
se
Using slide 47, explain about sorting the collections.
rU
Collection API provides the following two interfaces for ordering interfaces:
te
Comparable: The Comparable interface imposes a total ordering on the objects of
each class which implements it. Lists of objects implementing this interface are
en
This interface defines the method compare which performs pairwise comparison of the
h
elements and returns -1 if the element is smaller than the compared element, and
return 0 if it is equal, and 1 if it is larger.
ec
Comparator: This interface provides multiple sorting options and imposes a total
pt
In-Class Question:
After you finish explaining sorting the collections, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
Fo
Answer:
Comparator
©Aptech Limited
Slides 48 to 58
Let us understand enhancements in collection classes.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
ArrayDeque
The ArrayDeque class implements the Deque interface. This class is faster than stack and
linked list when used as a queue. It does not put any restriction on capacity and does not
allow null values. It does not allow simultaneous access by multiple threads.
Explain the Code Snippet that shows the use of some of the methods available in the
ArrayDeque class in slides 48 and 49. The code creates an ArrayDeque instance, adds
elements to it and then traverses in forward and backward directions. The methods,
getFirst() and getLast() retrieve the first and the last elements, Banana and
Apple respectively. The contains() method checks whether the ArrayDeque
y
contains the element, Apple and returns true after finding the specified element.
nl
ConcurrentSkipListSet
O
The ConcurrentSkipListSet class implements the NavigableSet interface. The
se
elements are sorted based on natural ordering or by a Comparator. It provides methods
to return iterators in ascending or descending order. It also provides methods to return the
closest matches of elements in a collection.
rU
Explain the Code Snippet that shows the use of some of the methods available in
ConcurrentSkipListSet class in slides 50 and 51. The code creates a
te
ConcurrentSkipListSet instance and adds elements into it. It then sorts its
en
elements in ascending and descending order, and finds lower and higher elements. Here,
the elements are displayed in descending order using the descendingSet() method.
Also, the methods, lower() and higher() returns the element before Mango and
C
ConcurrentSkipListMap
ec
entire map.
rA
Explain the Code Snippet that shows the use of some of the methods available in
ConcurrentSkipListMap class in slides 52 and 53. The code inserts, retrieves, and
reverses the data from a ConcurrentSkipListMap instance. The firstEntry()
Fo
and lastEntry() methods display the key-value mapping result for the first and the last
elements respectively.
LinkedBlockingDeque
©Aptech Limited
Explain the Code Snippet that shows the implementation of LinkedBlockingDeque
class and use of some of its available methods in slides 53 to 56.
The code creates three classes, ProducerDeque, ConsumerDeque, and
LinkedBlockingDeque. The ProducerDeque class creates an instance of
BlockingDeque that invokes the addFirst() method to insert 10 integers at the
front of the deque. The ConsumerDeque class also creates an instance of
BlockingDeque that invokes the peekFirst() method to retrieve and remove the
last integer value present in the deque. In the main class, LinkedBlockingDeque, an
object of LinkedBlockingDeque class is created that allows you to store a maximum
of 5 elements in the deque. If you try to insert more than 5 elements in the deque, it will
y
throw an IllegalStateException. The main class, on execution first runs the
nl
Producer thread and inserts the integer value 1 at the front of the deque.
Next, the Consumer thread runs and retrieves the integer value 1, but does not remove it
O
from the head. Again, the Producer thread executes and inserts 2 at the front of the
deque. Now, once again, the Consumer thread runs and retrieves the value 2 present at
se
the front of the deque, but does not remove it from the head. This process repeats until the
integer value 4 is retrieved from the head of the queue. Now, as soon as the integer value 5
rU
tries to enter the deque, a message is displayed that the deque is filled up to the maximum
capacity. This is because the deque has reached its maximum capacity and therefore
IllegalStateException is thrown.
te
AbstractMap.SimpleEntry
en
in slides 57 and 58. The code creates instances with an entry having key-value pair as (1,
Apple). It then retrieves key and value using getKey() and getValue() methods, and
pt
replaces the value of last entry from Apple to Orange using the setValue() method.
rA
AbstractMap.SimpleImmutableEntry
Fo
©Aptech Limited
Slide 59
Let us summarize the session.
y
nl
O
se
Using slide 59, summarize the session. End the session with a brief summary of what has
been taught in the session.
rU
te
3.3 Post Class Activities for Faculty
You should familiarize yourself with the topics of the next session which is Generics.
en
Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the OnlineVarsity site to
C
gain additional information related to the topics covered in the next session. You can also
connect to online tutors on the Online Varsity site to ask queries related to the sessions.
h
ec
pt
rA
Fo
©Aptech Limited
Session 4 – Generics
Here, you can ask students the key topics they can recall from previous session. Prepare a question
or two which will be a key point to relate the current session objectives.
y
4.1.1 Objectives
nl
By the end of this session, the learners will be able to:
O
Identify the need for Generics
List the advantages and limitations of Generics
se
Explain generic class declaration and instantiation
Define and describe generic methods
Explain the wildcard argument rU
Describe the relationship between Collection and Generics
which contain the collection framework, legacy collection classes, event model, date time
facilities, and internationalization.
h
ec
You should teach the concepts in the theory class using the images provided. For teaching in
the class, you are expected to use slides and LCD projectors.
pt
Tips:
rA
It is recommended that you test the understanding of the students by asking questions in
between the class.
Fo
In-Class Activities:
Follow the order given here during In-Class activities.
©Aptech Limited
Overview of the Session:
Give the students the overview of the current session in the form of session objectives.
Show the students slide 2 of the presentation.
y
nl
O
se
rU
Tell the students that this session introduces with Generics that was added to the Java
programming language as a part of J2SE 5.0. The sessions also covers java.util package
te
which contains the collections framework, legacy collection classes, event model, date time
facilities, and internationalization.
en
C
h
ec
pt
rA
Fo
©Aptech Limited
4.2 In-Class Explanations
Slide 3
Let us understand the generics in programming.
y
nl
O
se
rU
Using slide 3, explain the generics in programming.
Explain the students about the importance of detecting the errors in the compile-time.
te
Compile-time bugs, for example, can be detected early on; you can use the compiler's error
messages to figure out what the problem is and fix it, right then and there.
en
Runtime errors are more problematic, as they are not always visible immediately. Thus,
C
when they are detected, the cause may be far above the point of the code, rather than the
point where the runtime environment detected.
h
The adoption of generic programs can make the errors detect at compile-time providing
ec
Generic types can be compared with functions which are parameterized by type variables
and can be instantiated with different type arguments depending on the context. In other
rA
words, Generic types or methods differ from regular types and methods in that they have
type parameters.
Fo
Examples of generic types can be found in the Collections framework of the J2SE 5.0
platform libraries. A class like LinkedList<E> is a generic type. It has a type
parameter E which is a place holder for the type of elements to be stored in the list.
Tips:
Similar to formal parameters used in method declarations, type parameters provide a way
for you to re-use the same code with different inputs.
©Aptech Limited
Slides 4 to 6
Let us understand the overview of generics.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Generics
The need for generic types comes mainly from the implementation and use of
collections in Java. A collection contains objects of different types, however many
a times, programmers often want to specify that a collection contains elements of
a certain type, such as a list of integral values or a list of strings.
The Collections framework in non-generic which means Java did not forces the
collections of elements of the same type. For example, prior to Java 1.5, the
collections can be based on different classes, such as a class Integer and a
y
class String for holding integral values and strings respectively.
nl
Now, when the collection is traversed using Iterator interface, each iteration returns a
reference to an object whose type is Object, rather than the actual object type retrieved
O
from the collection which can be Integer or String. Then, the programmer has to
explicitly type cast the object which can lead to ClassCastException exception during
runtime.
se
The ClassCastException thrown to indicate that the code has attempted to cast an
object to a subclass of which it is not an instance.
For example,
Object x = new Integer(0);
System.out.println((String)x);
rU
te
The following code snippet illustrates the collection program:
en
3. Integer i = (Integer)v.get(0);
First, the code declares an ArrayList object. Then, it adds a String to
h
the ArrayList . Then, it retrieves the added String and cast it to an Integer .
ec
problem can be avoided by using generics and is the primary motivation for using generics.
rA
Generics in Java code generates one compiled version of a generic class. The introduction of
Generics in Java classes will help remove the explicit casting of a class object so the
ClassCastException will not arise during compilation.
Fo
Generics will help to remove type inconsistencies during compile time rather than at run
time.
Generics are added to the Java programming language because they enable:
©Aptech Limited
Generics allow the programmer to communicate the type of a collection to the compiler so
that it can be checked. Thus, using Generics is safe as during compilation of the program,
the compiler consistently checks for the element type of the collection and inserts the
correct cast on elements being taken out of the collection.
Explain the code snippet mentioned in slides 5 and 6. Generics allow a type or method to
operate on objects of various types, while providing compile-time type safety.
Code that uses generics has many benefits over non-generic code like:
Stronger type checks at compile time.
y
A Java compiler applies strong type checking to generic code and issues errors if the
code violates type safety.
nl
O
Enabling programmers to implement generic algorithms
Programmers can implement generic algorithms that work on collection of different
types can be customized and are type safe and easier to read.
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 7
Let us understand advantages of generics.
y
nl
O
se
Using slide 7, explain advantages of generics.
rU
Generics allow flexibility of dynamic binding. Generic type helps the compiler to check for
type correctness of the program at the compile time.
te
By allowing you to specify types that are acted on by a generic class or method, the generics
en
feature shifts the burden of type safety from you to the compiler. There is no need to write
code to test for the correct data type because it is enforced at compile time. The need for
C
Multiple bounds are one of the generic features which allow a type variable or wildcard to
h
©Aptech Limited
Slide 8
Let us understand limitations of generics.
y
nl
O
se
Using slide 8, explain limitations of generics.
rU
In Generics, you cannot create generic constructors. A local variable cannot be declared
where the key and value types are different from each other.
te
Generic does not support sub-typing which means List is not considered to be a sub-type
en
of List.
C
Tips:
Visit this link to understand more on restrictions on generics:
http://docs.oracle.com/javase/tutorial/java/generics/restricti
h
ons.html.
ec
pt
rA
Fo
©Aptech Limited
Slides 9 and 10
Let us understand generic classes.
y
nl
O
se
rU
te
en
C
h
ec
pt
A generic class is a mechanism to specify the type relationship between a component type
and its object type. The syntax for declaring a generic class is same as ordinary class except
that in angle brackets (<>) the type parameters are declared.
Fo
The declaration of the type parameters follows the class name. The type parameters are like
variables and can have the value as a class type, interface type, or any other type variable
except primitive data type. The class declaration such as List<E> denotes a class of
generic type.
The parameter to the generic is given at the time of declaration and is bound at compile
time. A generic class can thus generate many types, one for each type of parameter, such as
ARRAY [TREE], ARRAY [STRING], and so on.
©Aptech Limited
Generic classes can accept one or more type parameters. Therefore, they are called
parameterized classes or parameterized types. The type parameter section of a generic class
can include several type parameters separated by commas.
A generic class declaration looks like non-generic class declaration, except that the class
name is followed by a type parameter section. This class in Java is a class that can operate
on a specific type specified by the programmer at compile time.
In-Class Question:
After you finish explaining Generic Classes, you will ask the students an In-Class question.
y
This will help you in reviewing their understanding of the topic.
nl
O
Why generic classes are called parameterized classes?
Answer:
se
As they can accept one or more type parameters.
Tips:
rU
Java generics generate only one compiled version of a generic class or function regardless of
the number of parameterizing type used.
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 11 to 17
Let us understand declare and instantiate Generic class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
y
nl
O
Using slides 11 to 17, explain declare and instantiate Generic class.
se
To create an instance of the generic class, the new keyword is used along with the class
name except that the type parameter argument is passed between the class name and the
rU
parentheses. The type parameter argument is replaced with the actual type when an object
is created from a class. A generic class is shared among all its instances.
te
Then explain the syntax of declaring a generic class.
en
Then, explain the code snippet mentioned in slide12. The code creates a generic type class
declaration with a type variable, T that can be used anywhere in the class. To refer to this
C
generic class, a generic type invocation is performed which replaces T with a value such as
String. Typically, type parameter names are single, uppercase letters.
h
By convention, type parameter names are single, uppercase letters. The most commonly
pt
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
Explain the code Snippet that illustrates how a class can be declared and initialized as
mentioned in slides 14 and 15.
©Aptech Limited
Explain the Code Snippet that illustrates how an instance of TestQueue will accept String
as a type parameter mentioned in slides 16 and 17.
Slides 18 to 24
Let us understand Generic methods.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
y
nl
O
se
rU
te
en
C
h
ec
Generic methods are methods that introduce their own type parameters. This is similar to
pt
declaring a generic type, but the type parameter’s scope is limited to the method where it is
declared. Static and non-static generic methods are allowed, as well as generic class
rA
constructors. Generic methods can also be declared in non-generic classes. Also, Generic
methods are best suited for overloaded methods that perform identical operations for different
argument type. The use of generic methods makes the overloaded methods more compact and
Fo
easy to code.
The syntax for a generic method includes a type parameter, inside angle brackets, and
appears before the method’s return type. For static generic methods, the type parameter
section must appear before the method’s return type.
A generic method allows type parameters used to make dependencies among the type of
arguments to a method and its return type. The return type does not depend on the type
parameter, or any other argument of the method. This shows that the type argument is
being used for polymorphism.
©Aptech Limited
Explain the Code Snippet displays the use of a generic method mentioned in slides 19 and
20. The code uses a generic method, display(), that accepts an array parameter as its
argument.
Explain the Code Snippet demonstrates how to declare a class with two type parameters
mentioned in slides 21 and 22.
Explain the Code Snippet demonstrates how to declare a non-generic subclass mentioned in
slide 23.
y
Explain the Code Snippet that demonstrates the creation of a generic subclass mentioned in
slide 24.
nl
Tips:
O
The Util class includes a generic method, compare, which compares two Pair objects:
se
public class Util {
// Generic static method
}
C
private K key;
private V value;
ec
// Generic constructor
pt
this.value = value;
}
Fo
// Generic methods
public void setKey(K key) { this.key = key; }
public void setValue(V value) { this.value = value; }
public K getKey() { return key; }
public V getValue() { return value; }
}
©Aptech Limited
boolean same = Util.<Integer, String>compare(p1, p2);
The type can be left and you can write this as:
Pair<Integer, String> p1 = new Pair<>(1, "apple");
Pair<Integer, String> p2 = new Pair<>(2, "pear");
boolean same = Util.compare(p1, p2);
At compile-time, the compiler will gather the information on the type of the objects been
compared.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 25 to 28
Let us understand to declare Generic methods.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 25 to 28, explain declare Generic methods.
se
To create generic methods and constructors, type parameters are declared within the
method and constructor signature.
declarations.
There can be more than one type of type parameters, each separated by a comma. These
C
type parameters act as placeholders for the actual type argument’s data types, which are
passed to the method. Primitive data types cannot be represented for type parameters.
h
Explain the Code Snippet displays the generic methods present in the Collection interface
ec
Explain the Code Snippet demonstrates how to declare a generic class containing a generic
constructor mentioned in slides 27 and 28.
rA
In-Class Question:
Fo
After you finish explaining Declare Generic Methods, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
©Aptech Limited
Slides 29 to 31
Let us understand accept Generic parameters.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
A single generic method declaration can be called with arguments of different types.
Each type parameter section includes one or more type parameters separated by
commas. A type parameter is an identifier that specifies a generic type name.
All generic method declarations have a type parameter section delimited by angle
brackets preceding the method’s return type.
A generic method’s body should include type parameters that represent only reference
types.
y
The type parameters can be used to declare the return type. They are placeholders for
nl
the types of the arguments passed to the generic method. These arguments are called
actual type arguments.
O
Explain the Code Snippet displays a generic method declaration mentioned in slides 30 and
31.
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 32 and 33
Let us understand return Generic types.
y
nl
O
se
rU
te
en
C
h
ec
pt
Explain the Code Snippet displays a method having a generic return type declaration
mentioned in 32 and 33.
©Aptech Limited
Slides 34 to 38
Let us understand type inference.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
rU
te
en
C
h
ec
Generic methods introduced you to type interference, which enables you to invoke a
generic method as you would an ordinary method, without specifying a type between angle
rA
brackets.
Type inference enables the Java compiler to determine the type arguments that make the
Fo
©Aptech Limited
The type arguments required to invoke the constructor of a generic class can be replaced
with an empty set of type parameters (<>) as long as the compiler infers the type arguments
from the context.
In Java SE 7, the parameterized type of the constructor can be replaced with an empty set of
type parameters.
y
The following Code Snippet illustrates this:
nl
Map<String, List<String>> myMap = new HashMap<>();
O
In the following Code Snippet, the compiler generates an unchecked conversion warning:
Map<String, List<String>> myMap = new HashMap(); // unchecked
se
conversion warning
Java SE 7 supports limited type inference for generic instance creation. The type inference
rU
can be used only if the parameterized type of the constructor is apparent from the context.
Explain the Code Snippet illustrates this which is mentioned in slides 37 and 38.
te
Tips:
The inference algorithm uses only invocation arguments, target types, and possibly an
en
©Aptech Limited
Slides 39 to 41
Let us understand Generic constructors of Generic and non-Generic classes.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Using slides 39 to 41, explain Generic constructors of Generic and non-Generic classes.
Constructors can declare their own formal type parameters in both generic and non-generic
classes.
Explain the Code Snippet shows the instantiation of the class MyClass mentioned in slides
39 and 40.
y
Explain the Code Snippet is valid for Java SE 7 and later displays how compilers work
mentioned in slide 41.
nl
O
In the code, the compiler understands:
The type Integer is for the formal type parameter, X, of the generic class
MyClass<X>.
se
The type String is for the formal type parameter, T, of the constructor of the generic
class.
rU
Prior to Java 7, compilers are able to infer the actual type parameters of generic
constructors, similar to generic methods. However, compilers in Java 7 and later can infer
te
the actual type parameters of the generic class being instantiated if you use the <>.
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 42 and 43
Let us understand Java SE 7 enhancements.
y
nl
O
se
rU
te
en
C
h
ec
pt
Underscore characters (_) can be added anywhere between digits in a numerical literal to
separate groups of digits in numeric literals. The String class can be used in the
expression of a switch statement. In Java SE 7, the integral types can be defined using the
Fo
The Java SE 7 complier generates a warning at the declaration site of a varargs method or
constructor with a non-reliable varargs formal parameter. The required type arguments
can be replaced to invoke the constructor of a generic class with an empty set of type
parameters as long as the compiler infers the type arguments from the context.
A single catch block handles many types of exception. Users can define specific exception
types in the throws clause of a method declaration because the compiler executes accurate
analysis of rethrown exceptions.
©Aptech Limited
The try-with-resources statement declares one or more resources, which are
objects that should be closed after the programs have finished working with them.
Another introduction in Java SE 7 is tired compilation which brings client startup speeds to
the server virtual machine. Here along with interpreter to collect profiling information to fed
in the computer, it also contain client compiler to generate compiled version of methods
y
that collect profiling information about themselves. Since the compiled code is faster than
nl
interpreter, the program executes with greater performance during profiling phase.
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 44 and 45
Let us understand Collection and Generics.
y
nl
O
se
rU
te
en
C
h
ec
pt
Collection is an object that manages a group of objects. Collection API depends on generics
for its implementation.
Fo
Explain the Code Snippet illustrates this mentioned in slides 44 and 45.
The Java collections API provide Java developers with a set of classes and interfaces that
makes it easier to handle collections of objects. A collection works a bit like arrays, except
their size can change dynamically and they have more advanced behavior than arrays.
©Aptech Limited
Slide 46
Let us understand wildcards with Generics.
y
nl
O
se
Using slide 46, explain wildcards with Generics.
rU
Explain wildcards with Generics diagram mentioned in slide 46.
te
In generic, the question mark(?), called the wildcard, represents an unknown type. The
wildcard can be used in different situations like as a type of parameter, sometime as a
en
return type.
C
Tips:
A wildcard is never used as a type argument for generic method invocation or a generic class
instance creation or a super type.
h
ec
pt
rA
Fo
©Aptech Limited
Slides 47 and 48
Let us understand exception handling with Generics.
y
nl
O
se
rU
te
en
C
h
ec
pt
Exceptions provide a reliable mechanism for identifying and responding to error conditions.
The catch clause present with a try statement checks that the thrown exception matches
the given type.
Fo
A compiler cannot ensure that the type parameters specified in the catch clause matches
the exception of unknown origin as an exception is thrown and caught at run time. Thus, the
catch clause cannot include type variables or wildcards.
©Aptech Limited
Explain the Code Snippet displays the use of generic type with exceptions mentioned in slide
48.
In-Class Question:
After you finish explaining Exception Handling with Generics, you will ask the students an In-
Class question. This will help you in reviewing their understanding of the topic.
Which are not included by catch clause in Exception Handling with Generics?
Answer:
y
type variables or wildcards.
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 49 to 52
Let us understand inheritance with Generics.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 49 to 52, explain inheritance with Generics.
se
Inheritance is a mechanism to derive new classes or interfaces from the existing ones.
Object-oriented programming allows classes to inherit commonly used state and behavior
from other classes.
rU
Classes can extend generic classes and provide values for type parameters or add new type
te
parameters. A class cannot inherit from parametric type. Two instantiations of the same
generic type cannot be used in inheritance.
en
Explain the Code Snippet that displays the use of generics with inheritance mentioned in
C
slides 50 to 52.
h
ec
pt
rA
Fo
©Aptech Limited
Slides 53 to 56
Let us understand interoperability with Generics.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 53 to 56, explain interoperability with Generics.
se
In Java, genericity ensures that the same class file is generated by both legacy and generic
versions with some additional information about types. This is known as binary compatibility
rU
as the legacy class file can be replaced by the generic class file without recompiling.
Explain the Code Snippet displays the use of legacy code with legacy client mentioned in
te
slides 54 to 56.
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 57 to 62
Let us understand Generic library with legacy client.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
In generic code, the classes are accompanied by a type parameter. When a generic type like
collection is used without a type parameter, it is called a raw type. A value of parameterized
type can be passed to a raw type as parameterized type is a subtype of raw type.
Java generates an unchecked conversion warning when a value of raw type is passed where
a parameterized type is expected.
Explain the Code Snippet displays the use of generic library with legacy client mentioned in
slides 58 to 62.
y
It is the case where the library is updated to generics while the client remains in its legacy
version. This may occur because there is not enough time to convert everything all at once,
nl
or because the library and client are controlled by different organizations.
O
Whenever a parameterized type is defined, Java recognizes the corresponding
unparameterized version of the type called raw type. For instance, the parameterized type
se
Stack<E> corresponds to the raw type Stack, and parameterized type ArrayStack<E>
corresponds to the raw type ArrayStack.
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 63
Let us understand erasure.
y
nl
O
se
Using slide 63, explain erasure.
rU
When you insert an integer into a list, and try to extract a String it is wrong. If you extract an
element from list and by casting that to String if you try to treat that as string, you will
te
get ClassCastException. The reason is that Generics are implemented by the Java
compiler as a front end conversion called erasure.
en
Erasure removes all generic type information. All the type information between angle
C
brackets is thrown out, so, a parameterized type like List<String> is converted into
List. Type erasure maintains compatibility with Java libraries and applications which are
h
©Aptech Limited
Slides 64 to 67
Let us understand Generics in legacy code.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 64 to 67, explain Generics in legacy code.
se
Sometimes, it may be required to update the library not immediately but over a period of
time. In such cases, the method signatures get change and consists of the type parameters.
The method body will not change.
rU
This change in the method signature can be performed by making minimum changes in the
te
method, or by creating stub or by using wrappers.
en
Adding type parameters to the class or interface which has been extended or
implemented
Adding type parameters to the method signatures
h
Explain the Code Snippet displays the use of generics mentioned in slides 65 and 66 and in
pt
slide 67.
rA
In-Class Question:
After you finish explaining Generics in Legacy Code, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
Fo
©Aptech Limited
Slides 68 to 71
Let us understand using Generics in legacy code.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 68 to 71, explain using Generics in legacy code.
se
A generic library should be created when there is access to source code. Update the entire
library source as well as the client code to eliminate potential unchecked warnings.
rU
Explain the Code Snippet shows the use of generics in legacy code mentioned in slides 68 to
71.
te
The unchecked warning indicates that the compiler cannot offer the same safety guarantees
en
that are possible when generics are used uniformly throughout. However, when the generic
code is generated by updating legacy code, equivalent class files are produced from both
C
and hence running a legacy client with generic library will yield same result as running
legacy client with legacy library despite of unchecked warning.
h
ec
pt
rA
Fo
©Aptech Limited
Slide 72
Let us summarize the session.
y
nl
O
se
Using slide 72, you will summarize the session. You will end the session with a brief
rU
summary of what has been taught in the session.
te
4.3 Post Class Activities for Faculty
You should familiarize yourself with the topics of the next session which is File Handling in
en
Java.
Tips:
C
You can also check the Articles/Blogs/Expert Videos uploaded on the Online Varsity site to
gain additional information related to the topics covered in the next session. You can also
h
connect to online tutors on the Online Varsity site to ask queries related to the sessions.
ec
pt
rA
Fo
©Aptech Limited
Session 5 – File Handling in Java
Here, you can ask students the key topics they can recall from previous session. Prepare a question
or two which will be a key point to relate the current session objectives.
y
5.1.1 Objectives
nl
By the end of this session, the learners will be able to:
O
Define data streams
Identify the need for streams
se
Identify the purpose of the File class, its constructors, and methods
Describe the DataInput and DataOutput interfaces
rU
Describe the byte stream and character stream in the java.io.package
Explain the InputStream and OutputStream classes
Describe the BufferedInputStream and BufferedOutputStream classes
te
Describe Character stream classes
Describe the chaining of I/O systems
en
To teach this session, you should be well-versed with java.io package which contains
classes related to input/output streams to store data in the files. You should also be familiar
h
You should teach the concepts in the theory class using the images provided. For teaching in
pt
the class, you are expected to use slides and LCD projectors.
rA
Tips:
It is recommended that you test the understanding of the students by asking questions in
Fo
In-Class Activities:
Follow the order given here during In-Class activities.
©Aptech Limited
Overview of the Session:
Then give the students the overview of the current session in the form of session objectives.
Show the students slide 2 of the presentation.
y
nl
O
se
rU
Tell the students that this session introduces the java.io package. They will learn the
different classes provided in the java.io package. The session explains how to work with
the input/output stream to manage data in the files created on the system. The session also
te
teaches different types of streams such as character stream, byte stream, File class, and the
en
©Aptech Limited
5.2 In-Class Explanations
Slide 3
Let us understand about the concept of stream classes in Java.
y
nl
O
se
Using slide 3, explain the concept of stream classes in Java.
rU
Tell the students that most of the application programs work with data stored in local files
or coming from computers over the network. Java works with streams of data. A stream is a
sequence of data. It can also be defined as a logical entity that produces or consumes
te
information.
en
A data stream is a channel through which data travels from a source to a destination. This
source or destination can be an input or output device, storage media, or network
C
computers. A physical data storage is mapped to a logical stream and then, a Java program
reads data from this stream serially – one byte after another, or character after character. In
h
other words, a physical file can be read using different types of streams, for example,
FileInputStream or FileReader. Java uses such streams to perform various input
ec
and output operations. The standard input/output stream in Java is represented by three
fields of the System class. They are as follows:
pt
in
rA
The standard input stream is used for reading characters of data. This stream responds to
keyboard input or any other input source specified by the host environment or user. It has
been defined as follows:
Fo
out
The standard output stream is used to typically display the output on the screen or any
other output medium. It has been defined as follows:
public static final PrintStream out;
err
This is the standard error stream. By default, this is the user’s console. It has been defined
as follows:
public static final PrintStream err;
©Aptech Limited
Slide 4
Let us understand the need for stream classes in Java.
y
nl
O
se
Using slide 4, explain the need for stream classes in Java.
rU
Tell the students that in Java, streams are required to perform all the input/output (I/O)
operations. An input stream receives data from a source into a program and an output
te
stream sends data to a destination from the program.
en
Tips:
The stream in the java.io package supports many data such as primitives, objects,
pt
©Aptech Limited
Slide 5
Let us understand the steps for using stream classes in Java.
y
nl
O
se
Using slide 5, explain the steps for using stream classes in Java.
rU
Tell the students that to read or write data using Input/Output streams, the following steps
need to be performed. They are as follows:
te
Open a stream that points at a specific data source: a file, a socket, URL, and so on.
en
Input and Output streams are abstract classes and are used for reading and writing of
unstructured sequence of bytes. The other input and output streams are subclasses of the
h
basic Input and Output stream class and are used for reading and writing to a file.
ec
The different types of byte streams can be used interchangeably as they inherit the
pt
structure of Input/output stream class. For reading or writing bytes, a subclass of the
InputStream or OutputStream class has to be used respectively.
rA
In-Class Question:
After you finish explaining streams in Java, you will ask the students an In-Class question. This
Fo
©Aptech Limited
Slides 6 and 7
Let us understand the File class.
y
nl
O
se
rU
te
en
C
h
ec
pt
Tell the students that unlike other classes that work on streams, File class directly works
with files and the file system. The files are named using the file-naming conventions of the
Fo
host operating system. These conventions are encapsulated using the File class
constants. File class encapsulates access to information about a file or a directory. In
other words, File class stores the path and name of a directory or file. All common file
and directory operations are performed using the access methods provided by the File
class. Methods of this class allow to create, delete, and rename files, provid access to the
pathname of the file, determine whether any object is a file or directory, and check the read
and write access permissions.
The directory methods in the File class allow creating, deleting, renaming, and listing of
directories.
©Aptech Limited
The constructors of the File class are as follows:
File(String dirpath)
The File(String dirpath) creates a File object with pathname of the file
specified by the String variable, dirpath.
y
File(File fileobj, String filename)
nl
The File(File fileobj, String filename) creates a File object with
O
another File object specified by the variable, fileobj and filename specified by the string
variable, filename.
se
File(URL urlobj)
The File(URL urlobj) creates a URL object that describes a file.
public File(URL urlobj)
rU
Following are the important points about File object:
Instances may or may not denote an actual file-system object, such as a file or a
te
directory. If it does denote such an object, then that object resides in a partition. A
en
as access permissions.
Instances of the File class are immutable; that is, once created, the abstract
h
In-Class Question:
pt
After you finish explaining File class, you will ask the students an In-Class question. This
will help you in reviewing their understanding of the topic.
rA
Fo
Tips:
The File only gives you access to the file and file system metadata. If you need to read or
write the content of files, you should do so using either FileInputStream,
FileOutputStream, or RandomAccessFile.
©Aptech Limited
Slides 8 to 11
Let us understand the methods of the File class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 8 to 11, explain the methods of the File class.
se
The methods in the File class help to manipulate the file on the file system.
rU
Some of the methods in the File class are as follows:
renameTo(File newname)
te
The renameTo(File newname) method will name the existing File object with the
en
delete()
The delete() method deletes the file represented by the path of the invoking File
h
object.
public boolean delete()
ec
exists()
pt
The exists() method tests the existence of file or directory denoted by this abstract
pathname.
rA
getPath()
Fo
The getPath() method converts the abstract pathname into a pathname string.
public String getPath()
isFile()
The isFile() method checks whether the file denoted by this abstract pathname is a
normal file.
public boolean isFile()
©Aptech Limited
createNewFile()
The createNewFile() method creates a new empty file whose name is the path name
for this file. It is only created when the file of similar name does not exist.
public boolean createNewFile() throws IOException
mkdir()
The mkdir() method creates the directory named by this abstract pathname.
public boolean mkdir()
Explain the Code Snippet that displays the use of methods of the File class mentioned in
y
slide 9.
nl
Next, explain the Code Snippet that displays the use of FilenameFilter class to filter files with
O
a specific extension mentioned in slides 10 and 11.
Tell the students that the given example displays the use of FilenameFilter class to
se
filter files with a specific extension. The FilenameFilter interface defines an
accept() method which checks whether the specified file should be included in a file list.
rU
The method of this class returns true, if the filename ends with .java extension as stored in
the variable, ext. The list() method restricts the visibility of the file and displays only
those files which ends with the specified extension.
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 12
Let us understand the FileDescriptor class.
y
nl
O
se
Using slide 12, explain the FileDescriptor class.
rU
Tell the students that the java.io.FileDescriptor class instances serve as an
opaque handle to the underlying machine-specific structure representing an open file, an
te
open socket, another source, or sink of bytes.
en
The FileDescriptor class provides access to the file descriptors that are maintained
by the operating system when files and directories are being accessed. In practical use, a file
C
operating system.
ec
The static FileDescriptor err acts as a handle to the standard error stream.
static final FileDescriptor in
rA
stream.
©Aptech Limited
Next, explain the constructors and methods of the FileDescriptor class. These are as
follows:
FileDescriptor()
The constructor creates an (invalid) FileDescriptor object.
public FileDescriptor()
sync()
The sync() method clears the system buffers and writes the content that they contain to
y
the actual hardware.
nl
public void sync() throws SyncFailedException
O
valid()
The valid() method checks whether the file descriptor is valid. Since the file descriptors
se
are associated with open files, they become invalid when the file is closed.
In-Class Question:
rU
After you finish explaining FileDescriptor class, you will ask the students an In-Class
te
question. This will help you in reviewing their understanding of the topic.
en
Answer:
h
The boolean valid() method checks the validity of the file descriptor object.
ec
pt
rA
Fo
©Aptech Limited
Slide 13
Let us understand DataInput Interface and DataOutput Interface.
y
nl
O
se
Using slide 13, explain the DataInput Interface and DataOutput Interface.
rU
Tell the students that the DataInput interface provides for reading bytes from a binary
stream and reconstructing from the data in any of the Java primitive types.
te
In other words, data stream supports input/output of primitive data types and string values.
en
types.
Converting data from Java modified Unicode Transmission Format (UTF)-8 into string
ec
form.
pt
Tell the students that the DataOutput interface provides for converting data from any of
the Java primitive types to a series of bytes and writing these bytes to a binary stream.
There is also a facility for converting a String into modified UTF-8 format and writing the
Fo
Once you have DataOutputStream object in hand, then there is a list of helper
methods, which can be used to write the stream or to do other operations on the stream.
©Aptech Limited
Tips:
It is true for all the reading routines in this interface that, if end of file is reached before the
desired number of bytes has been read, an EOFException is thrown. If any byte cannot be
read for any reason other than end of file, an IOException other than EOFException is
thrown. In particular, an IOException may be thrown if the input stream has been closed.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 14
Let us understand the methods of DataInput Interface.
y
nl
O
se
Using slide 14, explain the methods of the DataInput Interface.
rU
Tell the students that the DataInput interface has several methods to read inputs, such as
binary data from the input stream and reconstructs data from the bytes to any of the Java
te
primitive type form. An IOException will be raised if the methods cannot read any byte
from the stream or if the input stream is closed.
en
readBoolean()
The readBoolean() method reads an input byte from a stream and returns true if the
h
readByte()
pt
The readByte() method reads one byte from a stream which is a signed value in the range
from -128 to 127.
rA
readInt()
Fo
The readInt() method reads four bytes from a stream and returns the int value of the
bytes read.
int readInt() throws IOException
©Aptech Limited
readDouble()
The readDouble() method reads eight bytes from a stream and returns a double value of
the bytes read.
double readDouble() throws IOException
readChar()
The readChar() method reads two bytes from a stream and returns a char value.
char readChar() throws IOException
readLine()
The readLine() method reads a line of text from the input stream. It reads a byte at a time
y
and then, converts the byte into a character and goes on reading until it encounters the end of
nl
line or end of file. The characters are then returned as a String.
String readLine() throws IOException
O
Explain the Code Snippet that displays the use of DataInput interface mentioned in slide
14. Tell the students that the code demonstrates the use of readDouble() and
se
readInt() method to accept values from the user.
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 15
Let us understand the methods of the DataOutput interface.
y
nl
O
se
Using slide 15, explain the methods of the DataOutput interface.
rU
Tell the students that the DataOutput interface has several methods to write outputs,
such as binary data to the output stream. An IOException may be thrown if bytes
te
cannot be written to the stream.
en
writeBoolean(boolean b)
The writeBoolean(boolean b) method writes the boolean value given as
h
parameter to an output stream. If the argument has the value as true, then 1 will be written
otherwise, the value 0 is written.
ec
writeByte(int value)
The writeByte(int value) method writes the byte value of the integer given as
rA
writeInt(int value)
The writeInt(int value) method writes four bytes that represent the integer given
as parameter to an output stream.
public void writeInt(int value) throws IOException
©Aptech Limited
writeDouble(double value)
The writeDouble(double value) method writes eight bytes that represent the
double value given as parameter to an output stream.
public void writeDouble(double value) throws IOException
writeChar(int value)
The writeChar(int value) method writes the char value of the integer given as
parameter to a stream.
public void writeChar(int value) throws IOException
writeChars(String value)
y
The writeChars(String value) method writes the string given as parameter to a
nl
stream.
public void writeChars(String s) throws IOException
O
writeUTF(String value)
se
The writeUTF(String value) method writes a string in Java modified UTF-8 form given
as parameter to a stream.
public void writeUTF(String str) throws IOException
rU
Explain the Code Snippet that displays the use of DataOutput interface mentioned in
slide 15. Tell the students that the code snippet demonstrates the use of
te
writeBoolean() and writeDouble() methods.
en
Following code snippet shows the use of DataInput and DataOutput stream:
C
(new FileInputStream("C:/Java/Hello.txt"));
(new FileOutputStream("C:/Java/Hello1.txt"));
String str;
rA
The code will convert the lines into capital letters and finally, copies them into another file
Hello1.txt.
©Aptech Limited
The output will be as shown in the following figure:
In-Class Question:
After you finish explaining DataInput/DataOutput interface, you will ask the students
an In-Class question. This will help you in reviewing their understanding of the topic.
y
nl
O
What is the function of readInt() method?
se
Answer:
The readInt() method reads four bytes and returns an int value.
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 16 to 22
Let us understand the java.io package.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
y
nl
O
Using slides 16 to 22, explain the java.io package.
se
A stream represents many sources and destinations, such as disk files and memory arrays. It
is a sequence of data. An I/O Stream represents an input source or an output destination.
rU
Streams support many forms of data, such as simple bytes, primitive date type, localized
characters, and so on. Certain streams allow data to pass and certain streams transform the
te
data in an useful way. However, all streams provide a simple model to programs to use
them.
en
A program uses an input stream to read data from a source. It reads one item at a time.
C
Explain the figure illustrates the input stream model in slide 17.
h
Next, explain the figure illustrates that a program uses an output stream to write data to a
ec
Explain the Code Snippet that displays the working of byte streams using the
FileInputStream class and FileOutputStream class mentioned in slides 18 and
rA
19.
A program that uses character streams adapts to the local character set and is ready for
Fo
internationalization. All character stream classes are derived from the Reader and
Writer class. There are character stream classes that specialize in file I/O operations such
as FileReader and FileWriter.
Explain the Code Snippet that displays the reading and writing of character streams using
the FileReader and FileWriter class mentioned in slides 20 to 22.
©Aptech Limited
The package java.io contains classes that handle fundamental input and output
operations in Java. Along with this, java.io package also contains other classes like:
File which represent a file on host system.
RandomAccessFile which represents a random access file.
StreamTokenizer which tokenizes the content of a streams.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 23 and 24
Let us understand the methods of InputStream class.
y
nl
O
se
rU
te
en
C
h
ec
pt
Tell the students that the InputStream class provides a number of methods that manage
reading data from a stream.
Fo
read()
The read() method reads the next bytes of data from the input stream and returns an int
value in the range of 0 to 255. The method returns -1 when end of file is reached.
public abstract int read() throws IOException
available()
The available() method returns the number of bytes that can be read without blocking. In
other words, it returns the number of available bytes.
public int available() throws IOException
©Aptech Limited
close()
The close() method closes the input stream. It releases the system resources associated
with the stream.
public void close() throws IOException
mark(int n)
The mark(int n) method marks the current position in the stream and will remain valid
until the number of bytes specified in the variable, n, is read. A call to the reset() method
will position the pointer to the last marked position.
public void mark(int readlimit)
y
skip(long n)
nl
The skip(long n) method skips n bytes of data while reading from an input stream.
public long skip(long n) throws IOException
O
reset()
The reset() method resets the reading pointer to the previously set mark in the stream.
se
public void reset() throws IOException
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 25 to 27
Let us understand FileInputStream class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
Tell the students that a FileInputStream obtains input bytes from a file in a file system.
The file type depends on the host environment.
©Aptech Limited
FileInputStream is meant for reading streams of raw bytes such as image data. File
stream objects can be created by either passing the name of the file or a File object or a
FileDescriptor object. FileInputStream class is used to read bytes from a file.
When an object of FileInputStream class is created, it is also opened for reading.
FileInputStream class overrides all the methods of the InputStream class, except
mark() and reset() methods. The reset() method will generate an IOException.
FileInputStream(String sObj)
The FileInputStream(String sObj) creates an InputStream object that can be
y
used to read bytes from a file. The parameter sObj stores the full path name of a file.
nl
public FileInputStream(String sObj) throws FileNotFoundException
O
FileInputStream(File fObj)
The FileInputStream(File fObj) creates an InputStream object that can be used
se
to read bytes from a file where fObj is a File object.
public FileInputStream(File fObj) throws FileNotFoundException
FileInputStream(FileDescriptor fdObj)
rU
The FileInputStream(FileDescriptor fdObj) creates a FileInputStream
using the file descriptor object that can be used to represent an existing connection to the file,
te
which is there in the file system. The file descriptor object is fdObj.
public FileInputStream(FileDescriptor fdObj) throws
FileNotFoundException
en
Explain the Code Snippet that displays the creation of FileInputStream object in slide
C
26.
h
Explain the Code Snippet that demonstrates how to create a FileInputStream object
using different constructors in slides 26 and 27. The code creates a FileInputStream
ec
object to which the filename is passed as an argument. The object is used to read the text
characters from the specified file. The program will print out its own source code.
pt
host environment that what types of files are available. It is meant for reading streams of
raw bytes such as image data. FileReader can be used for reading streams of characters.
Fo
©Aptech Limited
Slides 28 and 29
Let us understand ByteArrayInputStream class.
y
nl
O
se
rU
te
en
C
h
ec
pt
Tell the students that the ByteArrayInputStream class allows a buffer in the memory to
be used as an InputStream. The input source is a byte[] array.
Fo
ByteArrayInputStream contains a buffer that stores the bytes that are read from the
stream. ByteArrayInputStream class uses a byte[] array as the source.
ByteArrayInputStream class has an internal counter, which keeps track of the next byte
to be read. This class does not support any new methods. It only overrides the methods of the
InputStream class such as read(), skip(), available(), and reset().
©Aptech Limited
The constructors of this class are as follows:
ByteArrayInputStream(byte[] b)
The ByteArrayInputStream(byte[] b) creates a ByteArrayInputStream with
a byte[] array, b, as the input source.
public ByteArrayInputStream(byte[] b)
y
public ByteArrayInputStream(byte[] b, int start, int num)
nl
Explain the Code Snippet that displays the use of the ByteArrayInputStream class in
O
slide 29.
se
package bytearrayinoutapplication;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
rU
te
public class ByteArrayInOutApplication {
barrayOutput.write(System.in.read());
}
ec
©Aptech Limited
The output will be as shown in the following figure:
y
nl
O
In-Class Question:
After you finish explaining InputStream, you will ask the students an In-Class question.
se
This will help you in reviewing their understanding of the topic.
rU
Can the methods in the ByteArrayInputStream class be invoked after the
te
stream has been closed without generating an exception?
en
Answer:
Yes. Closing a ByteArrayInputStream has no effect.
C
Tips:
Once you have ByteArrayInputStream object in hand, then there is a list of
h
helper methods which can be used to read the stream or to do other operations in
ec
the stream.
Closing a ByteArrayInputStream has no effect. The methods in this class can
pt
be called after the stream has been closed without generating an IOException.
rA
Fo
©Aptech Limited
Slide 30
Let us understand OutputStream class and its subclasses.
y
nl
O
se
Using slide 30, explain OutputStream class and its subclasses.
rU
The OutputStream class is an abstract class that defines the method in which bytes or
arrays of bytes are written to streams. ByteArrayOutputStream and
te
FileOutputStream are the subclasses of OutputStream class.
en
The OutputStream class is the superclass of all classes representing an output stream of
bytes. An output stream accepts output bytes and sends them to some sink. At least a
C
method must be provided to write one byte of output by the applications that need to
define a subclass of OutputStream.
h
In-Class Question:
ec
After you finish explaining OutputStream Class and its subclasses, you will ask the
pt
students an In-Class question. This will help you in reviewing their understanding of the
topic.
rA
Fo
Answer:
ByteArrayOutputStream and FileOutputStream
©Aptech Limited
Slide 31
Let us understand the methods of the OutputStream class.
y
nl
O
se
Using slide 31, explain the methods of the OutputStream class.
rU
There are several methods in OutputStream class, which are used for writing bytes of data
to a stream. All the methods of this class throw an IOException. Some of the methods of this
class are as follows:
te
write(int b)
The write(int b) method writes the specified byte of the integer given as parameter to an
en
output stream.
public abstract void write(int b) throws IOException
C
write(byte[] b)
The write(byte[] b) method writes a byte array given as parameter to an output stream.
h
The number of bytes will be equal to the length of the byte array.
public void write(byte[] b) throws IOException
ec
The write(byte[] b, int off, int len) method writes bytes from a byte array
given as parameter starting from the given offset, off, to an output stream. The number of bytes
rA
flush( )
The flush() method flushes the stream. The buffered data is written to the output stream.
Flushing forces the buffered output to be written to the intended destination. It ensures that
only those bytes which buffered are passed to operating system for writing. There is no
guarantee that the bytes will be actually written to the physical device.
public void flush() throws IOException
close()
The close() method closes the output stream. The method will release any resource
associated with the output stream.
public void close() throws IOException
©Aptech Limited
Slides 32 and 33
Let us understand the FileOutputStream class.
y
nl
O
se
rU
te
en
C
h
ec
pt
to open a file for writing. Therefore, if the file is already open, the constructors in the class
fail. An IOException will be thrown only when a read-only file is opened.
FileOutputStream(String filename)
The FileOutputStream(String filename) method creates an output file stream
object that is used to write bytes to a file. Here, filename is full path name of a file.
public FileOutputStream(String filename) throws
FileNotFoundException
©Aptech Limited
FileOutputStream(File name)
The FileOutputStream(File name) method creates an FileOutputStream object
that can be used to write bytes to a file. Here, name is a File object that describes the file.
public FileOutputStream(File name) throws FileNotFoundException
y
nl
FileOutputStream(File name, boolean flag)
The FileOutputStream(File name, boolean flag) method creates an
O
FileOutputStream object that can be used to write bytes to a file. Here, name is a File
object. If flag is true, the file is opened in append mode.
public FileOutputStream(File name, boolean flag) throws
se
FileNotFoundException
rU
Explain the Code Snippet that displays the use of FileOutputStream class mentioned in
slide 33.
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 34
Let us understand ByteArrayOutputStream class.
y
nl
O
se
Using slide 34, explain ByteArrayOutputStream class.
rU
ByteArrayOutputStream class creates an output stream in which the data is written
using a byte array. It allows the output array to grow in size so as to accommodate the new
te
data that is written.
en
ByteArrayOutputStream()
ec
ByteArrayOutputStream(int size)
rA
©Aptech Limited
Slides 35 and 36
Let us understand the methods in ByteArrayOutputStream class.
y
nl
O
se
rU
te
en
C
h
ec
pt
Tell the students that the class inherits all the methods of the OutputStream class. The
methods of this class allow retrieving or converting data. Methods of this class can be invoked
even after the output stream has been closed and will not generate IOException.
Fo
reset()
The reset() method erases all the bytes that have been written so far by setting the value to
0.
public void reset()
©Aptech Limited
size()
The size() method returns the number of bytes written to the buffer.
public int size()
toByteArray()
The toByteArray() method creates a newly allocated byte array containing the bytes that
have been written to this stream so far.
public byte[] toByteArray()
writeTo(OutputStream out)
The writeTo(OutputStream out) method writes all the bytes that have been written to
y
this stream from the internal buffer to the specified output stream argument.
nl
public void writeTo(OutputStream out) throws IOException
O
toString()
The toString() method converts the content of the byte array into a string. The method
converts the bytes to characters according to the default character encoding of the platform.
se
public String toString()
rU
Explain the Code Snippet that displays the use of the ByteArrayOutputStream class
mentioned in slide 36.
In-Class Question:
te
After you finish explaining OutputStream class, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
en
C
Answer:
ec
The size() method is used to know the current size of the buffer.
pt
rA
Fo
©Aptech Limited
Slides 37 to 44
Let us understand the filter streams.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
y
nl
O
se
rU
te
en
C
h
stream as its basic source of data. The FilterOutputStream class streams are over
existing output streams. They either transform the data along the way or provide additional
rA
functionality.
FilterInputStream:
Fo
The FilterInputStream class overrides all the methods of the InputStream class
that pass all requests to the contained input stream. The subclasses can also override
certain methods and can provide additional methods and fields.
©Aptech Limited
Following are the methods of this class:
mark(int readlimit):This method identifies the current position in the input stream.
markSupported():This method checks if the input stream supports the mark and reset
methods.
read(): This method reads the next byte of data from the input stream.
available(): This method returns an approximation of bytes that can be read or
skipped from the input stream.
close(): This method closes the input stream and releases any system resources related
with the stream.
y
read(byte[] b): This method reads byte.length bytes of data from the input
nl
stream into an array of bytes.
reset(): This method repositions the pointer to the position in the stream when the
O
mark method was last invoked on the input stream.
skip(long n): This method skips and discards n bytes of data from the input stream.
read(byte[] b, int off, int len): This method reads len bytes of data from
se
the input stream into an array of bytes.
rU
Explain the Code Snippet that demonstrates the use of FilterInputStream class
mentioned in slides 38 to 40.
te
A FilterInputstream contains some other input stream, which it uses as its basic
source of data, possibly transforming the data along the way or providing additional
en
functionality.
FilterOutputStream Class:
C
can also override certain methods and give additional methods and fields.
class. This creates an output stream filter that exist class over the defined output stream.
Explain the Code Snippet that demonstrates the use of FilterOutputStream class
Fo
©Aptech Limited
Slide 45
Let us understand the buffered streams.
y
nl
O
se
Using slide 45, explain the buffered streams.
rU
A buffer is a temporary storage area for data. By storing the data in a buffer, time is saved as
data is immediately received from the buffer instead of going back to the original source of
te
the data.
en
Java uses buffered input and output to temporarily cache data read from or written to a
stream. This helps programs to read or write small amounts of data without adversely
C
Buffer allows skipping, marking, and resetting of the stream. Filters operate on the buffer,
h
which is located between the program and the destination of the buffered stream.
ec
pt
rA
Fo
©Aptech Limited
Slide 46
Let us understand the BufferedInputStream class.
y
nl
O
se
Using slide 46, explain the BufferedInputStream class.
rU
BufferedInputStream class allows the programmer to wrap any InputStream class
into a buffered stream. The BufferedInputStream act as a cache for inputs. It does so
te
by creating the array of bytes which are utilized for future reading.
en
BufferedInputStream(InputStream in)
pt
The constructor creates a buffered input stream for the specified InputStream instance.
The default size of the buffer is 2048 byte.
rA
The constructor creates a buffered input stream of a given size for the specified
InputStream instance.
public BufferedInputStream(InputStream in, int size)
BufferedInputStream reads data from a memory area known as buffer. The native
input API is called only when the buffer is empty.
©Aptech Limited
Slide 47
Let us understand the BufferedOutputStream class.
y
nl
O
se
Using slide 47, explain the BufferedOutputStream class.
rU
BufferedOutputStream creates a buffer which is used for an output stream. It
provides the same performance gain that is provided by the BufferedInputStream
te
class.
en
The main concept remains the same, that is, instead of going every time to the operating
system to write a byte, it is cached in a buffer. It is the same as OutputStream except
C
that the flush() method ensures that the data in the buffer is written to the actual
physical output device.
h
BufferedOutputStream(OutputStream os)
pt
BufferedOutputStream writes data to buffer. The native output API is called only
when the buffer is full. Buffering can speed up Input/Output quite a bit. You can write a
larger block at a time, rather than write one byte at a time to the network or disk.
Tips:
BufferedInputStream and BufferedOutputStream are much faster for disk
access and larger data amounts.
©Aptech Limited
Slides 48 to 51
Let us understand the character streams.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 48 to 51, explain the character streams.
se
Byte stream classes provide methods to handle any type of I/O operations except Unicode
characters. Character streams provide functionalities to handle character oriented
rU
input/output operations. They support Unicode characters and can be internationalized.
Reader and Writer are abstract classes at the top of the class hierarchy that supports
te
reading and writing of Unicode character streams. All character stream class are derived
from the Reader and Writer class.
en
Character streams are often wrapper for byte streams. The Character streams use byte
C
stream to perform physical I/O, while the character stream handles translation between
character and byte.
h
Reader Class
ec
Reader class is an abstract class used for reading character streams. The subclasses of this
pt
class override some of the methods present in this class to increase the efficiency and
functionality of the methods. All the methods of this class throw an IOException. The
rA
Reader classes are similar to input streams. It descends from the abstract reader class.
Fo
Writer Class
Writer class is an abstract class and supports writing characters into streams through
methods that can be overridden by its subclasses. The methods of the java.io.Writer
class are same as the methods of the java.io.OutputStream class. All the methods of
this class throw an IOException in case of errors.
Writer classes are similar to output streams. It descends from the abstract Writer
class.
©Aptech Limited
PrintWriter Class
The PrintWriter class is a character-based class that is useful for console output. It
implements all the print methods of the PrintStream class. It does not have methods for
writing raw bytes. In such a case, a program uses unencoded byte streams.
The PrintWriter class differs from the PrintStream class as it can handle multiple
bytes and other character sets properly. This class provides support for Unicode characters.
The class overrides the write() method of the Writer class with the difference that
none of them raise any IOException.
y
nl
The printed output is tested for errors using the checkError() method. The
PrintWriter class also provides support for printing primitive data types, character
O
arrays, strings, and objects. It provides formatted output through its print() and
println() methods. The toString() methods will enable the printing of values of
objects.
se
Difference between print() and println() methods
rU
The main advantage of the print() and println() method is that any Java object or literal
or variable can be printed by passing it as an argument. If the autoFlush option is set to true,
then automatic flushing takes place when println() method is invoked. The println()
te
method follows its argument with a platform dependent line separator. The print() method
does not flush the stream automatically. Otherwise, both these methods are same.
en
Explain the Code Snippet that displays the use of the PrintWriter class mentioned in
slide 51. An instance of the PrintWriter class is created. The println() method is used
h
In-Class Question:
After you finish explaining character streams, you will ask the students an In-Class question.
pt
Name the two classes which are used for working with the character stream.
Fo
Answer:
Reader and Writer class
©Aptech Limited
Slide 52
Let us understand CharArrayReader class.
y
nl
O
se
Using slide 52, explain CharArrayReader class.
rU
CharArrayReader class is a subclass of Reader class. The CharArrayReader class
implements a character buffer that can be used as a character-input stream.
te
The constructors of this class are as follows:
en
CharArrayReader(char arr[])
C
Explain the Code Snippet that displays the use of the CharArrayReader class mentioned
in slide 52. In the code, the content of the entire string is stored as a series of characters in the
character array, ch, by using the getChars() method. Next, an instance of
Fo
CharArrayReader is created and initialized with the first five characters from the array.
Tips:
To understand the methods of the CharArrayReader class, visit the link,
http://docs.oracle.com/javase/7/docs/api/java/io/CharArrayRead
er.html
©Aptech Limited
Slides 53 and 54
Let us understand CharArrayWriter class.
y
nl
O
se
rU
te
en
C
h
ec
pt
CharArrayWriter()
The CharArrayWriter() constructor creates a CharArrayWriter with a buffer
having a default size of 32 characters.
©Aptech Limited
CharArrayWriter(int num)
The CharArrayWriter(int num) constructor creates a CharArrayWriter with a
buffer of size specified by the variable num.
Explain the Code Snippet that displays the use of the CharArrayWriter class mentioned
in slide 54.
In the code, the content of the entire string is stored as a series of characters in the character
array, ch, by using the getChars() method. Next, the instance of CharArrayWriter
contains the content from the character array. The toCharArray() method is used to store
the content of the CharArrayWriter in a character array. Finally, the content is printed.
y
nl
Tips:
To understand the methods of the CharArrayReader class, visit the link,
O
http://docs.oracle.com/javase/7/docs/api/java/io/CharArrayWrit
er.html
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 55
Let us understand chaining I/O systems.
y
nl
O
se
Using slide 55, explain chaining I/O systems.
rU
A program, typically, uses a series of streams to process the data. Chaining is very simple.
The output of one stream becomes input to the other. Or to say, we pass an object of one
te
stream as parameter to another stream constructor.
en
For example, the derived classes of FilterInputStream class takes input from a stream
and filters it so that when you read from this stream, you get a filtered view of input. Similar
C
Filtering means that the filter stream provides additional functionality such as buffering,
h
monitoring line numbers, or aggregating data bytes into more meaningful primitive data
ec
type units. Thus, filter streams can work in chain with Input or Output streams. In other
words, each subsequent class accesses the output of the previous class through the variable.
pt
Explain the figure that displays the chaining of an output stream mentioned in slide 55.
rA
Fo
©Aptech Limited
Following code snippet shows chaining of streams using character stream classes:
try {
FileReader fr = new FileReader("C:\\employee.txt");
BufferedReader br = new BufferedReader(fr);
LineNumberReader lr = new LineNumberReader(br);
} catch (IOException e) {
System.out.println(e.getMessage());
}
y
nl
Here, the FileReader actually reads from source file. The BufferedReader uses the
FileReader object to read input from. The LineNumberBuffer reads from the
O
BufferedReader object and allocates line numbers to each line.
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 56
Let us understand Serialization.
y
nl
O
se
Using slide 56, explain Serialization.
rU
Serialization is a mechanism provided by Java where an object can be represented as a
sequence of bytes that includes the objects data as well as information about the object’s
te
type and the types of data stored in the object.
en
Serialization is the process of reading and writing objects to a byte stream. An object that
implements the Serializable interface will have its state saved and restored using
C
If a superclass is serializable, then its subclasses are also serializable. The only exception is if
rA
a variable is transient and static, its state cannot be saved by serialization facilities. When
the serialized form of an object is converted back into a copy of the object, this process is
called deserialization.
Fo
©Aptech Limited
Slides 57 and 58
Let us understand ObjectOutputStream class.
y
nl
O
se
rU
te
en
C
h
ec
pt
©Aptech Limited
ObjectOutputStream(OutputStream out)
The ObjectOutputStream(OutputStream out) constructor creates an
ObjectOutputStream that writes to the specified OutputStream.
writeFloat(float f)
The writeFloat(float f) method writes a float value to the output stream. Its
y
signature is as follows:
nl
public void writeFloat(float f) throws IOException
O
writeObject (Object obj)
The writeObject (Object obj) method writes an object, obj, to the output stream.
Its signature is as follows:
se
public final void writeObject(Object obj) throws IOException
defaultWriteObject()
rU
The defaultWriteObject() method writes non-static and non-transient fields into the
underlying output stream. Its signature is as follows:
public void defaultWriteObject() throws IOException
te
en
Explain the Code Snippet that displays the use of methods of ObjectOutputStream
class mentioned in slide 58.
C
The ObjectOutputStream class serializes an object into a stream to perform the following
actions:
pt
©Aptech Limited
Slides 59 to 63
Let us understand ObjectInputStream class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
rU
te
en
C
h
ec
ObjectInputStream()
The ObjectInputStream() constructor helps subclasses to re-implement
ObjectInputStream to avoid allocation of private data used by the implementation
of ObjectInputStream. Its signature is as follows:
protected ObjectInputStream() throws IOException,
SecurityException
©Aptech Limited
ObjectInputStream(InputStream in)
The ObjectInputStream(InputStream in) constructor creates an
ObjectInputStream that reads from the specified InputStream. Serialized
objects are read from input stream in.
Its signature is as follows: public ObjectInputStream(InputStream in)
throws IOException
readFloat()
The readFloat() method reads and returns a float from the input stream. Its
y
signature is as follows:
nl
public float readFloat() throws IOException
O
readBoolean()
The readBoolean() method reads and returns a boolean from the input stream. Its
se
signature is as follows:
public boolean readBoolean() throws IOException
readByte()
rU
The readByte() method reads and returns a byte from the input stream. Its
signature is as follows:
te
public byte readByte() throws IOException
readChar()
en
The readChar() method reads and returns a char from the input stream. Its signature
is as follows:
C
readObject()
h
The readObject() method reads and returns an object from the input stream. Its
ec
signature is as follows:
public final Object readObject() throws IOException,
ClassNotFoundException
pt
©Aptech Limited
Following steps have been followed in the program:
In-Class Question:
y
nl
After you finish explaining ObjectInputStream class, you will ask the students an In-
Class question. This will help you in reviewing their understanding of the topic.
O
se
Why readObject() method is used in ObjectInputStream class?
Answer:
It restores an object containing non-static and non-transient fields.
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 64
Let us summarize the session.
y
nl
O
se
Using slide 64, summarize the session. End the session with a brief summary of what has
been taught in the session.
rU
te
5.3 Post Class Activities for Faculty
You should familiarize yourself with the topics of the next session which is new features in
en
File Handling.
Tips:
C
You can also check the Articles/Blogs/Expert Videos uploaded on the OnlineVarsity site to
gain additional information related to the topics covered in the next session. You can also
h
connect to online tutors on the Online Varsity site to ask queries related to the sessions.
ec
pt
rA
Fo
©Aptech Limited
Session 6 – New Features in File Handling
Here, you can ask students the key topics they can recall from previous session. Prepare a question
or two which will be a key point to relate the current session objectives.
y
6.1.1 Objectives
nl
By the end of this session, the learners will be able to:
O
Describe the Console class
Explain the DeflaterInputStream class
se
Explain the InflaterOutputStream class
Describe the java.nio Package
Describe the file system
that help to enhance the I/O processing task in the Java application development.
You should teach the concepts in the theory class using the images provided. For teaching in
C
the class, you are expected to use slides and LCD projectors.
h
Tips:
ec
It is recommended that you test the understanding of the students by asking questions in
between the class.
pt
In-Class Activities:
rA
©Aptech Limited
Overview of the Session:
Then give the students the overview of the current session in the form of session objectives.
Show the students slide 2 of the presentation.
y
nl
O
se
rU
Tell the students that this session introduces the Console class and the classes that help to
compress and decompress the data. The java.nio API package that help to enhance the
I/O processing task in the Java application development. The session also introduces file
te
systems, paths, and files.
en
C
h
ec
pt
rA
Fo
©Aptech Limited
6.2 In-Class Explanations
Slide 3
Let us understand the overview of the NIO package.
y
nl
O
se
rU
Using slide 3, explain the overview of the NIO package.
te
NIO in Java stands for new Input/Output operation. It is a collection of Java APIs that offers
intensive I/O operations.
en
The java.nio.file package provides comprehensive support for input and output
C
operations. The java.nio package mainly defines buffers which are containers for data.
This API is easy to use.
h
ec
pt
rA
Fo
©Aptech Limited
Slides 4 to 6
Let us understand the Console class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Consider a scenario, where as a software developer you would not like to display the
characters typed by the user for a console based application such as user login. Earlier, this
was possible only with GUI based application.
Java SE 6 came up with a solution by introducing the Console class. The Console class
is a part of java.io package that has the ability to read text from the terminal without
echoing on the screen. The Console object provides input and output of character
streams through its Reader and Writer class.
The Console class provides various methods to access character-based console device.
y
These devices should be associated with the current virtual machine. Automatic invocation
nl
of virtual machine will not have a console associated with it. There are no public
constructors for the Console class.
O
To obtain an instance of the Console class, you need to invoke the System.console()
method. The System.console() method returns the Console object if it is available;
se
otherwise, it returns null.
rU
Following are the various methods available in the Console class:
format(String fmt, Object... args) - This method writes a formatted
string to this console's output stream using the specified format string and arguments.
te
printf(String fmt, Object... args) - This method is used to write a
formatted string to this console's output stream using the specified format string and
en
arguments.
reader()- This method retrieves the unique Reader object associated with this
C
console.
readLine() - This method reads a single line of text from the console.
readLine(String fmt, Object... args) - This method provides a
h
formatted prompt, then reads a single line of text from the console.
ec
readPassword()- This method reads password from the console without echoing on the
screen. The method returns a character array and not a String object to enable
pt
Explain the Code Snippet that shows the use of Console class methods mentioned in
slides 5 and 6. The code accepts user name and password from the user through a console
using the readLine() and readPassword() methods. The System.console()
Fo
method returns a Console object if it is available that reads the username and password.
©Aptech Limited
Slide 7
Let us understand classes in the java.util.zip.
y
nl
O
se
Using slide 7, explain classes in the java.util.zip package.
rU
java.util.zip provides classes for reading and writing the standard ZIP and GZIP file
formats. It also include classes for compressing and decompressing data.
te
List and explain classes in java.util.zip mentioned in slide 7.
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 8 and 9
Let us understand the Deflater class.
y
nl
O
se
rU
te
en
C
h
ec
pt
The Deflater class compresses the data present in an input stream. It compresses the
data using the ZLIB compression library.
Fo
The constructor of the Deflater class is used to create instances of the Deflater class.
Its syntax is as follows: public Deflater()
©Aptech Limited
deflate(byte[] buffer, int offset, int len) - Fills the output
buffer with compressed data and returns the actual size of compressed data in integer.
Here, buffer is the specified buffer used to store compressed data, offset is the
start location of the data, and len is the maximum number of bytes of compressed
data.
setInput(byte[] buffer) - Sets the input data present in buffer for
compression.
setInput(byte[] buffer, int offset, int len) - Sets the input data
present in buffer for compression. Here, buffer is the specified buffer used to store
input data bytes, offset is the start location of the data, and len is the length of
y
input data.
nl
finish() - Indicates that the compression should end with the current contents of
O
the input buffer
end() - Closes the compressor and discards the unprocessed input.
se
Explain the Code Snippet that shows the use of methods in Deflater class mentioned in
slide 9.
rU
In the code, the input string is initialized and encoded to a byte array. Next, it creates an
object of the Deflater class, which invokes the setInput() method that sets the
input data for compression. The Deflater object then invokes the deflate() method
te
to compress the input string. After compression, the deflate() method returns the
en
number of bytes of compressed data which is stored in an integer variable. The value is then
displayed. The method helps to obtain the size of the compressed file in bytes.
C
Deflater class provides support for general purpose data compression. The class uses
GZIP data compression algorithms. The DeflaterOutputStream uses an internal
h
Tips:
You do not need to create a Deflater, instead you can use an instance of one of the
pt
©Aptech Limited
Slides 10 to 12
Let us understand the Inflater class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
The Inflater class decompresses the compressed data. This class supports
decompression using the ZLIB compression library.
y
the specified buffer used to store the decompressed data, offset is the start location
of the data, and len is the maximum number of bytes of decompressed data.
nl
O
setInput(byte[] buffer) - Sets the input data present in the buffer for
decompression.
se
setInput(byte[] buffer, int offset, int len) - Sets the input data
rU
present in the buffer for decompression. Here, buffer is the specified buffer used to
store compressed data bytes, offset is the start location of the data, and len is the
length of compressed data.
te
end() - Closes the decompressor.
en
Explain the Code Snippet that shows the use of methods in Inflater class mentioned in
C
slides 11 and 12. In the code, the input data for decompression is set using the Inflater
object. Next, the Inflater object invokes the inflate() method to decompress the
h
compressed data. After decompression, the result is stored in the byte array, result.
ec
In-Class Question:
pt
After you finish explaining Inflater class, you will ask the students an In-Class question.
rA
Answer:
Using the ZLIB compression library.
©Aptech Limited
Slides 13 to 17
Let us understand the DeflaterInputStream class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
rU
te
en
C
h
ec
The DeflaterInputStream class reads the source data from an input stream and then
pt
compresses it in the ‘deflate’ compression format. This class provides its own constructors
that are as follows:
rA
The constructor creates an input stream of bytes to read the source data with a default
compressor and buffer size.
DeflaterInputStream(InputStream in, Deflater defl)
The constructor creates a new input stream with a default buffer size and the specified
compressor.
DeflaterInputStream(InputStream in, Deflater defl, int bufLen)
The constructor creates a new input stream with the specified buffer size and the
specified compressor.
©Aptech Limited
Following are the various methods available in the DeflaterInputStream class:
read() - Returns one byte of compressed data read from an input stream.
close() - Closes the input stream after reading the remaining source data.
y
boolean markSupported() - Returns false. This is because the input stream
nl
does not support the mark() and reset() methods.
O
int available() - Returns 0 after EOF is reached. It returns 1 otherwise.
se
long skip(long n) - Skips and discards data from the input stream.
rU
Explain the Code Snippet that shows the use of methods in DeflaterInputStream
te
class mentioned in slides 14 to 17. The increaseArray() method in the code creates a
dynamic array to store the size of the compressed file. The path of the source file is
en
specified as an argument to the instance of the File class. The File object is then
passed as a parameter to the FileInputStream object. Next, the
FileInputStream object is passed as a parameter to the DeflaterInputStream
C
instance. A byte array is created for storing the deflated data. The
DeflaterInputStream object invokes the read() method to read data from the
h
source file. The compressed data is stored in the buffer, input. The
ec
©Aptech Limited
Slides 18 to 20
Let us understand the DeflaterOutputStream class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
The DeflaterOutputStream class reads the source data, compresses it in the ‘deflate’
compression format, and then writes the compressed data to a predefined output stream. It
also acts as the base for other types of compression filters, such as GZIPOutputStream.
y
be written in bytes, offset is the start location of input data, and buffSize is the
size of buffer.
nl
O
deflate() - Compresses the source data and then writes the next block of
compressed data to the output stream.
se
close() - Closes the output stream after writing the remaining compressed data.
rU
finish() - Completes the process of writing compressed data to the output stream
without closing it.
te
Explain the Code Snippet that shows the use of methods in DeflaterOutputStream
en
In the code, two File objects are created, filein and fileout; where, filein
holds the location of source file and fileout holds the location of compressed file. The
object, filein is passed as a reference to the FileInputStream and the object,
h
DeflaterOutputStream object reads the Hello.txt file and compresses it. Finally,
the FileInputStream object named finRead invokes the write() method to
pt
©Aptech Limited
Slides 21 to 23
Let us understand the InflaterInputStream class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
The InflaterInputStream class reads the compressed data and decompresses it in
the ‘deflate’ compression format.
The constructor creates an input stream of bytes to read the compressed data with a default
decompressor and buffer size.
y
read(byte[] buffer, int offset, int buffSize) - Returns the
nl
number of bytes of decompressed data read into a byte array from the start location
specified by offset and of buffSize long.
O
Explain the Code Snippet that shows the use of methods in InflaterInputStream
se
class mentioned in slides 22 and 23.
The code creates two File objects, fout and finf; where, fout holds the location
rU
of compressed file and finf holds the location of decompressed file. The object, fout is
passed as a reference to the FileInputStream and the object, finf is passed as a
reference to the FileOutputStream. The InflaterInputStream object reads the
te
data in the FileInputStream object, decompresses the compressed data, and then
invokes the write() method to write the decompressed data to the output file named
en
InflatedMain.java.
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 24 to 26
Let us understand the InflaterOutputStream class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
The InflaterOutputStream class reads the compressed data, decompresses the data
stored in the deflate compression format, and then writes the decompressed data to an
output stream. This class also serves as the base class for the decompression class named
GZIPInputStream.
The constructor creates an output stream of bytes to write decompressed data with a
default decompressor and buffer size.
y
write(byte[] buffer, int offset, int buffSize) - Writes an array
nl
of bytes of decompressed data to the output stream. Here, buffer is the input data in
O
bytes, offset is the start location of input data, and buffSize is the size of buffer.
se
close() - Closes the output stream after writing the remaining uncompressed data.
finish() - Completes writing decompressed data to the output stream without
rU
closing the underlying output stream.
Explain the Code Snippet that shows decompression of data using the methods of
te
InflaterOutputStream class mentioned in slides 25 and 26. The
InflaterOutputStream object reads the FileOutputStream object, compresses
en
the input data, and then invokes the write() method to write the decompressed data to
the output file named InflatedMain.java.
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 27
Let us understand the java.nio package.
y
nl
O
se
Using slide 27, explain java.nio Package.
rU
Non-blocking I/O (usually called NIO, and sometimes called ’New I/O’ is a collection of Java
programming language APIs that offer features for intensive I/O operations. It was
te
introduced with the J2SE 1.4 release of Java by Sun Microsystems to complement an
existing standard I/O.
en
In Java SE 7, an extension to NIO that offers a new file system API, called NIO2 is released.
C
NIO APIs provide access to the low-level I/O operations for the I/O stream.
h
NIO is platform dependent and its ability to enhance application performance depends on
ec
the following:
OS
pt
Specific JVM
Mass storage characteristics
rA
Data
Host virtualization context
Fo
©Aptech Limited
Selectors - These along with selectable channels define a multiplexed, non-
blocking I/O facility. Non-blocking I/O is event based which means that a selector is
defined for an I/O channel and then processing happens. When an event takes place
such as the arrival of an input, on the selector, the selector wakes up and executes.
This can be performed using a single thread. The channel and selector APIs are
defined in the java.nio.channels package.
The rest of the components, such as Pipe and FileLock are utility classes to be used in
conjunction with the three core components.
In-Class Question:
y
nl
After you finish explaining java.nio package, you will ask the students an In-Class
O
question. This will help you in reviewing their understanding of the topic.
se
What are the central features of NIO APIs?
Answer:
Charset
Channel
Selectors
rU
te
Buffers
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 28 and 29
Let us understand File Systems, Paths, and Files.
y
nl
O
se
rU
te
en
C
h
ec
pt
Using slides 28 and 29, explain File Systems, Paths, and Files.
rA
File Systems
A file system stores and organizes files on media, typically hard drives. Typically, files are
Fo
stored in a hierarchical structure, where there is a root node. Below this node exist files and
directories.
Each directory can contain files and subdirectories, which can contain files and
subdirectories and so on. There is no limit to the hierarchical structure. File systems can
have one or more root directories. File systems have different characteristics for path
separators.
©Aptech Limited
Path
Every file is identified through its path. It starts from the root node. File system include
different characteristics for path separators. For example, Microsoft Windows uses the
backslash slash (\) and the Solaris OS uses the forward slash (/).
Files
y
Before JDK 7, the java.io.File class was used for performing all file and directory
nl
operations.
O
NIO.2 includes the following new package and classes:
java.nio.file.Path: This uses a system dependent path to locate a file or a
se
directory.
java.nio.file.Files: This uses a Path object to perform operations on files and
directories.
rU
java.nio.file.FileSystem: This provides an interface to a file system. This also
helps to create a Path object and other objects to access a file system.
te
With NIO.2 the two process have been separated. In NIO.2, it is the Path interface that
en
helps to create and control paths. It is the Files class that executes operations on files
and directories. The Files class operates only on Path objects. The Files class
methods that operate directly on the file system throws an IOException.
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 30
Let us understand symbolic links.
y
nl
O
se
Using slide 30, explain symbolic links.
rU
A symbolic link is a reference to another file and is transparent to applications and users.
Operations on symbolic links are automatically redirected to the target of the link. Here, the
te
target is the file or directory that is pointed to.
en
Typically, directories or files are file system objects. However, there are some file systems
which also support the notion of symbolic links. Symbolic link is also referred to as a soft link
C
or symlink.
h
ec
pt
rA
Fo
©Aptech Limited
Slides 31 to 33
Let us understand the Path interface.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
The java.nio.file.Path interface object can help to locate a file in a file system.
Typically, the interface represents a system dependent file path.
A Path is hierarchical. It includes a sequence of directory and file name elements. These are
separated by a delimiter.
The Path class is a programmatic representation of a path in the file system. A Path object
contains the file name and directory list used to construct the path, and is used to examine,
locate, and manipulate files.
y
Path can be relative or absolute. An absolute path always contains the root element and the
nl
complete directory list required to locate the file. For
example, /home/sally/statusReport is an absolute path. All of the information
O
needed to locate the file is contained in the path string.
se
A relative path needs to be combined with another path in order to access a file. For
example, loe/foo is a relative path.
A root
A root and a sequence of names
h
Explain methods of the Path interface that can be grouped based on their common
functionalities mentioned in slide 32.
pt
Explain the Code Snippet that displays the use of the Path interface mentioned in slide 33.
rA
Fo
©Aptech Limited
Slide 34
Let us understand working with links.
y
nl
O
se
Using slide 34, explain how to work with links.
rU
Path interface is link aware and every method either detects what to do or provides an
option to configure the behavior when a symbolic link is encountered. While certain file
te
systems support symbolic link, certain support hard links. Hard links differ from symbolic
links.
en
Tips:
Hard links are generally not allowed on directories and to cross partitions or volumes.
pt
rA
Fo
©Aptech Limited
Slides 35 to 51
Let us understand about tracking file system and directory changes.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
y
nl
O
se
rU
te
en
C
h
ec
Using slides 35 to 51, explain how to track file system and directory changes.
Static methods in the java.nio.file.Files class perform primary functions for the
pt
Path objects. The methods in the class can identify and automatically manage symbolic
links.
rA
©Aptech Limited
Copying a file or directory
Explain the Code Snippet that shows how to use the copy() method mentioned in slide
36.
Directories can be copied but the files inside the directory are not copied, so the new
directory is empty even when the original directory is empty.
y
Moving a file or directory
nl
To do so, use the move method. If the target file exists, the REPLACE_EXISTING option
O
should be used. Otherwise, the move fails. The method takes a varargs argument.
Explain the syntax that shows how to use the move() method mentioned in slide 37.
se
Empty directories can be moved. If the directory is not empty, the move is allowed when
rU
the directory can be moved without moving the contents of that directory.
particular path exists. The methods in the Path class operate on the Path instance.
Following are the Files methods for checking the existence of Path instance:
C
exists: These check if the file exists. By default, it uses symbolic links.
notExists: These check if the file does not exist.
h
©Aptech Limited
When testing a file’s existence, one of the following is the possible outcome:
The file is verified to not exist.
The file is verified to exist.
The existence of the file cannot be verified.
The file’s status is unknown.
The delete(Path) method can be used to delete a file, directories, or links. The deletion
y
will fail if the directory is not empty. The method throws an exception if the deletion fails. If
nl
the file does not exist, a NoSuchFileException is thrown.
O
To determine the reason for the failure, the exception can be caught as shown in the Code
Snippet mentioned in slide 40.
se
Listing a directory’s content
rU
To do so, use the DirectoryStream class that iterates over all the files and directories
from any Path directory.
te
Consider the following exceptions:
DirectoryIteratorException is thrown if there is an I/O error while iterating
en
Explain the Code Snippet that displays the use of DirectoryStream class mentioned in
slides 41 and 42.
h
ec
To read from files, use the readAllBytes or ReadAllLines methods that will read
the entire content of the file.
Explain the Code Snippet that shows the use of ReadAllLines method mentioned in
slide 44.
©Aptech Limited
Reading a file by using buffered stream I/O
Explain the Code Snippet that demonstrates the use of newBufferedReader() method
mentioned in slides 45 and 46.
y
Files can be non-sequentially or randomly accessed using the SeekableByteChannel
nl
interface.
O
To randomly access a file, perform the following:
Open the file.
se
Find the particular location.
Read from the file or write to the file.
rU
The SeekableByteChannel interface extends channel I/O and includes various
methods to set the position. The data can then be read from the location or written to it.
te
The interface includes the following methods:
en
read(ByteBuffer)
write(ByteBuffer)
truncate(long)
C
position
position(long)
h
ec
Explain the Code Snippet that displays the use of the methods of random access file
mentioned in slides 48 to 51.
pt
To access a file randomly, you open the file, seek a particular location, and read from or
rA
In-Class Question:
Fo
After you finish explaining Tracking File System and Directory Changes, you will ask the
students an In-Class question. This will help you in reviewing their understanding of the
topic.
Answer:
PatternSyntaxException
©Aptech Limited
Slide 52
Let us understand tracking file system using WatchService and PathMatcher.
y
nl
O
se
Using slide 52, explain how to track file system using WatchService and PathMatcher.
rU
The FileSystem class provides an interface to a file system and is the factory for objects
to access files and other objects in the file system.
te
en
getPath()
getPathMatcher()
h
getFileStores()
ec
A FileSystem can provide read-only or read-write access to the file system. Any attempt to
write to file stores using an object with a read-only file system throws
pt
ReadOnlyFileSystemException.
rA
Fo
©Aptech Limited
Slide 53
Let us understand WatchService.
y
nl
O
se
Using slide 53, explain WatchService.
rU
Tell the students that WatchService is provided in the java.nio.file package.
A WatchService watches registered objects for changes and events. Multiple concurrent
te
consumers can use a WatchService. A file manager can use a WatchService to check
a directory for changes such as when files are created or deleted.
en
When a change or event for an object occurs, the key is signaled or queued to the
WatchService. This helps consumers to retrieve the key and process the events when
h
After the events are processed, the consumer invokes the key’s reset() method. This
pt
resets the key. The key is then signaled and re-queued with further events. To cancel a
registration with a WatchService, the key’s cancel() method is invoked.
rA
objects for changes and events. It is one of the interesting features of the
java.nio.file package. The WatchService does not pick up events for sub-
directories of a watched directory.
Tips:
Watch keys are thread safe and can be used with the java.nio.concurrent
package.
For more explanation and example on WatchService, you can visit the link:
http://docs.oracle.com/javase/tutorial/essential/io/notif
ication.html#register
©Aptech Limited
Slides 54 to 59
Let us understand PathMatcher interface.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
To locate a file one would search directory. One could use a search tool or the
PathMatcher interface which has a match method that determines whether a Path
object matches a specified string. The PathMatcher interface is implemented by objects
to match operations on paths.
y
C:\\*
nl
*.java
*.*
O
The java.nio.PathMatcher interface has a match method to determine whether a
se
Path object matches the specified search string. The FileSystem factory methods can
be used to retrieve the PathMatcher instance.
failure happens.
C
throws an IOError. This class can be extended and only the required methods is required to
be overridden.
Fo
Explain the Code Snippet that displays the use of PatternMatcher and the
SimpleFileVisitor class to search for a file based on a pattern mentioned in slides 56
to 59.
©Aptech Limited
Slides 60 and 61
Let us understand file class and file attributes.
y
nl
O
se
rU
te
en
C
h
ec
pt
Using slides 60 and 61, explain file class and file attributes.
rA
In a file system, the files and directories include data. It is the metadata that tracks
information about each object in the file system. Information can be such as the file creation
date, the last file modified date, file owner, and so on.
Fo
The file attributes can be achieved by the methods of the Files class mentioned in slides 60
and 61.
To obtain a set of attributes, the Files class includes the following two
readAttributes() methods to get a file’s attributes in one bulk operation:
©Aptech Limited
The basic attributes of a file system includes the following time stamps:
creationTime
lastModifiedTime
lastAccessTime
The File Attribute class provides the attributes of a file or directory. It can be used to
determine various file properties such as file attributes (read-only, hidden, system, or
directory).
In-Class Question:
y
nl
After you finish explaining file class and file attributes, you will ask the students an In-Class
O
question. This will help you in reviewing their understanding of the topic.
se
What refers to file attributes of a file system?
Answer:
Metadata rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 62 and 63
Let us understand DOS file attributes.
y
nl
O
se
rU
te
en
C
h
ec
pt
File systems other than DOS such as Samba also support DOS file attributes.
Fo
A file attribute view that provides a view of the legacy ’DOS’ file attributes. These attributes
are supported by file systems such as the File Allocation Table (FAT) format commonly used
in consumer devices.
Name Type
readonly Boolean
hidden Boolean
©Aptech Limited
system Boolean
archive Boolean
Explain the Code Snippet that shows the use of the methods of the DosFileAttributes
class mentioned in slides 62 and 63. A DOS attribute can be set on a file using the
setAttribute(Path, String, Object, LinkOption...) method.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 64
Let us summarize the session.
y
nl
O
se
rU
Using slide 64, summarize the session. End the session with a brief summary of what has
been taught in the session.
te
6.3 Post Class Activities for Faculty
en
You should familiarize yourself with the topics of the next session which is introduction to
threads.
C
Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the OnlineVarsity site to
h
gain additional information related to the topics covered in the next session. You can also
ec
connect to online tutors on the OnlineVarsity site to ask queries related to the sessions.
pt
rA
Fo
©Aptech Limited
Session 7 – Introduction to Threads
Here, you can ask students the key topics they can recall from previous session. Prepare a
question or two which will be a key point to relate the current session objectives.
y
nl
7.1.1 Objectives
By the end of this session, the learners will be able to:
O
Introduction to Thread
Creating Threads
se
Thread States
Methods of Thread class
Managing Threads
Daemon Threads rU
te
7.1.2 Teaching Skills
To teach this session, you should be well-versed with the concept of threads and how to
en
create a thread object. You should also be well-versed with different states of thread object,
methods of the thread class, and the daemon thread.
C
You should teach the concepts in the theory class using the images provided. For teaching in
the class, you are expected to use slides and LCD projectors.
h
ec
Tips:
It is recommended that you test the understanding of the students by asking questions in
pt
In-Class Activities:
Follow the order given here during In-Class activities.
Fo
©Aptech Limited
Overview of the Session:
Then give the students the overview of the current session in the form of session objectives.
Show the students slide 2 of the presentation.
y
nl
O
se
rU
Tell the students that this session introduces the concept of threads and how to create a
thread object. Introduce them with different states of thread object, methods of the thread
class and give overview of the daemon thread.
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
7.2 In-Class Explanations
Slide 3
Let us understand introduction to threads.
y
nl
O
se
rU
Using slide 3, explain introduction to threads. Java provides built-in support for
multithreaded programming. A multithreaded program consists of two or more parts that
te
run concurrently. Each part of such a program is called a thread. Each thread defines a
separate path for execution.
en
A process is a program that is executing. Each process has its own run-time resources, such
C
as their own data, variables, and memory space. These run-time resources constitute an
execution environment for the processes inside a program. So every process has a self-
h
contained execution environment to run independently. Each process executes several tasks
at a time and each task is carried out by separate thread.
ec
A thread is nothing but the basic unit to which the operating system allocates processor
pt
time. A thread is the entity within a process that can be scheduled for execution. A process
is started with a single thread, often called the primary, default, or main thread. So a
rA
©Aptech Limited
Slide 4
Let us understand the characteristics of threads.
y
nl
O
se
Using slide 4, explain the characteristics of threads.
rU
A thread has its own complete set of basic run-time resources to run it independently. A
thread is the smallest unit of executable code in an application that performs a particular
te
job or task. Several threads can be executed at a time, facilitating execution of several tasks
of a single application simultaneously.
en
C
Tips:
Threads share same address space and therefore can share both data and code.
h
ec
pt
rA
Fo
©Aptech Limited
Slides 5 and 6
Let us understand the similarities and differences between processes and threads.
y
nl
O
se
rU
te
en
C
h
ec
pt
Using slides 5 and 6, explain the similarities and differences between processes and threads.
rA
Tell them that in concurrent programming, there are two basic units of execution: processes
and threads. In Java programming language, concurrent programming is mostly concerned
with threads. However, processes are also important.
Fo
A computer system normally has many active processes and threads. This is true even in
systems that only have a single execution core and thus, only have one thread actually
executing at any given moment. Processing time for a single core is shared among processes
and threads through an OS feature called time slicing.
Multiple threads allow access to the same part of memory whereas processes cannot
directly access memory of another process.
©Aptech Limited
Differences
Unlike processes, threads are not independent of one another.
Unlike processes, all threads can access every address in the task.
Unlike processes, threads are designed to assist one other.
Tell the students that a process has a self-contained execution environment. A process
generally has a complete, private set of basic run-time resources; in particular, each process
has its own memory space.
Processes are often seen as synonymous with programs or applications. However, what the
y
user sees as a single application may in fact be a set of cooperating processes. To facilitate
nl
communication between processes, most operating systems support Inter Process
Communication (IPC) resources, such as pipes and sockets. IPC is used not just for
O
communication between processes on the same system, but processes on different
systems.
se
Also tell them that threads are sometimes called lightweight processes. Both processes and
threads provide an execution environment, but creating a new thread requires fewer
resources than creating a new process.
rU
Threads exist within a process — every process has at least one thread. Threads share the
te
process's resources, including memory and open files.
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 7
Let us understand application and uses of threads.
y
nl
O
se
Using slide 7, explain application and uses of threads.
rU
Some of the applications of threads are as follows:
Playing sound and displaying images simultaneously.
te
Displaying multiple images on the screen.
en
In-Class Question:
C
After you finish explaining concept of threads, you will ask the students an In-Class question.
This will help you in reviewing their understanding of the topic.
h
ec
What is a process?
pt
Answer:
rA
Processes are often seen as synonymous with programs or applications. However, what the
user sees as a single application may in fact be a set of cooperating processes. To facilitate
the communication between processes, most operating systems support Inter Process
Communication (IPC) resources, such as pipes and sockets. IPC is used not only for
communication between processes on the same system, but also for processes on different
systems.
©Aptech Limited
Slide 8
Let us understand the different ways to create threads.
y
nl
O
se
Using slide 8, explain the different ways to create threads.
rU
There are two ways to create Thread class:
• Creating a subclass of Thread class.
te
• Implementing the Runnable interface.
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 9
Let us understand subclassing Thread class.
y
nl
O
se
Using slide 9, explain subclassing Thread class.
rU
Explain the way to create a Thread object by subclassing a Thread class. Explain to
them that an easy way of creating a new thread is to derive a class from
te
java.lang.Thread class. This class consists of methods and constructors, which helps
in realizing concurrent programming concept in Java. This is used to create applications
en
which can execute multiple tasks at a given point of time. This approach fails when a class
that wants to implement thread is being derived from another class.
C
The step by step procedure to create a new thread by extending the Thread class is as
h
follows:
ec
Tell them that these are the three main steps that one needs to follow when creating a
Thread object.
Fo
©Aptech Limited
Slide 10
Let us understand creating a subclass.
y
nl
O
se
Using slide 10, explain the way to create a subclass of the Thread class.
rU
Tell them one needs to declare a class that is a subclass of the Thread class. The Thread
class is defined in the java.lang package.
te
Explain the code snippet mentioned in slide 10 that shows the implementation of the
en
©Aptech Limited
Slide 11
Let us understand overriding the run() method.
y
nl
O
se
Using slide 11, explain overriding the run() method.
rU
Tell them that inside the subclass, override the run() method defined in the Thread
class. The code in the run() method defines the functionality required for the thread to
te
execute. The run() method in a thread is analogous to the main() method in an
application. Also mention that the run() method, which is the entry point for the new
en
thread.
C
Next, explain the code snippet that displays the implementation of the run() method.
h
In-Class Question:
ec
After you finish explaining about overriding the run() method, you will ask the students an
pt
In-Class question. This will help you in reviewing their understanding of the topic.
rA
©Aptech Limited
Slide 12
Let us understand how to start the thread.
y
nl
O
se
Using slide 12, explain how to start the thread.
rU
Mention to the students that the main() method creates an object of the class that
extends the Thread class. Next, the start() method is invoked on the object to start
te
the Thread. The start() method will place the Thread object in a runnable state.
The start() method of a thread invokes the run() method which allocates the
en
Next, explain the code snippet that displays the implementation of the start() method.
h
NewThread() {
// Create a new, second thread
super("Demo Thread");
Fo
©Aptech Limited
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
y
new NewThread(); // create a new thread
nl
try {
for(int i = 5; i > 0; i--) {
O
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
se
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
}
}
rU
System.out.println("Main thread exiting.");
te
Java provides an interface called Runnable that your class can implement in the class to
en
run from an instance of the Thread class. You can achieve this by passing the Runnable
object as an argument to the Thread constructor.
h
ec
pt
rA
Fo
©Aptech Limited
Slides 13 and 14
Let us understand constructors of the Thread class.
y
nl
O
se
rU
te
en
C
h
ec
pt
The ThreadGroup class represents a group of threads and is often used in constructors
of the Thread class.
Fo
Next, explain the different constructors of this class. They are as follows:
Thread() - Is the default constructor.
©Aptech Limited
Thread(Runnable objRun, String threadName) - Creates a new named
Thread object, where objRun is the object whose run() method is called and
threadName is the name of the thread that will be created.
y
nl
Thread(ThreadGroup group, Runnable objRun, String
threadName) - Creates a new Thread object so that it has objRun as its run
O
object, has the specified threadName as its name, and belongs to ThreadGroup
referred to by group.
se
Thread(ThreadGroup group, Runnable objRun, String
threadName, long stackSize) - Creates a new Thread object so that it
rU
has objRun as its run object, has the specified threadName as its name, belongs to the
thread group referred to by group, and has the specified stack size.
te
Thread(ThreadGroup group, String threadName) - Creates a new
en
Thread object with group as the ThreadGroup and threadName as the name of
the thread that will be created.
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 15
Let us understand the methods of the Thread class.
y
nl
O
se
Using slide 15, explain the methods of the Thread class.
rU
Explain the table mentioned on the slide to the students. Tell them that the Thread class
defines a number of methods useful for thread management. These include static
te
methods, which provide information about, or affect the status of the thread invoking the
method. The other methods are invoked from other threads involved in managing the
en
©Aptech Limited
Slides 16 to 19
Let us understand constructor and methods of the Thread class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
Using slides 16 to 19, explain constructor and methods of the Thread class.
Explain the use of methods and constructors of Thread class in an application. The code
rU
demonstrates the creation of a new thread by extending Thread class and using some of
the methods of Thread class.
te
Tell the students that in the code, NamedThread is declared as a derived class of Thread.
In the main() method of this class, a thread object objNamedThread is created by
en
instantiating NamedThread and its name is set to Thread1. The code then checks to see if
the current thread is alive by invoking the isAlive() method and displays the return
C
value of the method. This will result in true being printed because the main (default) thread
has begun execution and is currently alive. The code also checks if objNamedThread is alive
h
by invoking the same method on it. However, at this point of time, objNamedThread has
not yet begun execution so the output will be false. Next, the start() method is invoked
ec
on objNamedThread which will cause the thread to invoke the run() method which has
been overridden. The run() method prints the total number of threads running, which
pt
are by now, 2. The method then checks the name of the thread running and prints Marimba
if the currently running thread’s name is Thread1. The method performs this checking three
rA
true
Fo
false
true
true
2
Thread1
Marimba
2
Thread1
Marimba
©Aptech Limited
2
Thread1
Marimba
2
Thread1
Marimba
Tips:
Concurrent programming is a process of running several tasks at a time.
In Java, it is possible to execute simultaneously an invoked function and the statements
y
following the function call, without waiting for the invoked function to terminate.
The invoked function runs independently and concurrently with the invoking program, and
nl
can share variables, data, and so on with it.
O
Explain the example demonstrates the creation of a new thread by extending Thread class
and using some of the methods of Thread class mentioned in slides 16 to 19.
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 20
Let us understand Runnable interface.
y
nl
O
se
Using slide 20, explain Runnable interface.
rU
Tell the students that the Runnable interface defines a single method, run(), meant to
contain the code executed in the thread. The Runnable object is passed to the Thread
te
constructor.
en
Mention that the Runnable interface is designed to provide a common set of rules for
objects that wish to execute a code while a thread is active. Another way of creating a new
C
thread is by implementing the Runnable interface. This approach can be used because
Java does not allow multiple class inheritance. Therefore, depending upon the need and
h
requirement, either of the approaches can be used to create Java threads. The easiest way
to create a thread is to create a class that implements the Runnable interface.
ec
It is important to understand that run() method can call other methods, use other classes,
pt
and declare variables, just like the main thread can. After you create a class that implement
the Runnable interface, you will instantiate an object of type Thread from within that
rA
class.
The steps to be followed for creating and running a new Thread by implementing the
Fo
©Aptech Limited
Slide 21
Let us understand how to implement the Runnable interface.
y
nl
O
se
Using slide 21, explain how to implement the Runnable interface.
rU
Tell the students that one needs to declare a class that implements the Runnable
interface.
te
Next, explain the code that shows the implementation of the Runnable interface.
Mention that to implement the Runnable interface, a class needs to only implement a
en
The programmer will need to define the code that constitutes the new thread inside run()
h
method.
ec
In Java, the better way to create a thread is to implement Runnable interface. A thread can
pt
be created by extending Java Thread class also. If the thread class you are creating is to be
subclass of some other class, it cannot extend from the Thread class, because Java does
rA
not allow a class to inherit from more than one class. Hence, one can use Runnable
interface to implement the thread.
Fo
©Aptech Limited
Slide 22
Let us understand how to implement the run() method.
y
nl
O
se
Using slide 22, explain how to implement the run() method.
rU
Use slide 22 to explain how to implement the run() method. Tell the students that the
Runnable interface defines a method, run(), to contain the code that will be executed
te
by the thread object. The class implementing the Runnable interface should override the
run() method.
en
Next, explain the code snippet. Mention to them that the run() method can call other
C
methods, use other classes, and declare variables, just like the main thread.
Tips:
h
The run() method contain the code to implement the logic, that the thread class is
ec
designed to do.
pt
rA
Fo
©Aptech Limited
Slide 23
Let us understand how to start the thread.
y
nl
O
se
Using slide 23, explain how to start the thread.
rU
Tell the student that after creating a class that implements the Runnable interface, one
need to instantiate an object of type Thread from within that class. In the main()
te
method, create an object of the class that implements the Runnable interface. Thread
class defines several constructors.
en
Next, pass this object to the constructor of a Thread class to create an object of Thread
C
class. Finally, invoke the start() method on the thread object to start the thread. This is
declared within the Thread class.
h
Next, explain the code snippet that implements the start() method.
ec
Tips:
pt
You should not invoke the run() method directly. If you did so, it will simply execute in the
caller’s thread instead of as its own thread. So, you need to call the start() method,
rA
which schedules the thread with the JVM. The JVM call the corresponding run() method
when the resources and CPU is ready.
Fo
©Aptech Limited
Slides 24 and 25
Let us understand an example using the Runnable interface.
y
nl
O
se
rU
te
en
C
h
ec
Using slides 24 and 25, explain example using the Runnable interface.
pt
Explain the implementation of the Runnable interface in an application. Tell the students
rA
that in the code, the NamedThread class implements the Runnable interface. Therefore,
an instance of the NamedThread class can be passed as an argument to the constructor of
Fo
Thread class.
©Aptech Limited
In-Class Question:
After you finish explaining creation of thread in Java, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
Which method do you need to override when the class implements the Runnable
interface?
Answer:
y
The run() method
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 26
Let us understand the life cycle of a thread.
y
nl
O
se
rU
Using slide 26, explain the life cycle of a thread.
Tell them that a thread goes through various stages in its life cycle. For example, a thread is
te
born, started, runs, and then dies. The given diagram shows complete life cycle of a thread.
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 27
Let us understand the new state of a thread.
y
nl
O
se
Using slide 27, explain the new state of a thread.
rU
The thread can exists in various state – new, runnable, blocked, waiting, and terminated
according to its various phases in program. When a thread is newly created, it is a new
te
thread and is not alive.
en
In this state, it is an empty thread object with no system resources allocated. So the thread
is left as a ‘new thread’ state till the start() method is invoked on it. When a thread is in
C
this state, you can only start the thread or stop it. Calling any method before starting a
thread raises an IllegalThreadStateException.
h
Tips:
pt
A new thread begins its life cycle in the new state and it remains in it until the program
starts the thread. Sometimes, it is also referred to as a born thread.
rA
Fo
©Aptech Limited
Slide 28
Let us understand the runnable state of a thread.
y
nl
O
se
Using slide 28, explain the runnable state of a thread.
rU
A new thread can be in a runnable state when the start() method is invoked on it. A
thread in this state is alive. A thread can enter this state from running or blocked state.
te
Threads are prioritized because in a single processor system, all runnable threads cannot be
en
executed at a time. In the runnable state, a thread is eligible to run, but may not be running
as it depends on the priority of the thread. The runnable thread, when it becomes eligible
C
Next, explain the code snippet where an instance of a thread is created and is in a runnable
h
state.
ec
Tips:
pt
This state is called runnable because the thread might not be running, but the thread is
allocated to all the resources to run.
rA
Scheduler is a component in Java that assigns priority to the threads so that their execution
is inline with the requirements.
Fo
©Aptech Limited
Slide 29
Let us understand the blocked state of a thread.
y
nl
O
se
Using slide 29, explain the blocked state of a thread.
rU
Blocked state is one of the states in which a thread:
Is alive but currently not eligible to run as it is blocked for some other operation
Is not runnable but can go back to the runnable state after getting the monitor or lock
te
A thread in the blocked state waits to operate on the resource or object which at the same
en
time is being processed by another thread. A running thread goes to blocked state when
sleep(), wait(), or suspend() methods are invoked on it.
C
Tips:
h
Lock or monitor is an imaginary box containing an object. This imaginary box will only allow
a single thread to enter into it, so that it can operate on the object. Any thread which wants
ec
©Aptech Limited
Slide 30
Let us understand the waiting state of a thread.
y
nl
O
se
Using slide 30, explain the waiting state of a thread.
rU
A thread is in waiting state when it is waiting for another thread to release resources for it.
When two or more threads run concurrently and only one thread takes hold of the
te
resources all the time, other threads ultimately wait for this thread to release the resource
for them. In this state, a thread is alive but not running.
en
A call to the wait() method puts a thread in this state. Invoking the notify() or
C
notifyAll() method brings the thread from the waiting state to the runnable state.
A thread transitions to the waiting state, while the thread waits for another thread to
h
perform a task. A thread transitions back to the runnable state only when another thread
ec
©Aptech Limited
Slide 31
Let us understand the terminated state of a thread.
y
nl
O
se
Using slide 31, explain the terminated state of a thread.
rU
A thread, after executing its run() method dies and is said to be in a terminated state. This
is the way a thread can be stopped naturally. Once a thread is terminated, it cannot be
te
brought back to runnable state.
en
Methods such as stop() and destroy() can force a thread to be terminated, but in JDK
1.5, these methods are deprecated.
C
A runnable thread enters the terminated state when it completes its task or the thread gets
h
terminated.
ec
Tips:
If start() method is invoked on a terminated state, it will throw a run-time exception.
pt
In-Class Question:
rA
After you finish explaining Terminated state of a thread, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
Fo
©Aptech Limited
Slide 32
Let us understand the methods of the Thread class.
y
nl
O
se
Using slide 32, explain the methods of the Thread class.
rU
Some important methods of Thread class are as follows:
getName()
te
All threads have a name associated with it. At times, it is required to retrieve the name
en
of a particular thread. The getName() method helps to retrieve the name of the
current thread.
C
start()
h
A newly created thread remains idle until the start() method is invoked. The
start() method allocates the system resources necessary to run the thread and
ec
The life of a thread starts when the run() method is invoked. The characteristics of
rA
o It is public
Fo
o Accepts no argument
©Aptech Limited
sleep()
The sleep() method has the following characteristics:
o It suspends the execution of the current thread for a specified period of time
o It makes the processor time available to the other threads of an application or other
applications that might be running on the computer system
o It stops the execution if the active thread for the time specified in milliseconds or
nanoseconds
y
o It raises InterruptedException when it is interrupted using the
nl
interrupt() method
O
interrupt()
The interrupt() method interrupts the thread. The method tells the thread to stop
se
what it was doing even before it has completed the task. The interrupt() method
has the following characteristics:
rU
o An interrupted thread can die, wait for another task, or go to next step depending on
the requirement of the application.
te
o It does not interrupt or stop a running thread; rather it throws an
InterruptedException if the thread is blocked, so that it exits the blocked
en
state.
C
©Aptech Limited
Slide 33
Let us understand getName() method.
y
nl
O
se
Using slide 33, explain getName() method.
rU
All threads have a name associated with it. At times, it is required to retrieve the name of a
particular thread. The getName() method helps to retrieve the name of the current
te
thread.
en
Next, explain the code snippet that demonstrates the use of the getName() method.
C
Tips:
The setName() method assigns a name to a Thread. The name is passed as an argument
h
to the method.
public final void setName(String name)
ec
where,
name is a String argument passed to the setName() method.
pt
rA
Fo
©Aptech Limited
Slide 34
Let us understand start() method.
y
nl
O
se
Using slide 34, explain start() method.
rU
A newly created thread remains idle until the start() method is invoked. The start()
method allocates the system resources necessary to run the thread and executes the
te
run() method of its target object.
en
Tell them that it starts the thread in a separate path of execution, then invokes the run()
method on this Thread object.
ec
Next, explain the code snippet that demonstrates the use of start() method.
pt
Tips:
rA
Do not start a thread more than once. In particular, a thread may not be restarted once it
has completed execution.
Fo
©Aptech Limited
Slide 35
Let us understand run() method.
y
nl
O
se
Using slide 35, explain run() method.
rU
The run() method contains instructions, which are executed once the start() method
is invoked.
te
Also mention that if this Thread object was instantiated using a separate Runnable
en
Next, explain the code snippet that demonstrates the use of run() method.
h
ec
pt
rA
Fo
©Aptech Limited
Slide 36
Let us understand sleep() method.
y
nl
O
se
Using slide 36, explain sleep() method.
rU
Explain the characteristics of the sleep() method.
te
Syntax:
void sleep(long millis)
en
The Thread.sleep() method effectively pauses the current thread for a given period of
C
time.
Next, explain the code snippet that demonstrates the use of sleep() method. The thread
h
has been put to sleep for 10000 milliseconds. In other words, it causes the currently running
ec
thread to block for at least the specified number of milliseconds. It is a static method that
performs the operation on the currently running thread.
pt
Tips:
rA
On Windows and Linux, the Virtual Machine can generally offers a maximum sleep
granularity of 1 millisecond, and will achieve this accurately on a quiet system.
Fo
©Aptech Limited
Slide 37
Let us understand interrupt() method.
y
nl
O
se
Using slide 37, explain interrupt() method.
rU
The interrupt() method interrupts the thread. The method tells the thread to stop
what it was doing even before it has completed the task.
te
Then, explain the characteristics of the interrupt() method.
en
Syntax:
C
A thread sends an interrupt by sending interrupt() method on the thread object for
h
the thread to be interrupted. For the interrupt mechanism to work correctly, the
ec
Tips:
A thread can interrupt itself. When a thread is not interrupting itself, the checkAccess()
rA
method gets invoked. This method inspects whether the current thread has enough
permission to modify the thread. In case of insufficient permissions, the security manager
throws a SecurityException to indicate a security violation.
Fo
©Aptech Limited
In-Class Question:
After you finish explaining the methods of the Thread class, you will ask the students an
In-Class question. This will help you in reviewing their understanding of the topic.
Answer:
The sleep() method is a static method. It causes the currently running thread to block at
y
least for the specified number of milliseconds. Static method performs the operation on the
nl
currently running thread.
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 38
Let us understand managing threads.
y
nl
O
se
Using slide 38, explain managing threads.
rU
Tell the students that in our day-to-day activities, different degrees of importance need to
be assigned to different tasks. The decision is taken so that the best possible outcome is
achieved. For example, while deciding between the activities going to work and watching
te
television, the activity going to work gets priority over watching television. This is because
going to work is more important for the financial benefit of the person than mere
en
Threads are self-executing entities inside a program. In a single program, several threads
can execute independent of each other. However, at times, it may happen that a particular
h
run-time resource has to be shared by many threads, running simultaneously. This forces
ec
other running threads to enter the blocked state. So, in such situations, some internal
control or management of the threads is required so that the threads are executed
simultaneously.
pt
Next, explain the given figure that displays multiple threads. Take an example of a word
rA
processor; there are several threads running at a time, such as threads for accepting typed
words, auto-saving, and checking the spelling. Hence, it is necessary to manage the system
Fo
resources effectively to run all the tasks without any conflicts. When the application is
closed, all the threads should be terminated simultaneously.
Tips:
Take an example of a word processor; there are several threads running at a time, such as
threads for accepting typed words, auto-saving, and checking the spelling. Hence, it is
necessary to manage the system resources effectively to run all the tasks without any
conflicts. When the application is closed, all the threads should be terminated
simultaneously.
©Aptech Limited
Slide 39
Let us understand the need for thread priority.
y
nl
O
se
Using slide 39, explain the need for thread priority.
rU
Tell the students that every Java thread has a priority that helps the operating system to
determine the order in which threads are scheduled.
te
Next, explain to the students about the need for thread priority. Tell them that while
en
priorities play an important role. Priorities are used to express the importance of different
threads. Priorities play an important part when there is a heavy contention among threads
trying to get a chance to execute. This prioritizing process is managed by the scheduler
h
Thread priority is similar to your daily life where you have to prioritise your schedules or
pt
decisions based on some factors, so that every work is carried out according to their
priority.
rA
Fo
©Aptech Limited
Slide 40
Let us understand the types of thread priority.
y
nl
O
se
Using slide 40, explain the types of thread priority.
rU
Tell the students that thread priority helps the thread scheduler to decide which thread to
run. Priority also helps the operating system to decide the amount of resource that has to
te
be allocated to each thread. Thread priorities are integers ranging from MIN_PRIORITY to
MAX_PRIORITY.
en
The higher the integer value, higher are the priorities. Higher priority thread gets more CPU
C
time than a low priority thread. Thread priorities in Java are constants defined in the
Thread class. They are as follows:
Thread.MAX_PRIORITY
h
ec
Thread.MIN_PRIORITY
rA
Tips:
Fo
©Aptech Limited
In-Class Question:
After you finish explaining types of thread priority, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 41
Let us understand setPriority() method.
y
nl
O
se
Using slide 41, explain setPriority() method.
rU
Tell the students that a newly created thread inherits the priority from the thread that
created it. To change the priority of a thread, the setPriority() method is used. The
te
setPriority() method changes the current priority of any thread. The
setPriority() method accepts an integer value ranging from 1 to 10.
en
Next, explain the syntax of the method. Finally, explain the code snippet where an instance
C
of the Thread class is created and its priority has been set to 8.
h
ec
pt
rA
Fo
©Aptech Limited
Slide 42
Let us understand getPriority() method.
y
nl
O
se
Using slide 42, explain getPriority() method.
rU
Tell the students that the getPriority() method helps to retrieve the current priority
value of any thread. It is a query to know the current priority of the running thread to
te
ensure that the thread is running in the required priority level.
en
In-Class Question:
After you finish explaining thread priority in Java, you will ask the students an In-Class
C
question. This will help you in reviewing their understanding of the topic.
h
ec
Answer:
rA
NORM_PRIORITY or 5
Fo
©Aptech Limited
Slides 43 and 44
Let us understand Daemon threads.
y
nl
O
se
rU
te
en
C
h
ec
pt
A daemon thread runs continuously to perform a service, without having any connection
with the overall state of the program. In general, the threads that run system codes are
good examples of daemon threads.
Fo
Explain the two methods related to daemon threads mentioned in slide 44.
©Aptech Limited
setDaemon(boolean value)
The setDaemon() method turns a user thread to a daemon thread. It takes a boolean
value as its argument. To set a thread as daemon, the setDaemon() method is invoked
with true as its argument. By default, every thread is a user thread unless it is explicitly set
as a daemon thread previously.
isDaemon()
The isDaemon() method determines if a thread is a daemon thread or not. It returns true
if this thread is a daemon thread, else returns false.
y
Daemon threads are service providers for other threads running in the same process as the
daemon thread. The run() method for a daemon thread is typically an infinite loop that
nl
waits for a service request.
O
When the only remaining threads in a process are daemon threads, the interpreter exists.
As when only daemon threads remain, there is no other thread for which a daemon thread
se
can provide a service.
rU
Daemon thread’s life depends on user thread and it is a low priority thread.
Tips:
te
For instance, the garbage collector thread and the thread that processes mouse events for a
Java program are daemon threads. On the other hand, user threads are the default threads
en
©Aptech Limited
Slide 45
Let us understand the need for Daemon threads.
y
nl
O
se
Using slide 45, explain the need for Daemon threads.
rU
The task performed by the Daemon threads are as follows:
Daemon threads are service providers for other threads running in the same process.
te
Daemon threads are designed as low-level background threads that perform some tasks
such as mouse events for Java program.
en
Daemon threads are used for background supporting tasks and are only needed while
C
normal threads are executing. Daemon threads are terminated by the JVM when there are
no longer any user threads running, including main threads of execution.
h
In-Class Question:
ec
After you finish explaining daemon thread in Java, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
pt
rA
Answer:
boolean isDaemon()
©Aptech Limited
Slide 46
Let us summarize the session.
y
nl
O
se
Using slide 46, summarize the session. End the session with a brief summary of what has
been taught in the session. rU
te
7.3 Post Class Activities for Faculty
You should familiarize yourself with the topics of the next session which is on
en
Tips:
C
You can also check the Articles/Blogs/Expert Videos uploaded on the OnlineVarsity site to
gain additional information related to the topics covered in the next session. You can also
h
connect to online tutors on the OnlineVarsity site to ask queries related to the sessions.
ec
pt
rA
Fo
©Aptech Limited
Session 8 – Multithreading and Concurrency
Here, you can ask students the key topics they can recall from previous session. Prepare a question
or two which will be a key point to relate the current session objectives.
y
8.1.1 Objectives
nl
By the end of this session, the learners will be able to:
O
Define multithreading
Differentiate between multithreading and multitasking
se
Explain the use of isAlive() and join() method
Explain race conditions and ways to overcome them
Describe atomic access rU
Describe intrinsic lock and synchronization
synchronization. You should also well verse with deadlock and describes
java.util.concurrent collections.
h
ec
You should teach the concepts in the theory class using the images provided. For teaching in
the class, you are expected to use slides and LCD projectors.
pt
Tips:
rA
It is recommended that you test the understanding of the students by asking questions in
between the class.
Fo
In-Class Activities:
Follow the order given here during In-Class activities.
©Aptech Limited
Overview of the Session:
Give the students the overview of the current session in the form of session objectives.
Show the students slide 2 of the presentation.
y
nl
O
se
rU
Tell the students that this session introduces the concept of multithreading and
synchronization. The session also explains the concept of synchronization and the
mechanism for inter-process communication will also be discussed. The session also
te
describes how to deal with deadlocks which cause two processes to be waiting for a
resource. The session also explains about java.util.concurrent collections.
en
C
h
ec
pt
rA
Fo
©Aptech Limited
8.2 In-Class Explanations
Slide 3
Let us understand the thread-based multitasking.
y
nl
O
se
rU
Using slide 3, explain the thread-based multitasking.
Tell them that a thread performs a certain task and is the smallest unit of executable code in a
program.
te
Multitasking is the ability of the operating system to perform two or more tasks.
en
tasks at the same time. Thus, multithreading can be defined as the concurrent running of the
two or more parts of the same program.
h
ec
pt
rA
Fo
©Aptech Limited
Slide 4
Let us understand types of multitasking.
y
nl
O
se
Using slide 4, explain Types of Multitasking.
rU
Tell them that there are basically two types of multitasking in use among operating systems.
These are as follows:
te
Preemptive
en
In this case, the operating system controls multitasking by assigning the CPU time to each
running program. This approach is used in Windows 95 and 98.
C
Cooperative
h
In this approach, related applications voluntarily surrender their time to one another. This was
ec
parallel.
rA
In-Class Question:
After you finish explaining Types of Multitasking, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
Fo
Answer:
Preemptive
Cooperative
©Aptech Limited
Slide 5
Let us understand features of multithreading.
y
nl
O
se
Using slide 5, explain features of multithreading.
rU
Explain the features of multithreading. They are as follows:
te
Managing many tasks concurrently.
Distinguishing between tasks of varying priority.
en
Allowing the user interface to remain responsive, while allocating time to background tasks.
C
Consider a Web site that has both images and text as its content. When the Web site is loaded
on a user’s computer, both the content must be displayed at the same time. Displaying the
image or text is a separate task but must happen simultaneously. This is where multithreading
h
Also mention to the students that the key to utilizing multithreading support effectively is to
think concurrently rather than serially. For example, when you have two subsystems within a
pt
caution is in order, however, if you create too many threads, you can actually degrade the
performance of your program rather than enhance it.
Fo
Remember, some overhead is associated with context switching. If you create too many
threads, more CPU time will be spent changing contexts than executing your program.
©Aptech Limited
Slide 6
Let us understand differences between multithreading and multitasking.
y
nl
O
se
Using slide 6, explain differences between multithreading and multitasking.
rU
Explain the differences between multithreading and multitasking mentioned in slide 6.
te
One of the differences is that multitasking process takes a separate address space. These
are the different programs run on a single system, while in Multithreading, threads share
en
the same address space and co-operatively share the same heavy-weight process.
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 7
Let us understand need for multithreading.
y
nl
O
se
Using slide 7, explain need for multithreading.
rU
Multithreading is needed for the following reasons:
te
1. Multithreading increases performance of single-processor systems, as it reduces the
CPU idle time.
en
multithreading run as a single thread, causing problems when multiple events or actions
need to occur at the same time.
rA
Tips:
In Multithreading, inter-thread communication is very light-weight and context switching is
Fo
fast.
©Aptech Limited
Slides 8 to 10
Let us understand implementing multithreading.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Tell the students that in the code, the main() method creates two child threads by
instantiating the MultipleThreads class which has been derived from the Thread class. The
names of the child threads are set to Thread2 and Thread3 respectively. When the start()
method is invoked on the child thread objects, the control is transferred to the run() method
which will begin thread execution. Just as the child threads begin to execute, the number of
active threads is printed in the main() method.
Bring to the notice of the students that thread execution stops, once it finishes the execution of
run() method. Once stopped, thread execution cannot restart by using the start()
method. Also, the start() method cannot be invoked on an already running thread. This will
also throw an exception of type IllegalThreadStateException.
y
nl
Threads eat up a lot memory such as RAM, therefore, it is always advisable to set the references
to null when a thread has finished executing. If a Thread object is created but fails to call the
O
start() method, it will not be eligible for garbage collection even if the underlying
application has removed all references to the thread.
se
In-Class Question:
After you finish explaining features of multithreading and multitasking, you will ask the students
rU
an In-class question. This will help you in reviewing their understanding of the topic.
te
Does multithreading requires less overhead than multitasking?
en
Answer:
No.
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 11
Let us understand isAlive() method.
y
nl
O
se
Using slide 11, explain isAlive() method.
rU
Tell them that the thread that is used to start the application should be the last thread to
terminate. This indicates that the application has terminated. This can be ensured by stopping
te
the execution of the main thread for a longer duration within the main thread itself. Also it
should be ensured that all the child threads terminate before the main thread. However, how
en
does one ensure that the main thread is aware of the status of the other threads? There are
ways to find out if a thread has terminated. First, by using the isAlive() method.
C
A thread is considered to be alive when it is running. The Thread class includes a method
named isAlive(). This method is used to find out whether a specific thread is running or
h
not. If the thread is alive, then the boolean value true is returned. If the isAlive()
ec
method returns false, it is understood that the thread is either in new state or in terminated
state.
pt
Next, explain the syntax and the code snippet. Tell them that in the code snippet, the method
returns a boolean value of true or false depending on whether the thread is running or
rA
terminated. The code snippet will return false since the thread is in new state and is not
running.
Fo
©Aptech Limited
Slides 12 to 14
Let us understand join() method.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Using slides 12 to 14, explain join() method.
Next, explain the code snippet showing how to use the join() method. Tell the students that
in the code snippet, the current thread waits until the thread, objTh terminates.
The join() method of the Thread class has two other overloaded versions:
y
number of milliseconds elapses.
nl
void join(long timeout, int nanoseconds)
O
In this type of join() method arguments of type long and integer are passed.
The amount of timeout is given in milliseconds in addition to a specified amount of
nanoseconds.
se
This forces the thread to wait for the completion of the specified thread until the given
timeout elapses.
rU
The join() method is used more commonly than isAlive() method. join() method
tells the thread to waits until the specified thread completes the execution. The overloaded
te
versions of join() method allow is to specify time for which you want to wait for the
specified thread to terminate.
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 15 to 18
Let us understand different methods of thread class for multithreading.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 15 to 18, explain different methods of thread class for multithreading.
se
Tell the students that in the code, three thread objects are created in the main() method.
The isAlive() method is invoked by the three thread objects to test whether they are alive
rU
or dead. Then, the join() method is invoked by each of the thread objects. The join()
method ensures that the main thread is the last one to terminate. Finally, the isAlive()
method is invoked again to check whether the threads are still alive or dead. These statements
te
are enclosed inside a try-catch block.
en
two : 0
three : 0
rA
one : 1
two : 1
three : 1
Fo
one exiting
two exiting
three exiting
First thread is alive : false
Second thread is alive : false
Third thread is alive : false
Main thread is over and exiting
©Aptech Limited
In-Class Question:
After you finish explaining isAlive() and join() methods of the Thread class, you will
ask the students an In-class question. This will help you in reviewing their understanding of the
topic.
y
Answer:
nl
The join() method throws the exception when another thread interrupts it.
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 19
Let us understand race conditions.
y
nl
O
se
Using slide 19, explain Race Conditions.
rU
In multithreaded programs, several threads may simultaneously try to update the same
resource, such as a file. This leaves the resource in an undefined or inconsistent state. This is
te
called race condition.
en
Race condition in Java is a type of concurrency issue which is introduced in your program
ec
because parallel execution of your program by multiple threads at same time. Since, Java is
a multi-threaded programming language hence, risk of Race condition is higher in Java.
pt
Tips:
rA
©Aptech Limited
Slides 20 to 22
Let us understand synchronized blocks.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Tell the students that in multithreaded programs, several threads may simultaneously try to
update the same resource, such as a file. This leaves the resource in an undefined or
inconsistent state. This is called race condition.
The race conditions can be avoided by using synchronized blocks. This is a block of code
qualified by the synchronized keyword.
y
Explain the term by providing an example. Consider a situation where people are standing in
nl
a queue outside a telephone booth. They wish to make a call and are waiting for their turn.
This is similar to a synchronized way of accessing data where each thread wanting to access
O
data waits its turn. However, going back to the analogy described earlier, if there was no
queue and people were permitted to go in randomly, two or more persons would try to
se
enter the booth at the same time, resulting in confusion and chaos. This is similar to a race
condition that can take place with threads. When two threads attempt to access and
rU
manipulate the same object and leave the object in an undefined state, a race condition
occurs.
Java provides the synchronized keyword to help to avoid such situations. The core
te
concept in synchronization with Java threads is something called a monitor. A monitor is a
en
inside, the booth will be locked, thus preventing the others from entering. The telephone
inside the booth here is the real-life equivalent of an object, the booth is the monitor and the
h
lock is the mutex. A Java object has only one monitor and mutex associated with it.
ec
Thus, synchronized blocks are used to prevent the race conditions in Java applications. The
synchronized block contains code qualified by the synchronized keyword. A lock is assigned
pt
accessing it. A lock allows only one thread at a time to access the code. When a thread starts to
execute a synchronized block, it grabs the lock on it. Any other thread will not be able to
execute the code until the first thread has finished and released the lock. The lock is based on
Fo
Then, explain the students the syntax of using the synchronized keyword.
Then, explain the use of synchronized keyword on an object with the help of the code
snippet. Tell the students that in the code snippet, the deposit() method of Account class has
been synchronized by using a synchronized keyword. This method can be accessed by a
single thread at a time from the several threads in a program. The synchronized method
allows threads to access it sequentially.
©Aptech Limited
Slide 23
Let us understand synchronized method.
y
nl
O
se
Using slide 23, explain synchronized method.
rU
Tell the students that making the methods synchronized has two effects:
First, it is not possible for two invocations of synchronized methods on the same object to
te
interleave. When one thread is executing a synchronized method for an object, all other threads
that invoke synchronized methods for the same object block, suspend execution until the first
en
relationship with any subsequent invocation of a synchronized method for the same object. This
guarantees that changes to the state of the object are visible to all threads.
h
ec
pt
rA
Fo
©Aptech Limited
Slides 24 to 27
Let us understand example of Synchronized methods.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 24 to 27, explain example of Synchronized methods.
Explain the example shows how to use a synchronized method mentioned in slides 24 to 27.
se
Tell them that in the code, the class One has a method display() that takes an int parameter.
rU
This number is displayed with a suffix ’done‘. The Thread.sleep(1000) method pauses the
current thread, after the method display() is called.
The constructor of the class Two takes a reference to an object t of the class One and an integer
te
variable. Here, a new thread is also created. This thread calls the method run() of the object
t. The main class, SynchDemo instantiates an object of class, One, objOne and creates three
en
objects of the class Two. The same object objOne is passed to each of the objects of class Two.
The method join() makes the caller thread wait till the calling thread terminates.
C
11 done
ec
12 done
Tips:
pt
©Aptech Limited
Slide 28
Let us understand issues in synchronization.
y
nl
O
se
Using slide 28, explain issues in synchronization.
rU
Tell the students that it is not always possible to achieve synchronization by creating
synchronized methods within classes.
te
Consider a case where the programmer wants to synchronize access to objects of a class, which
en
does not use synchronized methods. Also assume that the source code is unavailable because
either a third party created it or the class was imported from the built-in library. In such a case,
the keyword synchronized cannot be added to the appropriate methods within the class.
C
Therefore, the problem here would be how to make the access to an object of this class
h
synchronized. This could be achieved by putting all calls to the methods defined by this class
ec
In-Class Question:
pt
After you finish explaining management of threads, you will ask the students an In-class
question. This will help you in reviewing their understanding of the topic.
rA
Fo
Answer:
No. Constructors cannot be synchronized — using the synchronized keyword with a
constructor results in a syntax error.
©Aptech Limited
Slide 29
Let us understand intrinsic locks and synchronization.
y
nl
O
se
Using slide 29, explain intrinsic locks and synchronization.
rU
Synchronization is built around the concept of an in-built monitor, which is also referred to
as intrinsic lock or monitor lock. The monitor lock enforces exclusive access to the thread
te
objects and creates a relationship between the thread action and any further access of the
same lock. Every object is connected to an intrinsic lock.
en
Typically, a thread acquires the object’s intrinsic lock before accessing its fields, and then
C
releases the intrinsic lock. In this span of acquiring and releasing the intrinsic lock, the
thread owns the intrinsic lock. No other thread can acquire the same lock. The other thread
will block when it attempts to acquire the lock.
h
ec
All Java objects contains an intrinsic locks, you can use that lock to make methods. When a
thread has a lock, no other thread can acquire it and must wait for the first thread to release
the lock. To acquire a lock, you have to use the synchronized keyword to automatically
Fo
acquire and release a lock for a code. You can add synchronized keyword to a method to
acquire the lock before invoking the method and release it after the method execution.
©Aptech Limited
In-Class Question:
After you finish explaining Intrinsic Locks and Synchronization, you will ask the students an
In-Class question. This will help you in reviewing their understanding of the topic.
Answer:
It is also referred to as intrinsic lock or monitor lock.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 30
Let us understand reentrant synchronization.
y
nl
O
se
Using slide 30, explain reentrant synchronization.
rU
This occurs when a thread acquires a lock that it already owns. In this event, the
synchronized code invokes a method directly or indirectly that also contains synchronized
te
code. Both sets of code use the same lock.
en
With reentrant synchronization, it is easy for synchronized code to avoid a thread cause
itself to block.
C
A thread cannot acquire a lock owned by another thread. But, allowing a thread to acquire
the same lock more than once enables re-entrant synchronization. Reentrant lock provides
h
Tips:
pt
Lock implementations provide more extensive locking operations than can be obtained
rA
using synchronized methods and statements. They allow more flexible structuring, may
have quite different properties, and may support multiple associated Condition objects.
Fo
A lock is a tool for controlling access to a shared resource by multiple threads. Commonly, a
lock provides exclusive access to a shared resource: only one thread at a time can acquire
the lock and all access to the shared resource requires that the lock be acquired first.
However, some locks may allow concurrent access to a shared resource, such as the read
lock of a ReadWriteLock.
The use of synchronized methods or statements provides access to the implicit monitor lock
associated with every object, but forces all lock acquisition and release to occur in a block-
structured way: when multiple locks are acquired they must be released in the opposite
order, and all locks must be released in the same lexical scope in which they were acquired.
©Aptech Limited
While the scoping mechanism for synchronized methods and statements makes it much
easier to program with monitor locks, and helps avoid many common programming errors
involving locks, there are occasions where you need to work with locks in a more flexible
way. For example, some algorithms for traversing concurrently accessed data structures
require the use of ‘hand-over-hand’ or ‘chain locking’: you acquire the lock of node A, then
node B, then release A and acquire C, then release B and acquire D and so on.
Implementations of the Lock interface enable the use of such techniques by allowing a lock
to be acquired and released in different scopes, and allowing multiple locks to be acquired
and released in any order.
y
With this increased flexibility comes additional responsibility. The absence of block-
nl
structured locking removes the automatic release of locks that occurs with synchronized
O
methods and statements. In most cases, the following idiom should be used:
Lock l = ...;
se
l.lock();
try {
// access the resource protected by this lock
} finally {
}
l.unlock();
rU
te
When locking and unlocking occur in different scopes, care must be taken to ensure that all
en
code that is executed while the lock is held is protected by try-finally or try-catch to ensure
that the lock is released when necessary.
C
©Aptech Limited
Slide 31
Let us understand atomic access.
y
nl
O
se
Using slide 31, explain atomic access.
In programming, an atomic action occurs all at once. This means an atomic action cannot
rU
stop in the middle: it either happens completely, or it doesn't happen at all. No side effects
of an atomic action are visible until the action is complete.
te
Following are the features of an atomic action:
It occurs completely or it doesn't occur at all.
en
Effects of an atomic action are visible only after the action is complete.
C
Reads and writes are atomic for all variables declared volatile.
ec
Atomic actions cannot be interleaved which mean that there will no thread interference
pt
when atomic actions are used. Using simple atomic variable access is more efficient than
accessing these variables through synchronized code, but requires more care by the
rA
Tips:
Fo
Using volatile variables reduces the risk of memory consistency errors, because any
write to a volatile variable establishes a happens-before relationship with subsequent
reads of that same variable. This means that changes to a volatile variable are always visible
to other threads. What's more, it also means that when a thread reads a volatile variable, it
sees not just the latest change to the volatile, but also the side effects of the code that led
up the change.
©Aptech Limited
Slide 32
Let us understand wait-notify mechanism.
y
nl
O
se
Using slide 32, explain wait-notify mechanism.
rU
The wait-notify mechanism acts as the traffic signal system in the program. It allows the
specific thread to wait for some time for other running thread and wakes it up when it is
te
required to do so. For these operations, it uses the wait(), notify(), and
notifyAll() methods.
en
In other words, the wait-notify mechanism is a process used to manipulate the wait() and
C
• Allowed to wait for the lock of a synchronized block of resource currently used by
another thread.
pt
• Notified to end its waiting state and get the lock of that synchronized block of resource.
rA
The idea behind wait/notify mechanism is that a thread forces itself to wait for some kind of
condition, a prerequisite for continued execution, to exist before it continues. The waiting
thread will assume that some other thread will create that condition and then notify the
Fo
©Aptech Limited
Slides 33 and 34
Let us understand wait() method.
y
nl
O
se
rU
te
en
C
h
ec
pt
The wait() method causes a thread to wait for some other thread to release a resource. It
forces the currently running thread to release the lock or monitor, which it is holding on an
object. Once the resource is released, another thread can get the lock and start running. The
Fo
wait() method can only be invoked only from within the synchronized code.
The following points should be remembered while using the wait() method:
©Aptech Limited
You can call the wait() method of any Java object, which suspends the current thread.
The thread is said to be ‘waiting on’ the given object.
In-Class Question:
After you finish explaining wait() method, you will ask the students an In-Class question.
This will help you in reviewing their understanding of the topic.
y
Answer:
nl
When the resource is released, another thread can get the lock and start running.
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 35 and 36
Let us understand notify() method.
y
nl
O
se
rU
te
en
C
h
ec
pt
The notify() method alerts the thread that is waiting for a monitor of an object. This
method can be invoked only within a synchronized block.
Fo
If several threads are waiting for a specific object, one of them is selected to get the object.
The scheduler decides this based on the need of the program.
©Aptech Limited
In-Class Question:
After you finish explaining notify() method, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
What will happen when notify() method is invoked but there are multiple threads
waiting to be notified for an object?
Answer:
If there are multiple threads waiting for an object, this method will wake up only one of them.
y
The choice of the thread to wake up depends on the OS implementation of thread management.
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 37 and 38
Let us understand deadlocks.
y
nl
O
se
rU
te
en
C
h
ec
pt
Deadlock describes a situation where two or more threads are blocked forever, waiting for
the others to release a resource. At times, it happens that two threads are locked to their
respective resources, waiting for the corresponding locks to interchange the resources
Fo
between them.
In that situation, the waiting state continues forever as both are in a state of confusion as to
which one will leave the lock and one will get into it. This is the deadlock situation in a
thread based Java program. The deadlock situation brings the execution of the program to a
halt.
• Thread A
Thread A has Resource X Lock and is waiting for Resource Y which is with Thread B for its
completion.
©Aptech Limited
• Thread B
Thread B has Resource Y Lock and is waiting for Resource Z which is with Thread C for its
completion.
• Thread C
Thread C has Resource Z Lock and is waiting for Resource X which is with Thread A for its
completion.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 39 to 42
Let us understand example of deadlock condition.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 39 to 42, explain example of deadlock condition.
se
Explain the example demonstrates a deadlock condition mentioned in slides 39 to 42. Tell
the students that the program creates two child threads. Each thread calls the synchronized
rU
run() method. When thread objTh1 wakes up, it calls the method syncIt() of the
DeadlockDemo object objDead1. Since, the thread objTh2 owns the monitor of objDead2,
thread objTh1 begins waiting for the monitor. When thread objTh2 wakes up, it tries to call
te
the method syncIt() of the DeadlockDemo object, objDead2. At this point, objTh2 also is
forced to wait since objTh1 owns the monitor of objDead1. Since, both threads are waiting
en
for each other, neither will wake up. This is a deadlock condition. The program is blocked
and does not proceed further.
C
©Aptech Limited
Slide 43
Let us understand overcoming the deadlock.
y
nl
O
se
Using slide 43, explain overcoming the Deadlock.
rU
Tell the students that one can plan for the prevention of deadlock while writing the codes. The
following things in a program can be done to avoid deadlock situations in it:
te
1 Avoid acquiring more than one lock at a time.
2 Ensure that in a Java program, you acquire multiple locks in a consistent and
en
defined order.
C
Tips:
If a thread holds a lock and goes in sleeping state, it does not lose the lock. However, when a
thread goes in the blocked state, it releases the lock. This eliminates potential deadlock
h
situations.
ec
Java does not provide any mechanism for detection or control of potential deadlock situations.
The programmer is responsible for avoiding them.
pt
rA
Fo
©Aptech Limited
Slide 44
Let us understand java.util.concurrent collections.
y
nl
O
se
Using slide 44, explain java.util.concurrent collections.
rU
Following are some of these collections that are categorized by the collection interfaces:
te
BlockingQueue: This defines a First In First Out (FIFO) data structure that blocks or times
out when data is added to a full queue or retrieved from an empty queue.
en
All of these collections help avoid memory consistency errors by defining a happens-before
ec
relationship between an operation that adds an object to the collection with subsequent
operations that access or remove that object.
pt
includes a few small standardized extensible frameworks, as well as some classes that
provide some useful functionality.
Fo
©Aptech Limited
Slides 45 and 46
Let us understand atomic variables.
y
nl
O
se
rU
te
en
C
h
ec
pt
©Aptech Limited
The following additional code snippet shows the use of synchronization to safe the thread
from thread interference.
y
nl
O
se
rU
Now, replacing the int field with an AtomicInteger allows us to prevent thread
te
interference without resorting to synchronization.
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 47
Let us understand Executors and Executor interface.
y
nl
O
se
Using slide 47, explain Executors and Executor interface.
rU
Objects that separate thread management and creates them from the rest of the
application are called executors.
te
The java.util.concurrent package defines the following three executor interfaces:
en
Executor Interface
rA
The Executor interface provides a single method, execute, and designed to be a drop-in
replacement for a common thread-creation idiom. If r is a Runnable object, and e is
an Executor object, then you can replace, the following code snippet:
Fo
Depending on the Executor implementation, execute may do the same thing, but is more
likely to use an existing worker thread to run r, or to place r in a queue to wait for a worker
thread to become available.
©Aptech Limited
ExecutorService and ScheduledExecutorService interfaces, although they
also work with the base Executor interface.
ExecutorService Interface
y
nl
ExecutorService also provides methods for submitting large collections
O
of Callable objects. Finally, ExecutorService provides a number of methods for
managing the shutdown of the executor. To support immediate shutdown, tasks should
handle interrupts correctly.
se
ScheduledExecutorService Interface
rU
The ScheduledExecutorService interface supplements the methods of its
parent ExecutorService with schedule, which executes
te
a Runnable or Callable task after a specified delay. In addition, the interface
defines scheduleAtFixedRate and scheduleWithFixedDelay, which executes
en
©Aptech Limited
Slide 48
Let us understand ThreadPools.
y
nl
O
se
Using slide 48, explain ThreadPools.
rU
Thread pools have worker threads that help create threads and thus minimize the overhead.
Certain executor implementations in java.util.concurrent use thread pools.
te
Thread pools are often used to execute multiple tasks. Allocating and deallocating multiple
en
Fixed thread pool is a common type of thread pool that includes the following features:
There are a specified number of threads running.
h
Applications using fixed thread pool services HTTP requests as quickly as the system
sustains.
pt
Threadpools are useful when you have to limit the number of threads running in your
rA
application at the same time. There is a performance overhead associated with starting a
new thread, and each thread is also allocated some memory for its stack.
Fo
One common type of thread pool is the fixed thread pool. This type of pool always has a
specified number of threads running; if a thread is somehow terminated while it is still in
use, it is automatically replaced with a new thread. Tasks are submitted to the pool via an
internal queue, which holds extra tasks whenever there are more active tasks than threads.
An important advantage of the fixed thread pool is that applications using it degrade
gracefully. To understand this, consider a Web server application where each HTTP request
is handled by a separate thread. If the application simply creates a new thread for every
©Aptech Limited
new HTTP request, and the system receives more requests than it can handle immediately,
the application will suddenly stop responding to all requests when the overhead of all those
threads exceed the capacity of the system. With a limit on the number of the threads that
can be created, the application will not be servicing HTTP requests as quickly as they come
in, but it will be servicing them as quickly as the system can sustain.
A simple way to create an executor that uses a fixed thread pool is to invoke
the newFixedThreadPool factory method in
java.util.concurrent.Executors.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 49 to 53
Let us understand For/Join framework.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
rU
te
en
C
h
ec
that run out of things to do can steal tasks from other threads that are still busy.
The Fork/Join framework allocates tasks to worker threads in a thread pool. There is the
Fo
Explain the Code Snippet displays the use of Fork/Join functionality mentioned in slides 50
to 53.
©Aptech Limited
In-Class Question:
After you finish explaining For/Join Framework, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 54
Let us summarize the session.
y
nl
O
se
Using slide 54 you will summarize the session. You will end the session with a brief summary
of what has been taught in the session. rU
te
8.3 Post Class Activities for Faculty
You should familiarize yourself with the topics of the next session which is JDBC API.
en
Tips:
C
You can also check the Articles/Blogs/Expert Videos uploaded on the Online Varsity site to
gain additional information related to the topics covered in the next session. You can also
connect to online tutors on the Online Varsity site to ask queries related to the sessions.
h
ec
pt
rA
Fo
©Aptech Limited
Session 9 – JDBC API
Here, you can ask students the key topics they can recall from previous session. Prepare a
question or two which will be a key point to relate the current session objectives.
y
nl
9.1.1 Objectives
By the end of this session, the learners will be able to:
O
Explain basics of JDBC
Explain JDBC architecture
se
Explain different types of processing models
Explain JDBC Driver Types
Explain Database Meta Information rU
Understand the steps involved in JDBC application development
To teach this session, you should be well-versed with the concept of Java Database
Connectivity (JDBC) API and its architecture. You should also be well-versed yourself with
C
the implementation of JDBC API to connect and retrieve data from SQL server database.
You should teach the concepts in the theory class using the images provided. For teaching in
h
the class, you are expected to use slides and LCD projectors.
ec
Tips:
pt
It is recommended that you test the understanding of the students by asking questions in
between the class.
rA
In-Class Activities:
Follow the order given here during In-Class activities.
Fo
©Aptech Limited
Overview of the Session:
Then give the students the overview of the current session in the form of session objectives.
Show the students slide 2 of the presentation.
y
nl
O
se
rU
Tell the students that this session introduces the concept of JDBC and its architecture and its
drivers to develop database application. The session also explains them how to connect and
retrieve data from SQL server database.
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
9.2 In-Class Explanations
Slide 3
Let us understand about communication with the databases.
y
nl
O
se
rU
Using slide 3, explain about communication with the databases. Java has established itself as
one of the prime backbones of enterprise computing.
te
en
The core of Java enterprise applications depends on storing and retrieving the data from
different types of streams. One of the major streams used for data storage is Database
Management Systems (DBMS) software. It acts as the repository for an enterprise’s data.
C
Hence, to build large enterprise applications, the data stored in the databases need to be
accessed.
h
To connect the Java applications with the databases, the Application Programming
ec
Interfaces (APIs) software for database connectivity, known as JDBC, is used. This software
API is a collection of application libraries and database drivers, whose implementation is
pt
Open Database Connectivity (ODBC) and JDBC are two widely used APIs for connecting and
retrieving data from the databases.
Fo
©Aptech Limited
Slide 4
Let us understand ODBC.
y
nl
O
se
Using slide 4, explain about ODBC.
rU
ODBC is an API provided by Microsoft for accessing the database. It uses Structured Query
Language (SQL) as its database language. It provides functions to insert, modify, and delete
te
data and obtain information from the database.
en
The application can be a GUI program written in Java, VC++, or any other software. The
application makes use of ODBC to connect with the databases. The driver manager is part of
C
Microsoft ODBC API and is used to manage various drivers in the system including loading.
h
operating systems.
pt
In-Class Question:
rA
After you finish explaining ODBC, you will ask the students an In-Class question. This will
help you in reviewing their understanding of the topic.
Fo
©Aptech Limited
Slide 5
Let us understand ODBC connection.
y
nl
O
se
Using slide 5, explain about ODBC connection.
rU
Explain the figure that displays the ODBC connection mentioned in slide 5.
te
ODBC accomplishes DBMS independence by using an ODBC driver as a translation layer
between the application and the DBMS. The application uses ODBC functions through an
en
ODBC driver manager with which it is linked and the driver passes the query to the DBMS.
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 6 and 7
Let us understand the JDBC API.
y
nl
O
se
rU
te
en
C
h
ec
pt
JDBC API is a Java API provided by Sun. The JDBC API has a set of classes and interfaces used
for accessing data from a relational database. These classes and interfaces are written in
Fo
Java programming language and provide a standard API for database developers to access
the database.
The advantage of using JDBC API is that an application can access any database and run on
any platform having JVM. The combination of JDBC API and Java platform offers the
advantage of accessing any type of data source and flexibility of running on any platform
which supports Java Virtual Machine (JVM).
©Aptech Limited
A single program with the JDBC implementation can send Structured Query Language (SQL)
or other statements to the suitable data source or database.
The tasks that can be performed by using JDBC drivers are as follows:
Establish a connection with the data source
Creating and sending queries and update statements to the data source
Process the results
Tips:
JDBC is compatible with many platforms like UNIX and Mac OS. JDBC acts as a standard API
y
for accessing database-independent connectivity between the Java application and the
database.
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 8
Let us understand the need for JDBC.
y
nl
O
se
Using slide 8, explain the need for JDBC.
rU
ODBC cannot provide direct use from the Java programming language because it uses a C
interface. The JDBC API was modeled after ODBC, but, because JDBC is a Java API, it offers a
te
Java interface for working with SQL databases. JDBC is needed to provide a ’pure Java’
solution for application development.
en
The JDBC code is installable, portable, and secure on all Java platforms from network
C
The first release of Java Developer Kit (JDK) was not providing database integration. The
ec
functionality of Java made it easy to build tools for accessing databases, but there was no
prescription about how such drivers should function. Several vendors produced good tools
pt
for database access, but no tool provided common guidelines on how database access tools
should be written.
rA
Thus, the SUN Microsystems created the JDBC API. The advent of JDBC means an end to
those shortcomings mentioned. JDBC provides a vendor-neutral, universal framework for
Fo
vendors to use in building tools that allow clients to access databases. The JDBC
specification itself is just a collection of interfaces and abstract classes that each vendor
must implement to write a JDBC-compliant driver. JDBC promises to database-enable any
Java applet or application.
It is included in the java.sql package, which will be part of the JDK version 1.1.
©Aptech Limited
Slide 9
Let us understand product components of JDBC.
y
nl
O
se
Using slide 9, explain product components of JDBC.
JDBC API
rU
te
JDBC API is a part of Java platform. JDBC APIs are included in two packages which are
included in Java Standard Edition and Java Enterprise Edition. The two packages are
en
java.sql and javax.sql. JDBC API allows access to the relational database from the
Java programming language. Thus, JDBC API allows applications to execute SQL statements,
C
class. The DriverManager class is the backbone of the of JDBC architecture. The task
performed by the DriverManager class are first to locate the driver for a specific
database and then process the initialization calls for JDBC.
pt
JDBC driver test suite helps to determine that JDBC drivers will run the program.
JDBC-ODBC Bridge
Fo
©Aptech Limited
Slide 10
Let us understand JDBC architecture.
y
nl
O
se
Using slide 10, explain JDBC architecture.
rU
Explain the figure that shows the location of the driver manager with respect to JDBC drivers
and applications mentioned in slide 10.
te
JDBC architecture is an API specifying interfaces for accessing relational databases. The JDBC
en
helps to connect to a database, send queries and updates to the database, and retrieve and
process the results obtained from the database for queries.
C
The JDBC API supports two-tier and three-tier processing models for database access.
h
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to different databases.
rA
The JDBC driver manager ensures that the correct driver is used to access each data source.
The driver manager is capable of supporting multiple concurrent drivers connected to
Fo
©Aptech Limited
Slide 11
Let us understand advantages of JDBC.
y
nl
O
se
Using slide 11, explain advantages of JDBC.
Vendor independent
C
The combination of the Java API and the JDBC API makes the databases transferable from
one vendor to another without modifications in the application code.
h
ec
Platform independent
JDBC is usually used to connect a user application to a ’behind the scenes’ database, no
pt
matter of what database management software is used to control the database. In this
fashion, JDBC is cross-platform or platform independent.
rA
Ease of use
With JDBC, the complexity of connecting a user program to a ’behind the scenes’ database is
Fo
©Aptech Limited
In-Class Question:
After you finish explaining advantages of JDBC, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
Does transferring from one database source to another affects the JDBC
applications?
Answer:
y
No, as JDBC is a standard interface and not specific to a particular database, so transferring
nl
from one database source to another does not affects the application code.
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 12
Let us understand two-tier data processing model.
y
nl
O
se
Using slide 12, explain two-tier data processing model.
rU
Explain the figure displaying the two-tier data processing model mentioned in slide 12.
te
In a two-tier client/server system, the client communicates directly to the database server
without the help of any middle-ware technologies or another server. In a two-tier JDBC
en
environment, the Java application is the client and DBMS is the database server.
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 13
Let us understand three-tier data processing model.
y
nl
O
se
rU
Using slide 13, explain three-tier data processing model.
Explain the figure displaying the three-tier data processing model mentioned in slide 13.
te
In a three-tier model, a ‘middle tier’ of services, a third server is employed to send the client
en
request to the database server. This middle tier helps in separating the database server
from the Web server. The involvement of this third server or proxy server enhances the
C
security by passing all the requests to the database server through the proxy server. The
database server processes the requests and sends back the results to the middle tier (proxy
server), which again sends it to the client.
h
ec
Tips:
JDBC API is used more and more in the middle tier of a three-tier application.
pt
rA
Fo
©Aptech Limited
Slide 14
Let us understand JDBC API.
y
nl
O
se
Using slide 14, explain JDBC API.
rU
JDBC API is a collection of specifications that defines the way how database and the
applications communicate with each other. The core of JDBC API is based on Java, so it is
te
used as the common platform for building the middle tier of three-tier architecture.
en
The JDBC API provides a call-level API for SQL-based database access. JDBC API is a Java API
and can access any kind of tabular data, especially data stored in relational database.
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 15
Let us understand JDBC Driver types.
y
nl
O
se
Using slide 15, explain JDBC Driver types.
rU
Explain the JDBC Driver types, their driver name, and description mentioned in slide 15.
te
JDBC drivers are installed on client machine that converts request from Java programs to a
protocol that the DBMS can understand.
en
C
Tips:
To learn more on the drivers and there types, visit the link:
http://docs.oracle.com/cd/E11882_01/java.112/e16548/overvw.htm
h
#JJDBC28033
ec
pt
rA
Fo
©Aptech Limited
Slides 16 to 18
Let us understand JDBC Type 1 Driver.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Explain the figure that displays the JDBC type 1 driver mentioned in slide 16.
The Type 1 drivers use a bridging technology that provides JDBC access via ODBC drivers.
JDBC Type 1 driver is also known as JDBC-ODBC Bridge. It is database driver implementation
that employs the ODBC driver to connect to the database. The driver converts JDBC method
calls into ODBC function calls.
The Type 1 drivers are written to allow access to various databases through pre-existing
ODBC drivers. For example, databases such as Microsoft Access or Microsoft SQL Server
y
having ODBC native call interface.
nl
The Type 1 driver does not hold good for applications that do not support software
O
installations on client machines. The native ODBC libraries and the database client codes
must reside on the server, which in turn reduces the performance.
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 19 to 21
Let us understand JDBC Type 2 Driver.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Explain the figure that displays the JDBC type 2 driver mentioned in slide 19.
The Type 2 driver comprises the Java code that converts JDBC calls into calls on a local
database API for Oracle, Sybase, DB2, or any other type of DBMS. This implies that the
driver calls the native methods of the individual database vendors to get the database
access. This kind of driver basically comes with the database vendors to interpret JDBC calls
to the database-specific native call interface, for example, Oracle provides OCI driver. The
Type 2 driver also needs native database-specific client libraries to be installed and
configured on the client machine like Type 1 drivers.
y
The Type 2 drivers are generally faster than Type 1 drivers as the calls get converted to
nl
database-specific calls. However, does not support applications that do not allow software
O
installations on client machines as it requires native database codes to be configured on
client machines.
se
In-Class Question:
rU
After you finish explaining JDBC Type 2 Driver, you will ask the students an In-Class question.
This will help you in reviewing their understanding of the topic.
te
Why type 2 drivers are generally faster than type 1 drivers?
en
Answer:
It is fast as the calls get converted to database-specific calls.
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 22 to 24
Let us understand JDBC Type 3 Driver.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Explain the figure that displays the JDBC type 3 driver mentioned in slide 22.
It is a database driver implementation which makes use of a middle tier between the calling
program and the database. The middle tier converts JDBC calls directly or indirectly into
database protocol. Type 3 is written entirely in Java.
The Type 3 driver is a pure Java driver that converts the JDBC calls into a DBMS-independent
network protocol, which is again translated to database-specific calls by a middle tier server.
This driver does not require any database-specific native libraries to be installed on the
client machines. The Web-based applications should preferably implement Type 3 drivers as
this driver can be deployed over the Internet without installing a client.
y
The Type 3 driver is the most flexible type as it does not require any software or native
nl
services to be installed on client machine. It provides a high degree of adaptability to change
O
and control underlying database without modifying the client side driver.
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 25 to 27
Let us understand JDBC Type 4 Driver.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Explain the figure that displays the JDBC type 4 driver.
JDBC type 4 driver are known as Direct to database Pure Java Driver. It is a database driver
implementation that converts JDBC calls into database protocol. They are platform
independent. They give better performance than type 1 and type 2 drivers as it does not
have the overhead of conversion of calls into ODBC or database API calls.
The Type 4 drivers communicate directly with the database engine using Java sockets, rather
than through middleware or a native library. This is the reason that these drivers are the
fastest JDBC drivers available. No additional software like native library is needed for
installation on clients. However, the Type 4 drivers are database-specific.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 28 to 30
Let us understand java.sql package.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
JDBC API defines a set of interfaces and classes to communicate with the database.
Connection: This is used to maintain and monitor database sessions. Data access can
also be controlled using the transaction locking mechanism.
DatabaseMetaData: This interface provides database information such as the version
number, names of the tables, and functions supported. It also has methods that help in
discovering database information such as the current connection, tables available,
schemas, and catalogues.
y
Driver: This interface is used to create Connection objects.
nl
PreparedStatement: This is used to execute pre-compiled SQL statements.
ResultSet: This interface provides methods for retrieving data returned by a SQL
O
statement.
ResultSetMetaData: This interface is used to collect the metadata information
associated with the last ResultSet object.
se
Statement: It is used to execute SQL statements and retrieve data into the ResultSet.
rU
Explain the table that describes some of the classes in this package mentioned in slide 29.
Explain the exceptions defined by the package are listed in the table mentioned in slide 30.
te
Tips:
en
The current version of JDBC API is JDBC 4.1 API which incorporates all of the previous JDBC
API versions:
C
Following table shows the JDBC API versions incorporated in the different Java versions:
Fo
©Aptech Limited
Slide 31
Let us understand the steps to develop a JDBC application.
y
nl
O
se
Using slide 31, explain the steps to develop a JDBC application.
rU
Explain the figure that displays the steps to develop a JDBC application mentioned in slide
31.
te
en
database Uniform Resource Locator (URL) identifies a JDBC connection and tells the
driver manager which driver and data source to use.
pt
submitted to the database for processing. SQL statement is the universally accepted
query language to perform retrieval, insertion, updation, or deletion operations on a
database.
Fo
©Aptech Limited
Slide 32
Let us understand about loading a driver.
y
nl
O
se
Using slide 32, explain about loading a Driver.
rU
Load the driver class by using the Class.forName() method. Invoking the
Class.forName() method creates an instance of the specified driver class and registers
te
it with the DriverManager class.
en
Once the driver is loaded successfully, the connection with a database can be established.
C
©Aptech Limited
Slide 33
Let us understand about establishing a connection.
y
nl
O
se
Using slide 33, explain about establishing a connection.
rU
The connection is established by using the DriverManager.getConnection()
method.
te
The method checks for the following:
en
You establish a connection with the data source you want to use. The data source can be a
DBMS, a legacy file system, or some other source of data with a corresponding JDBC driver.
h
Normally, a JDBC application connects to a target data source using any of two classes. They
ec
©Aptech Limited
Slides 34 and 35
Let us understand about creating statements and queries.
y
nl
O
se
rU
te
en
C
h
ec
pt
Using slides 34 and 35, explain about creating statements and queries.
rA
Statement
A Statement object needs to be created for query execution. The Statement object is
created by using the Connection.createStatement() method.
Fo
For example, you can create a Statement object with the following code:
stmt = con.createStatement();
©Aptech Limited
There are three different kinds of statements:
PreparedStatement
y
nl
A PreparedStatement is a special kind of Statement object with some useful
features. Remember, you need a Statement in order to execute either a query or
O
an update. You can use a PreparedStatement instead of a Statement and benefit
from the features of the PreparedStatement.
se
The PreparedStatement primary features are as follows:
rU
Easy to insert parameters into the SQL statement.
Easy to reuse the PreparedStatement with new parameters.
May increase performance of executed statements.
te
Enables easier batch updates.
en
Creating a PreparedStatement
C
Before you can use a PreparedStatement, you must first create it. You do so using the
Connection.prepareStatement().
h
ec
Following code snippet shows the code to create the PreparedStatement object:
pt
PreparedStatement preparedStatement =
connection.prepareStatement(sql);
Fo
©Aptech Limited
Inserting Parameters into a PreparedStatement
Everywhere, you need to insert a parameter into your SQL, you write a question mark (?).
For instance:
y
many setXXX() methods.
nl
Following code snippet shows how to insert parameters in the query:
O
preparedStatement.setLong(1, 123);
se
The first number (1) is the index of the parameter to insert the value for. The second
rU
number (123) is the value to insert into the SQL statement.
te
Explain the syntax and code snippet mentioned in slide 35.
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 36 and 37
Let us understand about using executeQuery() and ResultSet objects.
y
nl
O
se
rU
te
en
C
h
ec
pt
Using slides 36 and 37, explain about using executeQuery() and ResultSet objects.
rA
ResultSet object.
executeQuery(): This method executes any SQL statement with a SELECT clause, that
return the result of the query as a result set.
ResultSet object: ResultSet objects receive and store the data in the same form as it is
returned from the SQL queries. The ResultSet object is generally created by using the
executeQuery() method.
©Aptech Limited
Explain the syntax and code snippet mentioned in slide 37.
The data can be access in a ResultSet object through a cursor but, this cursor is not a
database cursor. The cursor is a pointer that points to one row of data in the ResultSet
object. You can invoke methods defined in the ResultSet object to move the cursor.
Tips:
For more information on working with the ResultSet object, you can visit the link:
http://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.
html
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 38
Let us understand about using executeUpdate() and execute() methods.
y
nl
O
se
Using slide 38, explain about using executeUpdate() and execute() methods.
rU
The executeUpdate() method executes INSERT, DELETE, UPDATE, and other SQL
Data Definition Language (DDL) such as CREATE TABLE, DROP TABLE, and so on. The
te
method returns an integer value indicating the row count.
en
The execute() method executes SQL statements that returns more than one result set.
The method returns true if a result set object is generated by the SQL statements.
C
the SQL statements. The execute() method returns true if the object that the query
returns is a ResultSet object. Use this method if the query returns one or more ResultSet
ec
objects.
pt
In-Class Question:
rA
After you finish explaining use of executeUpdate() and execute() methods, you
will ask the students an In-Class question. This will help you in reviewing their understanding
of the topic.
Fo
©Aptech Limited
Slide 39
Let us understand about creating parameterized queries.
y
nl
O
se
Using slide 39, explain about creating parameterized queries.
rU
Explain the figure that shows the steps to create parameterized queries mentioned in slide
39.
te
Explain the Code Snippet that demonstrates the steps to create parameterized query
en
©Aptech Limited
Slides 40 and 41
Let us understand about handling exceptions in JDBC applications.
y
nl
O
se
rU
te
en
C
h
ec
pt
Using slides 40 and 41, explain about handling exceptions in JDBC applications.
rA
Commonly occurring exceptions during database handling with JDBC include the following:
ClassNotFoundException
SQLException
Fo
ClassNotFoundException
While loading a driver using Class.forName(), if the class for the specified driver is
not present in the package, then the method invocation throws a
ClassNotFoundException.
The method should be wrapped inside a try block, followed by a catch block, which deals
with the thrown exception (if any).
Explain the Code Snippet that shows use of the ClassNotFoundException mentioned
in slide 40.
©Aptech Limited
SQLException
Explain the Code Snippet that shows the use of SQLException mentioned in slide 41.
When JDBC encounters an error during an interaction with the data source, it throws an
instance of SQLException as opposed to Exception.
y
Tips:
nl
The instance of SQLException contains the information regarding error such as
O
description of error, SQLState code, an error code, a cause, and a reference to any chained
exceptions.
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 42 and 43
Let us understand the need for processing queries.
y
nl
O
se
rU
te
en
C
h
ec
pt
Using slides 42 and 43, explain the need for processing queries.
rA
Once the database query is executed and ResultSet object is created, the next step is to
process and retrieve the result from the ResultSet. As the data in the ResultSet is in
a tabular format and the cursor is positioned before the first row, it needs to traverse the
Fo
rows using the next() method. The next() method allows to traverse forward by
moving the cursor one row forward.
It returns a boolean true if the current cursor position is on a valid row and returns a false
when the cursor is placed at a position after the last row.
Explain the Code Snippet that demonstrates use of the next() method mentioned in slide
43.
©Aptech Limited
In-Class Question:
After you finish explaining about the need for processing queries, you will ask the students
an In-Class question. This will help you in reviewing their understanding of the topic.
Answer:
It allows to traverse forward by moving the cursor one row forward.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 44
Let us understand the methods of ResultSet object.
y
nl
O
se
Using slide 44, explain the methods of ResultSet object.
getString()
rU
Is used for retrieving a string value (SQL type VARCHAR) and assigning into Java
te
String object.
en
getInt()
Is used for retrieving an integer value from the current row and assigning into a Java
C
integer variable.
h
getFloat()
Is used for retrieving a float value from a current row and assigning into a Java float
ec
variable.
pt
getObject()
Is used for retrieving the value from a current row as an object and assigning to
rA
©Aptech Limited
Slide 45
Let us understand about closing the database connection.
y
nl
O
se
Using slide 45, explain about closing the database connection.
rU
Use the close() method to close the database connection. To keep the database-
releasing methods tidy and always released (even though an exception may be thrown),
te
database connections should be closed within a finally block.
en
At the end of JDBC program, it is required to explicitly close all the connections to the
database to end each database session. Explicitly closing the connections conserves DBMS
resources.
h
ec
Tips:
If fails to explicitly close the connections, then the Java garbage collector will close the
pt
©Aptech Limited
Slide 46
Let us understand database meta information.
y
nl
O
se
Using slide 46, explain database meta information.
rU
The dictionary meaning of metadata is data about data. In the context of databases, it can
also be defined as information that defines the structure and properties of the data stored
te
in a database.
en
JDBC support the access of metadata by providing several methods. For example, a table in
a database has its defined name, column names, datatypes for its columns, and the owner
C
©Aptech Limited
Slide 47
Let us understand DatabaseMetaData interface.
y
nl
O
se
Using slide 47, explain DatabaseMetaData interface.
rU
The information that describes about the database itself is known as the database
metadata. This metadata information is stored by the objects of DatabaseMetaData
te
interface in the java.sql package.
en
This newly created object is assigned with the results fetched by the getMetaData()
method, called by the Connection object.
h
©Aptech Limited
Slides 48 to 50
Let us understand DatabaseMetaData methods.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 51
Let us understand ResultSetMetaData interface.
y
nl
O
se
Using slide 51, explain ResultSetMetaData Interface.
rU
The information that describes about the data contained in a ResultSet is known as the
ResultSet metadata. This metadata information is stored by the objects of
te
ResultSetMetaData interface in the java.sql package.
en
This object can give the information about attributes such as column names, number of
columns, and data types for the columns in the result set. To retrieve all these information,
C
a ResultSetMetaData object is created and assigned with the results fetched by the
getMetaData() method, called by the ResultSet object.
h
ec
pt
rA
Fo
©Aptech Limited
Slide 52
Let us understand ResultSetMetaData methods.
y
nl
O
se
Using slide 52, explain ResultSetMetaData methods.
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 53
Let us understand about connecting to database using type 4 driver.
y
nl
O
se
Using slide 53, explain about connecting to database using Type 4 driver.
rU
SQL Server 2012 is a widely used database from Microsoft. It allows the user to manipulate
data with a large number of data types, stored procedures, and offers a secure platform for
te
developing enterprise database applications. Java applications can be connected to SQL
Server 2012 through Type 4 JDBC Driver.
en
The Type 4 JDBC drivers are optimized for the Java environment, allowing you to
incorporate Java technology and extend the functionality and performance of your existing
h
system.
ec
Tips:
pt
The Type 4 JDBC driver is a pure Java driver that communicates directly with the vendor’s
database through sockets.
rA
Following figure shows the JDBC connectivity through JDBC type 4 driver:
Fo
©Aptech Limited
Slide 54
Let us summarize the session.
y
nl
O
se
Using slide 54, summarize the session. End the session with a brief summary of what has
been taught in the session. rU
te
9.3 Post Class Activities for Faculty
You should familiarize yourself with the topics of the next session which is Advanced JDBC
en
Features.
Tips:
C
You can also check the Articles/Blogs/Expert Videos uploaded on the OnlineVarsity site to
gain additional information related to the topics covered in the next session. You can also
h
connect to online tutors on the OnlineVarsity site to ask queries related to the sessions.
ec
pt
rA
Fo
©Aptech Limited
Session 10 – Advanced JDBC Features
Here, you can ask students the key topics they can recall from previous session. Prepare a
question or two which will be a key point to relate the current session objectives.
y
nl
10.1.1 Objectives
By the end of this session, the learners will be able to:
O
List and describe scrollable result sets
List different types of ResultSet and row-positioning methods
se
Explain stored procedures
Explain how to call a stored procedure using JDBC API
rU
Describe the steps to update records
Explain the steps of implementing transactions using JDBC
List the enhancements of JDBC 4.0 API
te
Explain RowSet and its type
Describe JDBC 4.1 RowSetProvider and RowSetFactory Interfaces
en
To teach this session, you should be well-versed with the concept of scrollable ResultSet
using JDBC and stored procedures, batch updates, and transactions.
h
This session also introduces the JDBC 4.0 and 4.1 features such as RowSet and its various
ec
You should teach the concepts in the theory class using the images provided. For teaching in
the class, you are expected to use slides and LCD projectors.
rA
Tips:
Fo
It is recommended that you test the understanding of the students by asking questions in
between the class.
In-Class Activities:
Follow the order given here during In-Class activities.
©Aptech Limited
Overview of the Session:
Give the students the overview of the current session in the form of session objectives.
Show the students slide 2 of the presentation.
y
nl
O
se
rU
This session describes how to work with scrollable result sets using JDBC. The session
te
provides explanations on stored procedure, batch updates, and transactions along with the
various ways of implementing them.
en
Then, the session introduces you to JDBC 4.0 and 4.1 features, such as RowSet and its
C
CachedRowSet.
ec
pt
rA
Fo
©Aptech Limited
10.2 In-Class Explanations
Slide 3
Let us understand the characteristics of ResultSet.
y
nl
O
se
rU
Using slide 3, explain the characteristics of ResultSet.
te
The ResultSet object in JDBC API represents a SQL result set in the JDBC application. A
default result set object cannot be updated or scrolled backward and forward.
en
The ResultSet object is a table of data representing a database result set which occurs
C
by executing the statements that queries the database. The data can be accessed in
ResultSet object through a cursor. This cursor is a pointer that points to one row of data
h
in the ResultSet.
ec
Scrollable - It refers to the ability to move backward as well as forward through a result
set.
rA
Updatable - It refers to the ability to update data in a result set and then copy the
changes to the database. This includes inserting new rows into the result set or deleting
existing rows.
Fo
Holdable - It refers to the ability to check whether the cursor stays open after a
COMMIT.
©Aptech Limited
Slides 4 to 6
Let us understand the scrollable ResultSet.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 4 to 6, explain the scrollable ResultSet.
se
A ResultSet object maintains a cursor pointing to its current row of data. Initially, the
rU
cursor is positioned before the first row. The next method moves the cursor to the next row,
and because it returns false when there are no more rows in the ResultSet object, it can
be used in a while loop to iterate through the result set.
te
A default ResultSet object is not updatable and has a cursor that moves forward only.
en
Thus, you can iterate through it only once and only from the first row to the last row. It is
possible to produce ResultSet objects that are scrollable and/or updatable.
C
Scrollability is the ability to move to any particular position in the result set, through either
relative positioning or absolute positioning. The relative positioning enables you to move a
h
specified number of rows forward or backward from the current row. Absolute positioning
enables you to move a specified row number, counting from either the beginning or the end
ec
Explain the table lists the methods that can be invoked on the Connection instance for
returning a scrollable ResultSet mentioned in slides 5 and 6.
rA
In-Class Question:
Fo
After you finish explaining Scrollable ResultSet, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
©Aptech Limited
Slide 7
Let us understand the types of ResultSet values.
y
nl
O
se
Using slide 7, explain the types of ResultSet values.
rU
Not all types are supported by all databases and JDBC drivers. You will have to check your
database and JDBC driver to see if it supports the type you want to use.
The DatabaseMetaData.supportsResultSetType(int type) method returns
te
true or false depending on whether the given type is supported or not.
en
TYPE_FORWARD_ONLY
C
TYPE_SCROLL_ INSENSITIVE
• A cursor that can be used to scroll in various ways through a ResultSet.
rA
©Aptech Limited
TYPE_SCROLL_SENSITIVE
• A cursor that can be used to scroll in various ways through a ResultSet.
• This type of cursor is sensitive to changes made to the database while it is
open. That is, if a record in the ResultSet is changed in the database by
another thread or process, it will be reflected in already opened ResulsSet
of this type.
Tips:
If you do not specify any ResultSet type, you will automatically get one that is
TYPE_FORWARD_ONLY.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 8 to 10
Let us understand the row positioning methods.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 8 to 10, explain the row positioning methods.
se
The ResultSet interface contains the row positioning methods. These methods are also
called as navigational methods. However, not all methods work with all ResultSet types,
rU
they depend on the database, JDBC driver, and the ResultSet type.
©Aptech Limited
Slide 11
Let us understand the updatable ResultSet.
y
nl
O
se
Using slide 11, explain updatable ResultSet.
rU
If the ResultSet is updatable, you can update the columns of each row in the
ResultSet. When updateRow() is called that the database is updated with the values
te
of the row. If you do not call this method, the values updated in the ResultSet are never
sent to the database.
en
Updatable ResultSet is the ability to update rows in a result set using Java programming
C
language methods rather than SQL commands. An updatable ResultSet will allow the
programmer to change the data in the existing row, to insert a new row, or delete an
h
existing row.
ec
The newUpdateXXX() methods of ResultSet interface can be used to change the data
in an existing row. When using an updatable result set, it is recommended to make it
pt
scrollable.
rA
Fo
©Aptech Limited
Slide 12
Let us understand concurrency in ResultSet.
y
nl
O
se
Using slide 12, explain concurrency in ResultSet.
rU
Concurrency is a process wherein two events take place in parallel. The concurrency type of
a result set determines whether it is updatable or not. The concurrency of
te
a ResultSet object determines what level of update functionality is supported.
en
The constant values that can be assigned for specifying the concurrency types are as
follows:
C
performed on the result set and the changes are copied to the database.
ec
pt
©Aptech Limited
Slide 13
Let us understand updating a row.
y
nl
O
se
Using slide 13, explain updating a row.
rU
There are two steps involved in this process:
First step: Change the values for a specific row using various update<Type> methods,
te
where <Type> is a Java data type.
Second step: Apply the changes to the rows of the underlying database.
en
The database itself is not updated until the second step. Updating columns in a
C
ResultSet without calling the updateRow() method does not make any changes to the
database. Once the updateRow() method is called, changes to the database are final and
h
cannot be undone.
ec
The following code snippet demonstrates the code to update price of the product:
...
pt
stmt = con.createStatement();
stmt =
rA
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery(
Fo
while (uprs.next()) {
float f = uprs.getFloat("PRICE");
uprs.updateFloat( "PRICE", f * percentage);
uprs.updateRow();
}
...
©Aptech Limited
The field ResultSet.TYPE_SCROLL_SENSITIVE creates a ResultSet object whose
cursor can move both forward and backward relative to the current position and to an
absolute position. The field ResultSet.CONCUR_UPDATABLE creates a
ResultSet object that can be updated. ResultSet contains various updater methods
that enable you to update column values of various data types. However, none of these
updater methods modifies the database; you must call the method
ResultSet.updateRow to update the database.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 14 and 15
Let us understand steps for inserting a row.
y
nl
O
se
rU
te
en
C
h
ec
pt
When you call the insertRow method, the new row is inserted into the object and is also
inserted in the database.
Fo
©Aptech Limited
Step 3: Inserting the Row
The insertRow() method is called to append the new row to the ResultSet and the
underlying database.
Explain the Code Snippet demonstrates the insertRow() method mentioned in slide 15.
Tips:
Not all JDBC drivers support inserting new rows with the ResultSet interface. If you
attempt to insert a new row and your JDBC driver database does not support this feature,
a SQLFeatureNotSupportedException exception is thrown.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 16
Let us understand steps for deleting a row.
y
nl
O
se
Using slide 16, explain steps for deleting a row.
•
•
Position the cursor.
rU
Call the deleteRow() method to commit the deletion of the row.
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 17
Let us understand stored procedure.
y
nl
O
se
Using slide 17, explain stored procedure.
rU
A stored procedure can be defined as a group of SQL statements performing a particular
task. Stored procedures having any combination of input, output, or input/output
te
parameters can be compiled and executed. As stored procedures are pre-compiled, they are
faster and more efficient than using individual SQL query statements.
en
You can call the procedure from a Java class using special syntax. When you call, the name
C
of the procedure and the parameters you specify are sent over the JDBC connection to the
DBMS, which executes the procedure and returns the results back over the connection.
h
Following are the basic elements that a stored procedure consists of:
ec
SQL statements
Variables
pt
Tips:
Fo
You can write your stored procedures in Java, Perl, or C, but they are most often written in a
language specific to the DBMS you are using.
©Aptech Limited
Slide 18
Let us understand characteristics of stored procedures.
y
nl
O
se
Using slide 18, explain characteristics of stored procedures.
rU
• They contain SQL statements using constructs and control structures.
• They can be invoked by name in an application that is using SQL.
te
• They allow an application program to run in two parts such as the application on the
client and the stored procedure on the server.
en
Stored procedures run in DBMS itself, they can help to reduce latency in applications.
C
Tips:
JDBC API provides the Statement, PreparedStatement,
h
Which method you use depends on the characteristic of the stored procedure. For example,
pt
if the stored procedure returns a single value, you should use a JDBC Statement object.
rA
The following table provides some guidelines for what method to use for which stored
procedure type:
Stored procedure type JDBC method
Fo
©Aptech Limited
Slides 19 and 20
Let us understand creating a stored procedure using Statement object.
y
nl
O
se
rU
te
en
C
h
ec
Using slides 19 and 20, explain creating a stored procedure using Statement object.
Explain the Code Snippet that shows the code to declare the string variable containing the
rA
Explain the Code Snippet that shows the use of the Statement object mentioned in slide
19.Explain the figure displaying the stored procedure using Statement object mentioned
in slide 20.
©Aptech Limited
Slide 21
Let us understand parameters of a stored procedure.
y
nl
O
se
Using slide 21, explain parameters of a stored procedure.
rU
Tell them that the attributes such as IN, OUT, and IN/OUT are the parameters modes with
a stored procedure. They define the formal parameters.
te
Then, explain the features of these parameters in a stored procedure.
en
The following code snippet creates a stored procedure to raise the price of the product:
C
// ...
pt
createProcedure =
"create procedure RAISE_PRICE(" +
rA
"begin " +
"main: BEGIN " +
"declare maximumNewPrice " +
"numeric(10,2); " +
"declare oldPrice numeric(10,2); " +
"select COFFEES.PRICE into oldPrice " +
"from COFFEES " +
"where COFFEES.COF_NAME " +
"= coffeeName; " +
©Aptech Limited
"set maximumNewPrice = " +
"oldPrice * (1 + " +
"maximumPercentage); " +
"if (newPrice > maximumNewPrice) " +
"then set newPrice = " +
"maximumNewPrice; " +
"end if; " +
"if (newPrice <= oldPrice) " +
"then set newPrice = oldPrice; " +
"leave main; " +
"end if; " +
y
"update COFFEES " +
"set COFFEES.PRICE = newPrice " +
nl
"where COFFEES.COF_NAME " +
"= coffeeName; " +
O
"select newPrice; " +
"END main; " +
se
"end";
// ...
}
Tips:
rU
te
The following figure shows the information about the parameter modes:
en
C
h
ec
pt
rA
Fo
©Aptech Limited
In-Class Question:
After you finish explaining Parameters of a Stored Procedure, you will ask the students an
In-Class question. This will help you in reviewing their understanding of the topic.
Which of the following parameter mode can be used to pass the initial value as
well as return the updated value to the calling method?
Answer:
IN/OUT
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 22 to 34
Let us understand creating a CallableStatement object.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
y
nl
O
se
rU
te
en
C
h
ec
A stored procedure can be called from a Java application with the help of a
pt
procedures. A CallableStatement object does not contain the stored procedure itself,
but contains only a call to the stored procedure.
Fo
The call to a stored procedure is written in an escape syntax. The call may take two forms,
such as with a result parameter and without a result parameter. The result parameter is a
value returned by a stored procedure, similar to an OUT parameter.
Both the forms have a different number of parameters used as input (IN parameters),
output (OUT parameters), or both (INOUT parameters). A question mark (?) is used to
represent a placeholder for a parameter.
©Aptech Limited
Explain the syntax for calling a stored procedure without parameters mentioned in slide 22.
Explain the syntax for calling a stored procedure in JDBC mentioned in slide 22.
Placeholders enclosed in square brackets indicate that they are optional. Explain the syntax
for a procedure that returns a result parameter mentioned in slide 22.
y
The getXX() methods such as getInt(), getString() in a ResultSet will retrieve
nl
values from a result set whereas in a CallableStatement, they will retrieve values
from the OUT parameters or return values of a stored procedure. CallableStatement
O
objects are created using the prepareCall() method of the Connection interface.
The section enclosed within the curly braces is the escape syntax for stored procedures. The
se
driver converts the escape syntax into native SQL used by the database.
rU
Explain the syntax mentioned in slide 25.
Consider the following statement:
te
CallableStatement cs = cn.prepareCall( “{call sal(?)}”);
The statement creates an instance of CallableStatement. It contains a call to the
en
stored procedure sal(), which has a single arguments and no result parameter. The type
of the (?) placeholder parameters whether it is IN or OUT parameter is totally dependent
C
OUT Parameters
Fo
In case the stored procedure returns some values (OUT parameters), the JDBC type of each
OUT parameter must be registered before executing the CallableStatement object.
The registerOutParameter() method is used to register the JDBC type. After the
registration is done, the statement has to be executed. The get<Type>() methods of
CallableStatement are used to retrieve the OUT parameter value. The
registerOutParameter() method uses a JDBC type (so that it matches the JDBC
type that the database will return), and get<Type>() casts this to a Java type.
©Aptech Limited
Some common JDBC types are as follows:
Char: used to represent fixed-length character string.
Varchar: used to represent variable-length string.
Bit: used to represent single bit value that can be zero or one.
Integer: used to represent a 32-bit signed integer value.
Double: used to represent a double-precision floating point number that supports 15
digits of mantissa.
Date: used to represent a date consisting of the day, month, and year.
y
nl
Explain the Code Snippet demonstrates how to use the registerOutParameter()
method mentioned in slide 27.
O
Explain the Code Snippet demonstrates how to retrieve an OUT parameter returned by a
se
stored procedure mentioned in slides 28 to 33.
A procedure for recalculating the salary of the highest salary earner is shown in the Code
Snippet mentioned in slide 34. rU
You can put a static value or a place holder in the CALL statement when creating the
te
CallableStatement object, for an IN parameter defined in a stored procedure. For an
OUT parameter defined in a stored procedure, you must put a static value or a place holder
en
Tips:
As with Statement objects, to call the stored procedure, you can
h
©Aptech Limited
Slide 35
Let us understand batch update.
y
nl
O
se
Using slide 35, explain Batch Update.
rU
Batch updates can be defined as a set of multiple update statements that is submitted to
the database for processing as a batch. In Java, the Statement, PreparedStatement,
te
and CallableStatement objects can be used to submit batch updates.
en
The benefits of batch updating is that it allows you to request records, bring them to the
client, make changes to the records on the client side, and then send the updated record
C
back to the data source at some other time. Submitting multiple updates together, instead
of individually, can greatly improve performance. Also, batch updating is used when there is
h
The batch of updates grouped together and sent to the database in one batch, rather than
sending the updates one by one. Sending them at one go is faster than sending them one by
pt
one, waiting for each one to finish. There is less network traffic involved in sending one
batch of updates, and the database might be able to execute some of the updates in
rA
parallel.
You can batch both, SQL inserts, updates, and deletes. It does not make sense to batch
Fo
select statements.
1. Using a Statement
2. Using a PreparedStatement
©Aptech Limited
Slide 36
Let us understand batch update using Statement interface.
y
nl
O
se
Using slide 36, explain batch update using Statement interface.
rU
Explain all the steps used to implement batch update.
te
In addition, the following code snippet uses a Statement object to execute batch updates:
en
try{
C
statement = connection.createStatement();
h
ec
} finally {
©Aptech Limited
In the code, the SQL statements to be executed in the batch is added in
the addBatch() method. Then you execute the SQL statements using
the executeBatch(). The int[] array returned by the executeBatch() method is
an array of int telling how many records were affected by each executed SQL statement in
the batch.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 37 to 39
Let us understand batch update using PreparedStatement interface.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Using slides 37 to 39, explain batch update using PreparedStatement interface.
The batch update facility is used with a PreparedStatement to associate multiple sets
of input parameter values with a single PreparedStatement object.
The addBatch() method of the Statement interface is given an SQL update statement
as a parameter, and the SQL statement is added to the Statement object’s list of
commands to be executed in the next batch. PreparedStatement interface allows
creating parameterized batch update.
The setXXX() methods of the PreparedStatement interface are used to create each
y
parameter set, while the addBatch() method adds a set of parameters to the current
nl
batch.
O
Finally, the executeBatch() method of the PreparedStatement interface is called
to submit the updates to the DBMS, which also clears the statement’s associated list of
batch elements.
se
Explain the Code Snippet shows how to perform batch updates using
rU
PreparedStatement mentioned in slides 38 and 39.
try{
ec
preparedStatement =
pt
connection.prepareStatement(sql);
preparedStatement.setString(1, "Gary");
rA
preparedStatement.setString(2, "Larson");
Fo
preparedStatement.addBatch();
preparedStatement.setString(1, "Stan");
preparedStatement.setString(2, "Lee");
©Aptech Limited
preparedStatement.addBatch();
}finally {
if(preparedStatement != null) {
preparedStatement.close();
y
}
nl
}
O
In the code, a PreparedStatement is created from an SQL statement with question
se
marks in, to show where the parameter values are to be inserted into the SQL. Then, each
set of parameter values are inserted into the preparedStatement, and
the addBatch() method is called. This adds the parameter values to the batch internally.
rU
You can now add another set of values, to be inserted into the SQL statement. Each set of
parameters are inserted into the SQL and executed separately, once the full batch is sent to
the database.
te
Finally, the executeBatch() method is called, which executes all the batch updates. The
en
SQL statement along with the parameter sets are sent to the database in one go.
The int[] array returned by the executeBatch() method is an array of int telling
C
how many records were affected by each executed SQL statement in the batch.
Tips:
h
executed separately by the database. That means, some of them succeed before one of
them fails. Succeeded one are applied to database, while rest of updates may not be. This
pt
©Aptech Limited
Slides 40 and 41
Let us understand batch update using CallableStatement interface.
y
nl
O
se
rU
te
en
C
h
ec
pt
Using slides 40 and 41, explain batch update using CallableStatement interface.
rA
procedures that take input parameters or no parameters at all. Also, the stored procedure
must return an update count. The executeBatch() method of the
CallableStatement interface that is inherited from PreparedStatement interface
will throw a BatchUpdateException if the return value of stored procedure is anything
other than an update count or takes OUT or IN/OUT parameters.
Explain the Code Snippet that shows batch update using CallableStatement interface
mentioned in slide 41.
©Aptech Limited
Slide 42
Let us understand transactions.
y
nl
O
se
Using slide 42, explain transactions.
rU
A transaction is a set of one or more statements that are executed together as a unit. This
ensures that either all the statements in the set are executed or none of them is executed.
te
In other words, a transaction is a set of actions to be carried out as a single, atomic action.
en
Explain the students the transaction mechanism using a scenario. To understand why
transactions are necessary in bank accounts, consider that you need to transfer $100 from
h
one account to the other. You do so by subtracting $100 from the first account, and adding
$100 to the second account. If this process fails after you have subtracted the $100 from the
ec
first bank account, the $100 are never added to the second bank account. The money is lost
in cyber space.
pt
To solve this problem the subtraction and addition of the $100 are grouped into a
rA
transaction. If the subtraction succeeds, but the addition fails, you can ‘rollback’ the first
subtraction. That way the database is left in the same state as before the subtraction was
executed.
Fo
Transactions also help to preserve the integrity of the data in a table. To avoid conflicts
during a transaction, a DBMS will use locks, which are mechanisms for blocking access by
others to the data that is being accessed by the transaction. Once a lock is set, it will remain
in force until the transaction is committed or rolled back.
©Aptech Limited
Tips:
You can execute the batch update inside a transaction. When executed inside a transaction
you can make sure that either all updates are executed, or none are. Any successful updates
can be rolled back, in case one of the updates fail.
In-Class Question:
After you finish explaining Transactions, you will ask the students an In-Class question. This
will help you in reviewing their understanding of the topic.
y
Why locks are used by DBMS?
nl
Answer:
To avoid multiple updates to the data from different users at the same time, DBMS locks the
O
records accessed for the updates.
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 43
Let us understand properties of transaction.
y
nl
O
se
Using slide 43, explain properties of transaction.
rU
Atomicity: A transaction is an atomic unit of processing. This transaction requires that we
execute a transaction to completion.
te
Consistency: A transaction is consistency preserving if it complete execution takes the
en
Isolation: A transaction should appear as though it is being executed in isolation from other
transactions.
h
Durability: The changes applied to the database by a committed transaction must persist in
ec
the database.
pt
rA
Fo
©Aptech Limited
Slides 44 to 48
Let us understand implementing transactions using JDBC.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Step 1: Start the Transaction
y
method commit is called explicitly.
All statements executed after the previous call to the method commit are included in
nl
the current transaction and are committed together as a unit.
O
Step 2: Perform Transactions
The second step is to perform the transaction as shown in the Code Snippet mentioned in
se
slide 45.
©Aptech Limited
Slides 49 and 50
Let us understand JDBC 4.0 features.
y
nl
O
se
rU
te
en
C
h
ec
pt
JDBC 4.0 has redefined subclasses of SQLException. Application servers use these
objects to look for vendor-specific extensions inside standard JDBC objects such as
Fo
©Aptech Limited
There are new overloads of the streaming methods in CallableStatement,
PreparedStatement, and ResultSet to define long lengths or omit length
arguments.
With JDBC 4.0, the JDBC application does not have to register drivers programmatically. The
important features of JDBC API 4.0 are automatic loading of driver class. With JDBC 4.0,
y
applications no longer need to issue a Class.forName() on the driver name; instead,
nl
the DriverManager will find an appropriate JDBC driver when the application requests a
O
connection.
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 51
Let us understand RowSet.
y
nl
O
se
Using slide 51, explain RowSet.
rU
RowSet is an interface in the new standard extension package javax.sql.rowset and
is derived from the ResultSet interface. It typically contains a set of rows from a source
te
of tabular data similar to a result set. A JDBC RowSet object holds tabular data in a way
en
that makes it more flexible and easier to use than a result set.
Some DBMS do not support result sets that can be scrolled (scrollable), and some do not
C
support result sets that can be updated (updatable). If a driver for that DBMS does not add
the ability to scroll or update result sets, you can use a RowSet object to do it.
h
updatable.
pt
It can be configured to connect to and read/write data from a JDBC data source. A JDBC
RowSet object is easier to use than a result set.
rA
Tips:
Fo
©Aptech Limited
Slide 52
Let us understand benefits of using RowSet over ResultSet.
y
nl
O
se
rU
Using slide 52, explain benefits of using RowSet over ResultSet.
All RowSet objects are derived from the ResultSet interface and therefore share its
te
capabilities. What makes JDBC RowSet objects special is that they add these new
en
capabilities:
©Aptech Limited
Slide 53
Let us understand different types of RowSets.
y
nl
O
se
rU
Using slide 53, explain different types of RowSets.
Explain the figure showing different Types of RowSets mentioned in slide 53.
te
Explain that a connected RowSet object uses a JDBC driver to make a connection to a
en
relational database and maintains that connection throughout its life span.
A disconnected RowSet object makes a connection to a data source only to read in data
C
from a ResultSet object or to write data back to the data source. After reading data from
or writing data to its data source, the RowSet object disconnects from it, thus becoming
h
‘disconnected’. During much of its life span, a disconnected RowSet object has no
ec
As a JavaBeans component, a JdbcRowSet object can be used, for example, in a GUI tool
to select a JDBC driver. A JdbcRowSet object can be used this way because it is effectively
a wrapper for the driver that obtained its connection to the database.
©Aptech Limited
Disconnected RowSet Objects
y
In-Class Question:
nl
After you finish explaining Different Types of RowSets, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
O
se
What are the different types of RowSets?
Answer:
Connected
Disconnected rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 54 and 55
Let us understand implementation of connected RowSet.
y
nl
O
se
rU
te
en
C
h
ec
pt
JdbcRowSet Interface
Fo
If a JdbcRowSet object has been constructed using the default constructor, then the new
instance is not usable until its execute() method is invoked. The execute() method
can only be invoked on such an instance if all the other properties such as command,
username, password, and URL have been set. These properties can be set using the
methods of the RowSet and the JdbcRowSet interface.
©Aptech Limited
JdbcRowSetImpl Class
An instance of this class can be obtained by using any of the following constructors:
JdbcRowSetImpl()
JdbcRowSetImpl(Connection con)
JdbcRowSetImpl(String url, String user, String password)
JdbcRowSetImpl(java.sql. ResultSet res)
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 56
Let us understand using JDBCRowSet object.
y
nl
O
se
Using slide 56, explain using JDBCRowSet Object.
rU
Explain some of the most commonly used methods of the JdbcRowSetImpl class that
are mentioned in slide 56.
te
A JDBCRowSet object is an enhanced ResultSet object. It maintains a connection to its
en
data source, just as a ResultSet object does. The main use of a JDBCRowSet object is to
make a ResultSet object scrollable and updatable when it does not otherwise have those
C
capabilities.
Tips:
h
An instance of JDBCRowSet can simply take calls invoked on it and in turn call them on its
ec
©Aptech Limited
Slide 57
Let us understand implementation of a disconnected RowSet.
y
nl
O
se
Using slide 57, explain Implementation of a disconnected RowSet.
rU
A disconnected RowSet is useful since it does not require a continuous connection with the
database. A disconnected RowSet stores its data in memory and operates on that data
te
rather than directly operating on the data in the database.
en
Disconnected RowSet are serializable and hence they are suitable for sending data over the
network.
pt
rA
Fo
©Aptech Limited
Slides 58 to 61
Let us understand using CachedRowSet object.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
rU
te
en
C
h
ec
Update
Updating a record from a RowSet object involves navigating to that row, updating data
Fo
Explain the Code snippet illustrates the updation of row mentioned in slide 58.
Insert
©Aptech Limited
The insert row is a special buffer row provided by an updatable result set for constructing a
new row. When the cursor is in this row only the update, get, and insertRow() methods
can be called. All the columns must be given a value before the insertRow() method is
invoked. The insertRow() method inserts the newly created row in the result set. The
moveToCurrentRow() method moves the cursor to the remembered position.
Delete
Deleting a row from a CachedRowSet object is simple. Explain the Code Snippet illustrates
this mentioned in slide 59.
y
nl
Retrieve
O
A CachedRowSet object is scrollable, which means that the cursor can be moved forward
and backward by using the next(), previous(), last(), absolute(), and
first() methods. Once the cursor is on the desired row, the getter methods can be
se
invoked on the RowSet to retrieve the desired values from the columns.
rU
A CachedRowSet object is special as it can operate without being connected to the data
source, that is, it is a disconnected RowSet object. It is called CachedRowSet object
because it stores its data in memory so that it can operate on its open data rather than on
te
the data stored in a database.
en
In-Class Question:
C
After you finish explaining Using CachedRowSet Object, you will ask the students an In-Class
question. This will help you in reviewing their understanding of the topic.
h
ec
Which method can be invoked on the RowSet to retrieve the desired values from
the columns?
pt
Answer:
The getter methods.
rA
Fo
©Aptech Limited
Slide 62
Let us understand event notification mechanism in RowSet.
y
nl
O
se
rU
Using slide 62, explain event notification mechanism in RowSet.
A RowSet object is inherently a JavaBeans component. The fields of a RowSet are the
te
JavaBean properties of the RowSet. RowSet objects follow the JavaBeans Event
Notification Model for processing events.
en
According to this model, all components that need to be notified of an event need to be
registered as event listeners for the component generating the events.
C
Movement of a cursor
Insertion, updation, or deletion of a row
ec
The notification of an event goes to all listeners, components that have implemented
the RowSetListener interface and have had themselves added to the RowSet object's
rA
©Aptech Limited
Slide 63
Let us summarize the session.
y
nl
O
se
Using slide 63, you will summarize the session. You will end the session with a brief
rU
summary of what has been taught in the session.
te
10.3 Post Class Activities for Faculty
You should familiarize yourself with the topics of the next session which is Design Patterns.
en
Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the Online Varsity site to
C
gain additional information related to the topics covered in the next session. You can also
connect to online tutors on the Online Varsity site to ask queries related to the sessions.
h
ec
pt
rA
Fo
©Aptech Limited
Session 11 – Design Patterns
Here, you can ask students the key topics they can recall from previous session. Prepare a
question or two which will be a key point to relate the current session objectives.
y
nl
11.1.1 Objectives
By the end of this session, the learners will be able to:
O
Describe polymorphism
Describe the procedure to override methods of the Object class
se
Explain design patterns
Describe the Singleton, Data Access Object (DAO), and Factory and Observer design
patterns
Describe delegation rU
Explain composition and aggregation
te
11.1.2 Teaching Skills
en
To teach this session, you should be well-versed with the concept of polymorphism and how
to apply it by overriding the various methods of the Object class. You should teach the
C
concepts in the theory class using the figures provided in the sessions.
For teaching in the class, you are expected to use slides and LCD projectors.
h
ec
Tips:
It is recommended that you test the understanding of the students by asking questions in
pt
In-Class Activities:
Follow the order given here during In-Class activities.
Fo
©Aptech Limited
Overview of the Session:
Then give the students the overview of the current session in the form of session objectives.
Show the students slide 2 of the presentation.
y
nl
O
se
rU
Tell the students that the session describes briefly about polymorphism in Java. It then
explains how to apply polymorphism by overriding the various methods of the Object
class. Then, the session explains design patterns in detail. It explains some of the design
te
patterns such as Singleton, Data Access Object (DAO), Factory, and Observer design
patterns. Then, it describes delegation, composition, and aggregation in design patterns.
en
C
h
ec
pt
rA
Fo
©Aptech Limited
11.2 In-Class Explanations
Slide 3
Let us understand the concept of polymorphism.
y
nl
O
se
rU
Using slide 3, explain the concept of polymorphism.
te
Tell them that there are three key aspects of object-oriented programming which form the
principles during the design of software. These are as follows:
en
Encapsulation means that objects keep their state information private. Rather than directly
C
manipulating an object's data, other objects send requests to the object, in the form of
messages, some of which the object may respond to by altering its internal state.
h
Inheritance means that objects of one class can derive part of their behavior from another
ec
Polymorphism means that objects of different classes can be used interchangeably. In this,
a subclass can have its own unique behavior even while sharing certain common
rA
These features are not the ‘Design Principles’, but a repetition of a good OO design.
Fo
©Aptech Limited
Slides 4 to 7
Let us understand how to implement polymorphism.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 4 to 7, explain how to implement polymorphism.
se
The concept of method overriding is an example of polymorphism in object-oriented
programming in which the same method behaves in a different manner in super class and in
subclass.
rU
A fundamental feature of OOP is that when a class is inherited from another class, then the
subclass inherits the members of the super class, including its methods. These methods can
te
also be overridden, that is, they can be given new functionality, provided the super class
method has not been marked as final. In OOP, overriding means to override the
en
Then, explain that the demonstration of polymorphism shown in code snippet where a
ec
super class named Car has been created having two methods, accelerate() and
printDescription(). A sub class named LuxuryCar is created based on Car and
overrides the methods of the Car class.
pt
Then, explain the code snippet which demonstrates the main() method that creates two
instances of type Car, instantiates them, and invokes the accelerate() and
Fo
©Aptech Limited
Slides 8 to 19
Let us understand how to override the methods of Object class.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
Using slides 8 to 19, explain how to override the methods of Object class.
©Aptech Limited
Object is the root class. Its methods can be overridden by any class (unless the methods
are marked as final).
The Object class, in the java.lang package, sits at the top of the class hierarchy. Every
class is descendant of the Object class and inherits the instance methods of Object.
When you use any of these methods, you need to override them with code that is specific to
your class. Otherwise, the methods provide the default implementation.
Following are the methods that can be overridden with a different functionality as
compared to the root class:
y
public boolean equals(Object obj)
public int hashCode()
nl
public String toString()
O
The equals() method compares two objects to determine if they are equal. The
equals() method helps to check logical or value equality. To test reference equality, you will
se
use the == operator.
rU
Then, explain the code snippet that checks the equality of object references. The equality
operator (==) compares the memory addresses of the two strings. Therefore, when strAObj
is compared to strBObj, the result is false, although their value is same, which is JOHN. A
te
comparison between strAObj and strCObj returns false because the references of the two
different String objects are different addresses. However, notice that when strAObj is
en
compared to strEObj, the result is true because they point to the same memory location.
Then, explain the code snippet that checks for logical or value equality. The equals()
C
method is used to check for logical equality. The equals() method is implicitly inherited from
the Object class. The String class overrides the equals() method and compares the
h
two String objects character by character. This is done because the equals() method
ec
inherited from Object class performs only reference equality and not value equality.
However, any code that overrides the equals() method must override the hashCode()
pt
method because overriding the equals() method makes the Object’s implementation of
hashCode() invalid.
rA
The hashCode() method of Object class returns the object’s memory address in
hexadecimal format.
Fo
Then, explain the code snippet that overrides the default implementation of the equals()
and hashCode() methods to include testing for logical equality. The value returned
by hashCode() is the object's hash code, which is the object's memory address in
hexadecimal.
©Aptech Limited
The toString() method of Object class returns a string representation of the object. It
is typically used for debugging. Explain the code snippet mentioned in slides 18 and 19.
Tips:
The toString() method returns the string representation of the object. If you print any
object, java compiler internally invokes the toString() method on the object. So,
overriding the toString() method, returns the desired output, it can be the state of an
object depends on your implementation.
y
In-Class Question:
nl
After you finish explaining overriding the methods of Object class, you will ask the
students an In-Class question. This will help you in reviewing their understanding of the
O
topic.
se
When the toString() method of Object class is used?
Answer:
It is used for debugging.
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 20 to 24
Let us understand the instanceof operator.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
rU
te
en
C
h
ec
The instanceof operator is used to check the type of an object at run-time. It is also
known as type comparison operator because it compares the instance with type. It returns
true or false. If you apply the instanceof operator with any variable that have null value,
it returns false.
For example, the following code snippet shows the comparison of instanceof operator
with null value:
String s = null;
if (s instanceof java.lang.String) {
©Aptech Limited
System.out.println("true");
} else {
System.out.println("false");
}
Tips:
instanceof operator is used for object reference variables only to check whether
an object is of a particular type.
y
nl
Before attempting a ‘downcast’, we need to use instanceof operator for testing
an object to see if it's an instance of one of its subtypes.
O
instanceof operator is useful with generics and collection classes.
se
Use of the instance operator protects the program from attempting a wrong
downcast.
rU
You can test whether the null reference is an instance of a class, this will always
result in false.
te
Use of instanceof operator to test across two different class hierarchies will
result in compile time error.
en
Use of instanceof operator with object array and primitive array is possible
because arrays are objects in java.
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 25 to 34
Let us understand design patterns.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
y
nl
O
Using slides 25 to 34, explain design patterns.
se
Design Pattern
rU
If a problem occurs over and over again, a solution to that problem has been used
effectively. That solution is described as a pattern.
te
Patterns are a way to analyze solutions to recurring problems, make them reusable and
communicate them. Patterns are a way of thinking.
en
The design patterns are language-independent strategies for solving common object-
C
oriented design problems. When you make a design, you should know the names of some
common solutions. Learning design patterns is good for people to communicate each other
effectively.
h
ec
In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides
published a book titled Design Patterns - Elements of Reusable Object-Oriented
pt
These authors are collectively known as Gang of Four (GOF). According to these authors,
design patterns are primarily based on the following principles of object orientated design.
Generally, to build a system, you may need many patterns to fit together. Different designer
may use different patterns to solve the same problem. Some of uses of patterns are as
follows:
©Aptech Limited
Patterns are not methods or framework
Patterns give you hint to solve a problem effectively
Today, there are 23 design patterns by GOF are well known. However, at least 250 patterns
are discovered and used in the object-oriented development world.
y
use case.
Some of the creational patterns are as follows:
nl
o Abstract Factory
O
o Builder
o Factory
o Prototype
se
o Singleton
Structural Patterns - These design patterns concern class and object composition.
rU
Concept of inheritance is used to compose interfaces and define ways to compose
objects to obtain new functionalities.
Some of the structural patterns are as follows:
te
o Adapter
o Bridge
en
o Composite
o Decorative
o Façade
C
o Proxy
Behavioral Patterns - These design patterns are specifically concerned with
h
o Iterator
o Mediator
rA
o Observer
o Visitor
Fo
Creational Patterns
Singleton pattern is a type of creational pattern. The singleton design pattern provides
complete information on such class implementations. One instance of a class is accessible
globally in an application.
Examples of Singleton pattern can be a single file system, a single Window manager, a single
printer spooler, a test engine, an Input/Output socket, and so on.
©Aptech Limited
It is recommended to use singleton classes to concentrate access to particular resources
into a single class instance. To implement a singleton design pattern, perform the following
steps:
Next, a public factory method is declared static to access the static field.
y
A factory method is a method that instantiates objects. Similar to the concept of a
nl
factory that manufactures products, the job of the factory method is to manufacture
objects.
O
Explain the code snippet mentioned in slides 27 and 28. This class illustrates the
se
implementation of singleton design patterns.
rU
Explain another code snippet mentioned in slide 29. This class creates the object of the
Singleton class defined in the earlier code snippet.
In Java, interfaces include constant fields. They can be used as reference types. They are
te
important components of many design patterns.
en
Then, explain the interfaces in Java and its use in designing a software design based on
design patterns.
h
Consider a scenario where following programs are created to automate certain tasks of an
ec
automobile:
pt
A program that turns the vehicle in different directions. There can be such many other
programs for automobile automation. Now, all these programs need not be made by a
rA
programmers decide to write a code for a similar target (such as automation of automobile),
they comply with this interface.
In Java, interfaces include constant fields and methods whose implementation is provided
by the class signing an implementation contract with the interface. Interfaces also play a
vital role in design patterns as they can standardize the operations performed by the objects
in the application.
©Aptech Limited
The declaration of an interface in Java includes:
Modifiers
The keyword interface
The interface name
A comma-separated list of parent interfaces that it can extend
Interface body
y
public int passengerCapacity = 400;
nl
// method signatures
void fly();
O
......
se
// more method signatures
}
}
public interface IAutomobile extends IVehicle {
h
}
pt
An IAutomobile interface is created that extends IVehicle. Users can now either use the
old interface or upgrade to the new interface. If a class implements the new interface, it must
rA
The Data Access Object (DAO) pattern is used when an application is created that needs to
persist its data. The DAO pattern involves a technique for separating the business logic from
persistence logic. It is based on adopting a unique interface which will help to access
multiple databases.
©Aptech Limited
The DAO pattern uses the following:
DAO Interface: This defines the standard operations for a model object. In other words,
it defines the methods used for persistence.
DAO Concrete Class: This implements the DAO interface and retrieves data from a data
source, such as a database.
Model Object or Value Object: This includes the get/set methods that store data
retrieved by the DAO class.
Explain the figure that shows the structure of a DAO design pattern mentioned in slide 32.
y
Explain the following terms:
nl
Book object will act as a Model or Value Object
O
BookDao is the DAO Interface
se
BookDaoImpl is the concrete class that implements the DAO interface
DAOPatternApplication is the main class. It will use BookDao to display the use of the
DAO pattern. rU
Then, explain the example to persist the Book details to the list using DAO pattern.
te
en
Factory Pattern
In Factory pattern, we create object without exposing the creation logic to the client and
ec
Consider the example of the Shape factory which creates the different shapes for the
clients.
rA
Fo
The client applications can invoke the ShapeFactory class to get the shape object
without understanding how a particular shape is created from the concrete classes in the
application.
©Aptech Limited
This is used when you have a super class with multiple sub classes. A factory is a class in Java
that encapsulates object creation code. A factory class instantiates and returns a particular
type of object based on data passed to the factory.
Observer Pattern
Observer pattern is used when there is one to many relationship between objects such as if
one object is modified, its dependent objects are to be notified automatically. Observer
pattern falls under behavioral pattern category.
Usage: Observer pattern is often used in GUI application. For example, defining a one-to-
y
many dependency between objects so that when one object changes state, all its
dependents are notified and updated automatically, like stock change affecting many data
nl
or diagram updated accordingly.
O
It helps to observe the behavior of objects such as change in state or change in property. An
object called the subject maintains a collection of objects called observers. Whenever the
se
subject changes, it notifies the observers.
rU
Observers can be added or removed from the collection of observers in the subject.
In observer pattern, the object that watch on the state of another object are called observer
te
and the object that is being watched is called Subject.
en
Explain the figure that shows the factory pattern diagram mentioned in slide 34.
In-Class Question:
C
After you finish explaining Design Patterns, you will ask the students an In-Class question.
This will help you in reviewing their understanding of the topic.
h
ec
Tips:
Design Patterns promotes reusability that provides more robust and highly maintainable
Fo
code.
©Aptech Limited
Slide 35
Let us understand about delegation.
y
nl
O
se
Using slide 35, explain the delegation.
rU
Delegation is a relationship between objects. Here, one object forwards method calls to
another object, which is called its delegate.
te
Unlike inheritance, delegation does not create a super class. Delegation does not force to
en
accept all the methods of the super class. Delegation supports code reusability and provides
run-time flexibility.
C
Usage: If you need to use functionality in another class but you do not want to change that
functionality, then use delegation instead of inheritance.
pt
In-Class Question:
rA
After you finish explaining Delegation, you will ask the students an In-Class question. This
will help you in reviewing their understanding of the topic.
Fo
©Aptech Limited
Slides 36 to 41
Let us understand about composition and aggregation.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Composition refers to the process of composing a class from references to other objects.
Composition forms the building blocks for data structures. Programmers can use object
composition to create more complex objects.
In aggregation, one class owns another class. In composition, when the owning object is
destroyed, so are the objects within it. However, in aggregation, this is not true.
Composition and aggregation are design concepts and not actual patterns.
An aggregation is used when life of object is independent of container object, but still
y
container object owns the aggregated object, whereas a Composition is used where each
part may belong to only one whole at a time.
nl
O
Explain the code snippet mentioned in slide 37. The code implements object composition, it
performs the following steps:
se
Create a class with reference to other classes.
Add the same signature methods that forward to the referenced object.
rU
Consider an example of a student attending a course.
The student ‘has a’ course.
te
The composition for the Student and Course classes is depicted in the Code Snippet
en
Tips:
You can read more on the following link for aggregation and composition:
http://www.apwebco.com/aggregation/AggregationComposition.html
h
ec
pt
rA
Fo
©Aptech Limited
Slide 42
Let us summarize the session.
y
nl
O
se
Using slide 42, summarize the session. End the session with a brief summary of what has
been taught in the session. rU
te
11.3 Post Class Activities for Faculty
You should familiarize yourself with the topics of the next session which is
en
Tips:
C
You can also check the Articles/Blogs/Expert Videos uploaded on the OnlineVarsity site to
gain additional information related to the topics covered in the next session. You can also
h
connect to online tutors on the OnlineVarsity site to ask queries related to the sessions.
ec
pt
rA
Fo
©Aptech Limited
Session 12 – Internationalization and
Localization
Here, you can ask students the key topics they can recall from previous session. Prepare a
y
question or two which will be a key point to relate the current session objectives.
nl
O
12.1.1 Objectives
By the end of this session, the learners will be able to:
se
Describe internationalization
Describe localization
rU
Describe the Unicode character encoding
Explain the internationalization process
Define the internationalization elements
te
12.1.2 Teaching Skills
en
To teach this session, you should be well-versed with various methods that Java application
uses to handle different languages, number formats. You should be well-versed with
C
You should teach the concepts in the theory class using the images provided. For teaching in
the class, you are expected to use slides and LCD projectors.
pt
Tips:
rA
It is recommended that you test the understanding of the students by asking questions in
between the class.
In-Class Activities:
Fo
©Aptech Limited
Overview of the Session:
Then give the students the overview of the current session in the form of session objectives.
Show the students slide 2 of the presentation.
y
nl
O
se
rU
Tell the students this session describes the internationalization and localization process that
makes an application serve users in multiple different languages and are suitable for global
market. It describes various methods that Java application can use to handle different
te
languages, number formats, and so on.
en
C
h
ec
pt
rA
Fo
©Aptech Limited
12.2 In-Class Explanations
Slide 3
Let us understand the globalization of software.
y
nl
O
se
rU
Using slide 3, explain the globalization of software.
te
With the advent of the Internet, globalization of software products has become an
important requirement. When the input and output operations of an application is made
en
specific to different locations and user preferences, users around the world can use it with
ease. This can be achieved using the processes called internationalization and localization.
C
The adaptation should be done with extreme ease without the need to change the coding of
h
the application.
ec
pt
rA
Fo
©Aptech Limited
Slide 4
Let us understand internationalization.
y
nl
O
se
Using slide 4, explain internationalization.
rU
An application is accessible to the international market when the input and output
operations are specific to different locations and user preferences. The process of designing
te
such an application is called internalization.
en
covers more than just language. It also covers formatting of numbers, date and time, and so
on.
h
between the first letter i and the last letter n. Java includes a built-in support to
internationalize applications.
pt
rA
Fo
©Aptech Limited
Tips:
With the addition of localized data, the same executable can run worldwide.
Textual elements, such as status messages and the GUI component labels, are not
hardcoded in the program. Instead, they are stored outside the source code and
retrieved dynamically.
Support for new languages which does not require recompilation.
Culturally-dependent data, such as dates and currencies, appear in formats that
y
conform to the end user's region and language.
nl
It can be localized quickly.
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 5
Let us understand localization.
y
nl
O
se
Using slide 5, explain localization.
rU
Localization deals with a specific region or language. In localization, an application is
adapted to a specific region or language. Locale-specific components are added and text is
te
translated in the localization process.
en
Localization is what the Java application does when it adapts itself to a user with a specific
language, number format, date and time, and so on.
C
Localization is commonly referred as l10n. 10 in l10n refers to the 10 letters between the
first letter l and the last letter n. Primarily, in localization, the user interface elements and
h
In-Class Question:
pt
After you finish explaining Localization, you will ask the students an In-Class question. This
will help you in reviewing their understanding of the topic.
rA
Answer:
The user interface elements and documentation are translated.
©Aptech Limited
Slide 6
Let us understand benefits of I18N and L10N.
y
nl
O
se
Using slide 6, explain benefits of I18N and L10N.
rU
No Recompilation of New Languages: New languages are supported without
recompilation.
te
Same Executable File: The localized data needs to be incorporated in the application and
en
Dynamic Retrieval of Textual Elements: Textual elements are not hardcoded in the
program.
h
Conformation to the End User’s Region and Language: Region specific information such
ec
as currencies, numbers, date, and time follow the specified format of the end user’s
region and language.
pt
L10N complements I18N by helping the product adapt to a particular language or culture,
enable you to access to more markets.
Fo
©Aptech Limited
Slides 7 to 12
Let us understand ISO codes.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
In the internationalization and localization process, a language is represented using the
alpha-2 or alpha-3 ISO 639 code, such as es that represents Spanish. The code is always
represented in lower case letters.
A country is represented using the ISO 3166 alpha-2 code or UN M.49 numeric area code. It
is always represented in upper case. For example, ES represents Spain. If an application is
well internationalized, it is easy to localize it for a character encoding scheme.
Explain the Code Snippet that illustrates the use of Japanese language for displaying a
message mentioned in slides 8 to 12. In the code, two arguments are accepted to represent
y
country and language. Depending on the arguments passed during execution of the
program, the message corresponding to that country and language is displayed. For this, five
nl
properties files have been created.
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 13 and 14
Let us understand about Unicode.
y
nl
O
se
rU
te
en
C
h
ec
pt
Unicode is a computing industry standard for the consistent encoding, representation, and
handling a text expressed in most of the world writing system. Unicode success at unifying
character sets has led to its widespread and predominant use in the internationalization and
Fo
localization of computer software. The standard has been implemented in many recent
technologies, including XML, Java programming language, and modern operating system.
Unicode provides a unique number for every character irrespective of platform, program, or
language. The Unicode standard was first designed using 16 bits to encode characters. 16-
bit encoding supports 216 (65,536) characters where in the hexadecimal, they ranged from
0x0000 to 0xFFFF.
©Aptech Limited
This was insufficient to define all characters in world languages. So, the Unicode standard
was extended to 0x10FFFF hexadecimal values. This new standard supports over one million
characters.
Following list defines the terminologies used in the Unicode character encoding:
Character: This represents the minimal unit of text that has semantic value.
Character Set: This represents set of characters that can be used by many languages.
Coded Character: This is a character set. Each character in the set is assigned a unique
number.
Code Point: This is the value that is used in a coded character set. A code point is a 32-
y
bit int data type. Here, the upper 11 bits are 0 and the lower 21 bits represent a valid
nl
code point value.
Code Unit: This is a 16-bit char value.
O
Supplementary Characters: These are the characters that range from U+10000 to
U+10FFFF.
o Supplementary characters are represented by a pair of code point values called
se
surrogates that support the characters without changing the char primitive data
type.
rU
o Surrogates also provide compatibility with earlier Java programs.
Basic Multilingual Plane (BMP): These are the set of characters from U+0000 to U+FFFF.
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 15
Let us understand Unicode character encoding.
y
nl
O
se
Using slide 15, explain Unicode character encoding.
rU
Consider the following points for Unicode character encoding:
The hexadecimal value is prefixed with the string U+.
te
The valid code point range for the Unicode standard is U+0000 to U+10FFFF.
en
Explain the table that shows code point values for certain characters mentioned in slide 15.
C
The Unicode standard uses hexadecimal to express a character. The Unicode standard was
initially designed using 16 bits to encode characters because primary machines were 16-bit
h
PC’s.
ec
Tips:
UTF-8 uses only one byte to encode English character.
pt
©Aptech Limited
Slide 16
Let us understand Internationalization process.
y
nl
O
se
Using slide 16, explain Internationalization process.
•
•
Creating the Properties files
Defining the Locale
rU
te
• Creating a ResourceBundle
• Fetching the text from the ResourceBundle class
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 17 and 18
Let us understand how to create the Properties files.
y
nl
O
se
rU
te
en
C
h
ec
pt
Using slides 17 and 18, explain how to create the Properties files.
rA
Following example shows the lines included in the default properties file,
MessagesBundle.properties that needs to be translated:
greetings = Hello
farewell = Goodbye
inquiry = How are you?
Since the messages are in the properties file, it can be translated into various languages. No
changes to the source code are required.
©Aptech Limited
To translate the message in French, the French translator creates a properties file called
MessagesBundle_ fr_FR.properties which contains the following lines:
greetings = Bonjour.
farewell = Au revoir.
inquiry = Comment allez-vous?
Notice that, the values to the right side of the equal sign are translated. The keys on the left
side are not changed. These keys must not change because they are referenced when the
program fetches the translated text. The name of the properties file is important.
The Java properties class is used for storing data for your application, since it consists of a
y
hashtable data structure of String keys with a String value for each key. The store method of
nl
the Properties class allows you to easily store your Properties object to a file.
O
In-Class Question:
se
After you finish explaining how to create the Properties files, you will ask the students an In-
Class question. This will help you in reviewing their understanding of the topic.
rU
Why the keys on the left side are not changed?
te
Answer:
As they are referenced when the program fetches the translated text.
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 19 to 21
Let us understand how to define the Locale.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Using slides 19 to 21, explain how to define the Locale.
The Locale object identifies a particular language and country. A Locale is simply an
identifier for a particular combination of language and region.
Locale is a set of parameters that defines the user language, country, and any special variant
y
preferences that the user wants to see in their user interface. Usually, a locale identifier
consists of at least a language identifier and a region identifier.
nl
O
A Locale object is created using the following constructors:
public Locale(String language, String country)
public Locale(String language)
se
Locale objects are only identifiers. After defining a Locale, the next step is to pass it to
rU
other objects that perform useful tasks, such as formatting dates and numbers. These
objects are locale-sensitive because their behavior varies according to Locale.
te
A ResourceBundle is an example of a locale-sensitive object.
en
©Aptech Limited
Slides 22 to 25
Let us understand how to create a ResourceBundle.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 22 to 25, explain how to create a ResourceBundle.
se
The java.util.ResourceBundle class is used to store texts and components that are
locale sensitive. The ResourceBundle has two subclasses called
rU
PropertyResourceBundle and List ResourceBundle. The
PropertyResourceBundle class stores localized text in standard Java property files.
te
ResourceBundle objects contain locale-specific objects. These objects are used to isolate
locale-sensitive data, such as translatable text. The ResourceBundle class is used to
en
The ResourceBundle class has a static and final method called getBundle() that
pt
Explain the Code Snippet that displays how to create a ResourceBundle mentioned in
slides 23 and 24. To retrieve the locale-specific data from the properties file, the
ResourceBundle class object should first be created.
©Aptech Limited
Slide 26
Let us understand fetching the text from the ResourceBundle class.
y
nl
O
se
Using slide 26, explain fetching the text from the ResourceBundle class.
rU
The properties files contain key-value pairs. The values consist of the translated text that the
program will display. The keys are specified when fetching the translated messages from the
te
ResourceBundle with the getString() method.
en
The Code Snippet that illustrates how to retrieve the value from the key-value pair using the
getString() method mentioned in slide 26. The code uses the key greetings
C
because it reflects the content of the message. The key is hardcoded in the program and it
must be present in the properties files. If the translators accidentally modify the keys in the
h
properties files, then the getString()method will be unable to locate the messages.
ec
pt
rA
Fo
©Aptech Limited
Slide 27
Let us understand Internationalization elements.
y
nl
O
se
Using slide 27, explain Internationalization elements.
•
•
Component Captions
rU
Numbers, Currencies, and Percentages
te
• Date and Times
• Messages
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slide 28
Let us understand component captions.
y
nl
O
se
Using slide 28, explain component captions.
rU
These refer to the GUI component captions such as text, date, and numerals. These GUI
component captions should be localized because their usage vary with language, culture,
te
and region.
en
Formatting the captions of the GUI components ensures that the look and feel of the
application is in a locale-sensitive manner. The code that displays the GUI is locale-
C
©Aptech Limited
Slides 29 to 36
Let us understand numbers, currencies, and percentages.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Fo
rA
pt
ec
h
C
en
©Aptech Limited
te
rU
se
O
nl
y
y
nl
O
se
rU
te
en
C
h
ec
The format of numbers, currencies, and percentages vary with culture, region, and
pt
language. Hence, it is necessary to format them before they are displayed. For example, the
number 12345678 should be formatted and displayed as 12,345,678 in the US and
rA
12.345.678 in Germany.
Similarly, the currency symbols and methods of displaying the percentage factor also vary
Fo
By invoking the methods provided by NumberFormat class, you can format number,
currencies and percentages according to Locale. You can format primitive-type numbers
such as double. The currency can be format same as numbers except that you call
getCurrencyInstance to create a formatter.
©Aptech Limited
To format the percentage, invoke the getPercentInstance method. With this, a
decimal fraction such as 0.75 is displayed as 75%.
Explain the Code Snippet that shows how to create locale-specific format of number for the
country Japan mentioned in slides 30 to 33.
The syntax for some of the methods to format currencies are as follows:
public final String format(double currency
public static final NumberFormat getCurrencyInstance()
public static NumberFormat getCurrencyInstance(Locale
y
inLocale)
nl
Explain the Code Snippet that shows how to create locale-specific format of currency for the
O
country, France mentioned in slides 34 and 35.
Explain the Code Snippet that shows how to create locale-specific format of percentages for
se
the country, France mentioned in slide 36.
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 37 to 40
Let us understand date and time.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 37 to 40, explain date and time.
se
The date and time format should conform to the conventions of the end user’s locale. The
date and time format varies with culture, region, and language. Hence, it is necessary to
format them before they are displayed.
rU
In German, the date can be represented as 20.04.07, whereas in US, it is represented as
te
04/20/07. Java provides the java.text.DateFormat and
java.text.SimpleDateFormat class to format date and time. The DateFormat
en
Next, the format() method of the NumberFormat class is also invoked. The date to be
formatted is passed as an argument. The DateFormat getDateInstance(style,
locale) method returns an instance of the class DateFormat for the specified style and
h
locale.
ec
Explain the Code Snippet that demonstrates how to retrieve a DateFormat object and
display the date in Japanese format mentioned in slides 39 and 40. The DateFormat
allows you to format dates and times with predefined styles in a locale sensitive manner.
To display date and time in the same string, create a formatter with the
getDateTimeInstance method. The first parameter is date style, while second
parameter is time style.
©Aptech Limited
In-Class Question:
After you finish explaining Date and Time, you will ask the students an In-Class question.
This will help you in reviewing their understanding of the topic.
Answer:
It is used to create locale-specific formats for date.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
Slides 41 to 44
Let us understand Messages.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
©Aptech Limited
y
nl
O
Using slides 41 to 44, explain Messages.
se
Programs that keep us informed by displaying status and error messages. These messages
need to be translated, so that they can be understood by end users around the world.
rU
Compound message contains variable data.
Displaying messages such as status and error messages are an integral part of any software.
te
The MessageFormat class helps create a compound message.
en
2. Create a template.
3. Create an Object array for variable arguments.
4. Create a MessageFormat instance and set the desired locale.
h
The MessageFormat class has a method applyPattern() to apply the pattern to the
pt
Explain the Code Snippet when executed will display the message in Danish using
MessageFormater class mentioned in slides 42 to 44.
Fo
Tips:
Compound messages are difficult to translate because message text is fragmented. If you
provide compound messages, localization will take longer and cost more.
©Aptech Limited
Slide 45
Let us summarize the session.
y
nl
O
se
Using slide 45, summarize the session. End the session with a brief summary of what has
been taught in the session. rU
te
12.3 Post Class Activities for Faculty
en
You should familiarize yourself with the topics of the next session.
C
Tips:
You can also check the Articles/Blogs/Expert Videos uploaded on the OnlineVarsity site to
h
gain additional information related to the topics covered in the next session. You can also
connect to online tutors on the OnlineVarsity site to ask queries related to the sessions.
ec
pt
rA
Fo
©Aptech Limited
Session 13: Advanced Concurrency and
Parallelism
13.1 Pre-Class Activities
Before you commence the session, you should familiarize yourself with the topics of this
session in-depth. Prepare a question or two that will be a key point to relate the current
session objectives.
y
13.1.1 Objectives
nl
By the end of this session, learners will be able to:
O
Explain the enhancements of java.util.concurrency package
se
Describe atomic operations with the new set of classes of the
java.util.concurrent.atomic package
Explain the StampedLock class to implement locks
rU
Explain the new features of ForkJoinPool
Define parallel streams
Describe parallel sorting of arrays
te
Identify recursive actions of the fork/join framework
en
To teach this session, you should be well versed with the concepts of Java Programming.
You should be familiar with the difference between Professional Programming in Java. You
h
You should teach the concepts in the theory class using the images provided. For teaching in
the class, you are expected to use slides and LCD projectors.
pt
Tips:
rA
It is recommended that you test the understanding of the students by asking questions in
between the class.
Fo
In-Class Activities
© Aptech Limited
Slide 2
Objectives
y
nl
O
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 2
se
13.2 In-Class Explanations
Slides 3 and 4
Let us understand the concept of parallelism.
rU
te
Introduction [1-2]
© Aptech Limited
Introduction [2-2]
y
through work stealing strategy.
◆ The Fork-Join framework in Java meets the work
nl
stealing requirements through recursive job
partitioning.
O
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 4
Provide a brief overview on the concept of parallelism using the slide. Concept of parallelism
is very similar to tasks that run parallel in real world, such as the train tracks. Parallelism
se
refers to the process of taking a serial code that runs on a single CPU and dividing the work
across multiple CPUs. Through parallelism, applications run more efficiently. Any challenges
rU
faced by parallelism are addressed through work stealing strategy. The Fork-Join framework
in Java meets the work stealing requirements through recursive job partitioning.
te
Slide 5
Let us understand the Enhancements in the java.util.concurrent Package.
en
java.util.concurrency package
• CompletableFuture
h
Classes • CountedCompletor
• ConcurrentHashMap.KeySetView
ec
• CompletableFuture.AsynchronousCompletionTask
Interface • CompletionStage<T>
pt
rA
Exception • CompletionException
Fo
List the enhancements that are made in the java.util.concurrent package. Describe the
function of each interface and exception.
Several enhancements have been added in the java.util.concurrent package.
CompletableFuture.AsynchronousCompletionTask interface acts as a marker
interface to identify asynchronous tasks that async methods generate.
CompletionStage<T> interface represents a stage in an asynchronous computation
process.
A CompletionException is thrown when an error or other exception is encountered in
the course of completing a result or task.
© Aptech Limited
Slides 6 and 7
Let us understand about CompletableFuture Class.
CompletableFuture Class [1-2]
y
◆ The methods of the CompletableFuture
nl
class run asynchronously without stopping
the program execution.
O
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 6
se
CompletableFuture Class [2-2]
supplyAsync()
rU
Methods of the CompletableFuture Class
Method Description
Accepts a Supplier object that contains code to be
te
executed asynchronously
thenApply() Returns a new CompletableFuture object that is
executed with the result of the completed stage, provided
en
Explain about the CompletableFuture Class using the slide. Also, explain about the methods
pt
© Aptech Limited
Slides 8 and 9
Let us understand about CountedCompletor Class.
CountedCompletor Class [1-8]
y
nl
The compute() method
performs the main
computation and
invokes the
tryComplete() method.
O
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 8
se
CountedCompletor Class [2-8]
methods:
Method
onCompletion(CountedCompleter)
rU Description
To perform some action
te
upon normal completion.
onExceptionalCompletion(Throwable, To perform some action
CountedCompleter)
when an exception is thrown.
en
C
h
ec
Explain about the CountedCompletor Class using the slide. Also, explain that the method
CountedCompletor class may override using the slide.
pt
rA
Fo
© Aptech Limited
Slide 10
Let us understand about CountedCompletor Class when it is declared void.
CountedCompletor Class [3-8]
y
nl
O
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 10
se
Explain about the CountedCompletor class when it is declared as void.
Slides 11 to 14
rU
Let us understand about code of CountedCompletor Class.
CountedCompletor Class [4-8]
te
◆ The code demonstrates the implementation of the
en
CountedCompleter class.
Code Snippet
package com.training.demo.countedcompletor;
C
import java.util.ArrayList;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountedCompleter;
import java.util.concurrent.ExecutionException;
h
import java.util.concurrent.ForkJoinPool;
ec
© Aptech Limited
CountedCompletor Class [5-8]
NumberComputator(ConcurrentLinkedQueue<String>
concurrentLinkedQueue, int start, int end) {
this(concurrentLinkedQueue, start, end, null);
}
NumberComputator(ConcurrentLinkedQueue<String>
concurrentLinkedQueue, int start, int end,
NumberComputator parent) {
super(parent);
this.concurrentLinkedQueue = concurrentLinkedQueue;
this.start = start;
this.end = end;
}
@Override
public void compute() {
if (end - start < 5) {
y
String s = Thread.currentThread().getName();
for (int i = start; i < end; i++) {
concurrentLinkedQueue.add(String.format("Iteration
nl
number: {%d} performed by thread {%s}", i, s));
O
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 12
se
}
propagateCompletion();
} else {
rU
int mid = (end + start) / 2;
NumberComputator subTaskA = new
NumberComputator(concurrentLinkedQueue, start,
mid, this);
NumberComputator subTaskB = new
te
NumberComputator(concurrentLinkedQueue, mid, end,
this);
setPendingCount(1);
en
subTaskA.fork();
subTaskB.compute();
}
}
}
C
ConcurrentLinkedQueue<>();
NumberComputator numberComputator = new
ForkJoinPool.commonPool().invoke(numberComputator);
rA
Explain about the CountedCompletor and its implementation class. The code creates a
CountedCompletorDemo class with a static inner NumberComputator class.
© Aptech Limited
NumberComputator class has two overloaded constructors. First constructor accepts
following parameters: a ConcurrentLinkedQueue and the start and end index to perform
iterations.
First overloaded constructor, in turn, calls the second one that has an additional parameter.
If block in the overridden compute() method loops through the start and end index if their
difference is less than five and finally calls propagateCompletion() to mark that the current
task as complete.
Otherwise, two NumberComputator sub tasks are created.setPendingCount() method with
the argument 1 indicates that only the subTaskA sub-task is forked.
The compute() method called on subTaskB makes subTaskB execute synchronously. Then,
the main() method invokes an initialized NumberComputator using a ForkJoinPool and
y
outputs the result to console.
nl
O
Slide 15
Let us understand the output of CountedCompletor Class.
se
CountedCompletor Class [8-8]
rU
te
en
C
h
Explain about the output of the code that uses CountedCompletor the class.
pt
rA
Fo
© Aptech Limited
Slide 16
Let us understand about ConcurrentHashMap Class.
ConcurrentHashMap.KeySetView Class [1-3]
◆ Implements the Set interface and thus, can access the keys as a
Set object
y
nl
O
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 16
se
Explain about ConcurrentHashMap.KeySetView Class. ConcurrentHashMap.KeySetView class
provides a preview of the keys contained in the class. This class implements the Set
interface, which enables you to access the keys as a Set object. The Set object and the
rU
ConcurrentHashMap object have a bi-directional relationship. This means that when
you update the Set object the ConcurrentHashMap class also gets updated and vice-versa.
te
Also, it is not possible to directly create a ConcurrentHashMap.KeySetView instance. It is
created only when you call keySet(), keySet(V), newKeySet(), and newKeySet(int) on a Map
en
Slide 17
Let us understand ConcurrentHashMap Class using code.
h
Code Snippet
package com.training.demo.kesysetview;
import java.util.Iterator;
rA
import java.util.Map;
import java.util.Set;
import
java.util.concurrent.ConcurrentHashMap;
Explain about the method to access the keys in the ConcurrentHashMap as a Set.Code
creates a Map and initializes it with key value pairs. The call to keySet() uses
ConcurrentHashMap.KeySetView to return a Set of keys. The keys are printed as an output
of the code.
© Aptech Limited
Slide 18
Let us understand about ConcurrentHashMap class output.
ConcurrentHashMap.KeySetView Class [3-3]
y
nl
O
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 18
se
Explain about the output of the code.
Slide 19
rU
Let us understand about Atomic Operations and Locks.
Atomic Operations and Locks [1-15]
te
New classes in the java.util.concurrent.atomic package
en
Explain one of the biggest challenges in Java is to maintain scalability that is simultaneously
updated through multiple threads. This is addresses with the help of new classes that are
Fo
© Aptech Limited
Slides 20 to 22
Let us understand about LongAdder and DoubleAdder.
Atomic Operations and Locks [2-15]
package com.training.demo.atomicoperation;
import java.util.concurrent.atomic.DoubleAdder;
import java.util.concurrent.atomic.LongAdder;
public class AtomicOperationClassDemo {
private final LongAdder longAdder;
private final DoubleAdder doubleAdder;
y
public AtomicOperationClassDemo(LongAdder
nl
longAdder, DoubleAdder doubleAdder)
{
O
this.longAdder = longAdder;
this.doubleAdder = doubleAdder;
}
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 20
se
Atomic Operations and Locks [3-15]
} rU
public void incrementLong() {
longAdder.increment();
}
public double getSumAsDouble() {
return doubleAdder.doubleValue();
}
C
DoubleAdder());
ec
System.out.println("-----Long Counter-----");
for (int i = 0; i < 10; i++) {
atomicOperationClassDemo1.incrementLong();
System.out.println("Long Counter " +
atomicOperationClassDemo1.getLongCounter());
Fo
}
System.out.println("-----Double Sum-----");
for (int j = 0; j < 10; j++) {
atomicOperationClassDemo1.addDouble(j);
System.out.println("Double Sum " +
atomicOperationClassDemo1.getSumAsDouble());
}
}
}
© Aptech Limited
Explain about the code that uses the LongAdder and DoubleAdder atomic operation
classes. The code initializes a LongAdder and a DoubleAdder in the constructor. The
incrementLong() method increments the current LongAdder value by 1 through a call to
LongAdder.increment(). The getLongCounter() method returns the current LongAdder value.
The addDouble() method adds the double value passed to it to the current value of
DoubleAdder through a call to DoubleAdder. add(). The getSumAsDouble() method returns
the current DoubleAdder value.
Then, the main() method instantiates AtomicOperationClassDemo with the LongAdder and
DoubleAdder objects. The first loop calls the incrementLong() method followed by the
getLongCounter() method. The second loop calls the addDouble() method followed by the
y
getSumAsDouble() method. The code also prints the result out to the console from both the
nl
for loops.
O
Slide 23
Let us understand about the output of LongAdder and DoubleAdder classes.
se
Atomic Operations and Locks [5-15]
rU
Following is the output of the code:
te
en
C
h
ec
Explain about the output of the code that uses the LongAdder and DoubleAdder
atomic operation classes.
pt
rA
Fo
© Aptech Limited
Slide 24
Let us understand about StampedLock class.
Atomic Operations and Locks [6-15]
y
nl
◆ The lock supports a new lock mode known as optimistic locking.
O
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 24
se
Explain that prior to Java 8, the most common way to implement locks was with the help of
ReadWriteLock. However, using ReadWriteLock had several shortcomings, such as starvation
rU
and lack of support for optimistic reads. All the shortcomings of ReadWriteLock is now
addressed using the StampledLock class. Also explain about the Stampled locked class using
the slide.
te
en
Slides 25 to 27
Let us understand about modes of StampedLock Class.
C
tryWriteLock() method.
• When a thread is locked in write mode
then no read locks can be obtained.
Fo
© Aptech Limited
Atomic Operations and Locks [8-15]
y
nl
O
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 26
se
Implements lock with three modes for read/write access
Slides 28 to 32
pt
package com.training.demo.stampedlock;
import java.util.concurrent.locks.StampedLock;
© Aptech Limited
Atomic Operations and Locks [11-15]
try {
balance += amount;
System.out.println("Available balance: "+balance);
} finally {
stampedLock.unlockWrite(stamp);
System.out.println("Unlocked write lock");
}
}
public void withdraw(double amount) {
System.out.println("\nAbout to withdraw $: "+amount);
long stamp = stampedLock.writeLock();
System.out.println("Applied write lock");
try {
balance -= amount;
System.out.println("Available balance: "+balance);
y
} finally {
stampedLock.unlockWrite(stamp);
nl
System.out.println("Unlocked write lock");
}
}
O
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 29
se
public double checkBalance() {
System.out.println("\nAbout to check balance");
long stamp = stampedLock.readLock();
rU
System.out.println("Applied read lock");
try {
System.out.println("Available balance: "+balance);
return balance;
} finally {
te
stampedLock.unlockRead(stamp);
System.out.println("Unlocked read lock");
}
}
en
read lock");
double balance = this.balance;
h
if (!stampedLock.validate(stamp)) {
pt
balance = this.balance;
} finally {
stampedLock.unlockRead(stamp);
System.out.println("Unlocked read lock");
}
Fo
}
System.out.println("Available balance: "+balance);
return balance;
}
© Aptech Limited
Atomic Operations and Locks [14-15]
y
nl
O
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 32
Explain about the code that uses the StampedLock class in reading, writing, and
se
optimistic reading mode. The deposit() method in the code acquires a write lock through a
call to stampedLock.writeLock() before updating the balance field. The finally block inside
the deposit() method releases the lock. The withdraw () method also acquires a write lock
rU
through a call to stampedLock.writeLock() before updating the balance field, and releases
the lock in the finally block. Then, the checkBalance() method acquires a read lock through a
call to stampedLock.readLock() to read the balance and releases the lock in the final block.
te
Next, the checkBalanceOptimisticRead() method acquires an optimistic read method
en
After obtaining the current balance, the code checks whether or not the stamp is still valid
through a call to the StampedLock.validate(). If the stamp is valid, the current balance is
h
returned. Else, a full read lock is acquired before reading the balance again. The finally block
releases the lock with a call to stampedLock.unlockRead().
ec
The main() method creates a StampedLockDemo object initialized with a long amount.
pt
© Aptech Limited
Slide 33
Let us understand the output of StampedLock Class.
Atomic Operations and Locks [15-15]
y
nl
O
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 33
se
Explain about the output of the code that uses of the StampedLock class in reading,
writing, and optimistic reading mode.
Slide 34 rU
Let us understand the features of Fork-Join Framework.
te
More Features of the Fork-Join Framework
en
Stream
ForkJoinPool
Parallelization
Features
h
ec
Explain about the new features that are added in the Fork-Join Framework. Some additional
Fo
features of the Fork-Join framework include the new features added to the ForkJoinPool
class in Java 8. They are New ForkJoinPool Features, Stream Parallelization, Array Sorting
Parallelism, and Recursive Action.
© Aptech Limited
Slide 35
Let us understand about ForkJoinPool Feature.
New ForkJoinPool Features
y
nl
getCommonPoolParallelism(): A new
method that returns the targeted parallelism
level of the common thread pool.
O
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 35
se
Explain about the New ForkJoinPool Features and methods using the slide.
Slides 36 and 37
Let us understand about Stream Parallelization.
Stream Parallelization [1-2]
rU
te
◆ The code demonstrates the use of parallel stream to iterate
en
package com.training.demo.parallelstream;
C
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
items.add("one");
items.add("two");
items.add("three");
items.add("four");
Stream parallelStream = items.parallelStream();
pt
parallelStream.forEach(System.out::println);
}
}
rA
© Aptech Limited
Stream Parallelization [2-2]
y
nl
O
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 37
Explain that Java 8 introduces the new Stream API that operates on collections and arrays to
se
produce pipelined data that can be used to perform operations, such as filter, sort, and
iterate through data. To process larger streams, traditional multi-thread programing
rU
approaches are taken. However, streams are not thread-safe. Therefore, to address such
limitations Java 8 supports parallel computation of streams.
Also, explain about the code that uses parallel stream to iterate through the elements of an
ArrayList.
te
en
The code creates a List and initializes it with string elements. The parallelStream() method
returns a parallel stream object of type Stream. The foreach() loop iterates through the
parallel stream and prints out the elements. Also, explain about the output code that uses
C
Slides 38 and 39
Let us understand about Arrays Sort Parallelism.
ec
package com.training.demo.parallelarraysort;
import java.util.Arrays;
© Aptech Limited
Arrays Sort Parallelism [2-2]
y
nl
O
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 39
Explain that Java 8 introduces a new parallelSort() method in the Arrays class that allows
se
parallel sorting of array elements.
The code creates an int array of size 100 and fills it with random numbers starting for 0 to
100. The Arrays.parallelSort() method sorts the array in parallel before the code prints the
rU
array elements to the console. Also explain about the output of code.
Slide 40
te
Let us understand about Recursive Action.
en
processes:
ec
RecursiveTask
returns a result
pt
RecursiveAction
when executed
does not return a
result when executed
rA
© Aptech Limited
Slides 41 to 44
Let us understand about Fork-Join with Recursive Action.
Recursive Action [2-5]
package com.training.demo.recursiveaction;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
y
public class RecursiveActionDemo extends RecursiveAction {
private long assignedWork = 0;
nl
public RecursiveActionDemo(long assignedWork) {
this.assignedWork = assignedWork;
}
private List<RecursiveActionDemo> createSubtasks() {
O
List<RecursiveActionDemo> subtaskList = new
ArrayList<>();
se
Recursive Action [3-5]
rU
RecursiveActionDemo subtask1 = new
RecursiveActionDemo(this.assignedWork / 2);
RecursiveActionDemo subtask2 = new
RecursiveActionDemo(this.assignedWork / 2);
subtaskList.add(subtask1);
te
subtaskList.add(subtask2);
return subtaskList;
}
@Override
en
this.assignedWork);
List<RecursiveActionDemo> subtaskList = new
ArrayList<>();
subtaskList.addAll(createSubtasks());
h
}
} else {
System.out.println("Main thread " +
Thread.currentThread() + " computing: : " +
this.assignedWork);
}
Fo
}
public static void main(String[] args) {
RecursiveActionDemo recursiveActionDemo = new
RecursiveActionDemo(500);
final ForkJoinPool forkJoinPool = new
ForkJoinPool(4);
forkJoinPool.invoke(recursiveActionDemo);
}
}
© Aptech Limited
Recursive Action [5-5]
y
nl
O
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 44
Explain about the code that uses the Fork-Join functionality with RecursiveAction.
Constructor contains code to create a RecursiveActionDemo initialized with the
se
assignedWork long value passed to it when the constructor is invoked. The createSubtasks()
method creates two subtasks and returns them as a List object to the caller.
rU
The overridden compute() method calls the createSubtasks() method if the assignedWork is
above 50 and then calls the fork() method of the subtasks to distribute work. If the
te
workLoad is below 50, then the work is carried out by RecursiveActionDemo itself. The
main() method creates a RecursiveActionDemo initialized with the value 500 and calls the
en
Slides 45 and 46
h
Summary [1-2]
© Aptech Limited
Summary [2-2]
◆ RecursiveTask, similar to
RecursiveAction extends ForkJoinTask
to represent tasks that run within a
y
ForkJoinPool.
nl
O
© Aptech Ltd. Advanced Concurrency and Parallelism/Session 13 46
Using this slide, summarize the key points of this session. Explain the following points in
se
brief:
The CompletableFuture class simplifies coordination of asynchronous operations.
rU
The CountedCompletor class represents a completion action performed when
triggered, provided there are no remaining pending actions.
The LongAccumulator, LongAdder, DoubleAccumulator, and DoubleAdder classes
te
provide better throughput improvements as compared to Atomic variables.
The StampedLock class implements lock to control read/write access.
en
Parallel computation of streams enables working with streams faster without the risk
of threading issues.
The new parallelSort() method in the Arrays class allows parallel sorting of array
C
elements.
RecursiveTask, similar to RecursiveAction extends ForkJoinTask to represent tasks
h
You should familiarize yourself with the topics of the next session.
rA
Fo
© Aptech Limited
Session 14: Java Class Design and
Advanced Class Design
14.1 Pre-Class Activities
Before you commence the session, you should familiarize yourself with the topics of this
session in-depth. Prepare a question or two that will be a key point to relate the current
session objectives.
y
14.1.1 Objectives
nl
By the end of this session, learners will be able to:
O
Explain Java access modifiers
se
Explain advanced OOP concepts in Java
Describe packages
Define abstract class
rU
Explain the use of static and final keywords
Identify different types of inner classes
Explain advanced types
te
14.1.2 Teaching Skills
en
To teach this session, you should be well versed with the concepts of Java Programming.
C
You should be familiar with the difference between Professional Programming in Java. You
should also know the advantages and disadvantages of Java.
h
You should teach the concepts in the theory class using the images provided. For teaching in
ec
the class, you are expected to use slides and LCD projectors.
pt
Tips:
It is recommended that you test the understanding of the students by asking questions in
rA
In-Class Activities
Fo
© Aptech Limited
Slide 2
Objectives
◆ Describe packages
keywords
◆ Identify different types of inner classes
y
◆ Explain advanced types
nl
O
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 2
se
14.2 In-Class Explanations
Slide 3
Let us understand the concept of Access Control.
rU
te
Access Control
en
Access Modifiers
h
ec
Explain that access control determines how a class and its member variables and methods
Fo
are accessible and used by other classes and objects. Java provides access modifiers to
control access at two levels, the class level and the member level. The class level applies to
the class. The member level applies to the member variables and methods of the class.
© Aptech Limited
Slide 4
Let us understand the concept of Access Modifiers.
public
• Can be applied to classes, member variables, and methods.
• Accessible from within the same class.
• Is applied using the public keyword.
protected
• Can be applied to member variables and methods.
y
• Accessible only to the class in which they are declared and its subclasses.
• Is applied using the protected keyword.
nl
private
• Can be applied to member variables and methods.
O
• Accessible only to the class in which they are declared.
• Is applied using the private keyword.
se
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 4
Explain that an access modifier controls the access of class members and variables by other
objects. Various access modifiers in Java are :
rU
• public: This can be applied to classes, member variables, and methods. Public variables
and methods are accessible from within the same class, the same package in which the
te
class is created, and also from a different package. This modifier is applied using the
public keyword.
• protected: This can be applied to member variables and methods. Protected variables and
en
methods are accessible only to the class in which they are declared and its subclasses.
This modifier is applied using the protected keyword.
C
• private: This can be applied to member variables and methods. Private member variables
and methods are accessible only to the class in which they are declared. This modifier is
h
Tell the students that other than these modifiers, there is friendly or package access, which
is automatically applied to classes, member variables, and methods when no other access
rA
modifiers are specified. This modifier does not have any keyword. A class, variable, or
method with friendly or package access is accessible only to the classes and other classes
within the same package.
Fo
© Aptech Limited
Slide 5
Let us understand the access levels of access modifiers.
Access Modifiers [2-2]
y
friendly or package Yes Yes No No
nl
private Yes No No No
O
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 5
se
Explain the table given on the slide that shows the access levels of different access
modifiers.
Slide 6
Let us understand access control best practices.
rU
te
Access Control Best Practices
en
Explain that the best practices to be followed when applying access control to Java classes,
Fo
© Aptech Limited
Slide 7
Let us understand Advanced OOP Concepts in Java.
Advanced OOP Concepts in Java
Java
Object-oriented Designers need to be
programming language well-versed with OOP concepts
y
nl
OOP
A programming approach
O
A software development involving object collections
methodology and their inter-relationships
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 7
se
Explain that Java is an object-oriented programming language. In order to design Java classes
and interfaces in a better manner, a developer needs to be well-versed with OOP concepts.
rU
OOP is a software development methodology based on modeling a real-world system. An
object is the core concept involved in OOP. It is the representation of a real world entity.
OOP can be considered as a programming approach involving object collections and their
te
inter-relationships.
en
Slide 8
Let us understand the Multi-level Inheritance.
C
inherited.
ec
Inheritance Subclass
pt
Explain that inheritance enables a class to inherit members of a class such as its variables
and methods. Inheritance supports reusability of an existing class in a new class. Besides
inheriting variables and classes from a super class, a subclass can additionally add new
features to it. A subclass inherits from a superclass using the extends keyword. A Java class
can extend from only one superclass. However, a class can extend from multiple interfaces.
Java supports multi-level inheritance. One class can inherit from a parent class, which itself
inherits from another parent class. Such inheritance hierarchy can extend to any level.
© Aptech Limited
However, irrespective of the level in a multi-level inheritance, the Object class always
remains on the top of the hierarchy.
Slide 9
Let us understand Multi-level Inheritance with the help of code.
Multi-level Inheritance [2-4]
package com.classdesign.demo;
public class Movie {
y
String language="English";
String type="Full length movie";
nl
void getMovie() {
System.out.println("Language "+ language);
System.out.println("Type: "+ type);
O
}
}
se
© Aptech Ltd.
Explain that the class creates two variables and a getMovie() method to print the
variable values. The class extends from Movie, declares three variables, and defines a
9
te
getActionMovie() method that prints the variables.
en
Slide 10
Let us understand about the ActionMovie class.
C
Code Snippet
package com.classdesign.demo;
void getActionMovie() {
System.out.println("Genre: "+ genre);
System.out.println("Title: " + title);
System.out.println("Duration: " + duration);
}
}
Fo
Explain about ActionMovie class that extends Movie forming an inheritance hierarchy
using slide 10.
© Aptech Limited
Slide 11
Let us understand the output of Multi-level Inheritance classes.
Multi-level Inheritance [4-4]
y
nl
O
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 11
se
Display the output of Multi-level inheritance code using slide 11.
Slide 12
rU
Let us understand the concept of Method Overloading.
Method Overloading [1-4]
te
In object-oriented programming, every method has a
en
The number
of The data The order in
parameters types of which the
h
Explain that in object-oriented programming, every method has a signature. This comprises
the number of parameters passed to the method, the data types of parameters, and the
order in which the parameters are written. While declaring a method, the signature of the
method is written in parentheses next to the method name. No class is allowed to contain
two methods with the same name and signature. However, it is possible for a class to have
two methods having the same name but different signatures. The concept of declaring more
than one method with the same method name, but different signatures is called method
overloading. In method overloading where multiple methods exist with the same name but
different method signatures, a call to the correct method is resolved at compile time
through static polymorphism.
© Aptech Limited
Slide 13
Let us understand about Method Overloading using code.
Method Overloading [2-4]
package com.classdesign.demo;
public class MethodOverloadingDemo {
static int add(int intNum1, int Num2) {
return intNum1 + Num2;
}
static float add(float floatNum1, float floatNum2) {
y
return floatNum1 + floatNum2;
}
nl
public static void main(String[] args) {
System.out.println("Sum of int value: " + add(5, 15));
System.out.println("Sum of float value: " + add(5.95f,
15.30f));
O
}
}
se
Explain about the add() method to calculate the square of the int and float values
passed as parameters using slide 13. Explain that the code creates two methods with the
rU
same name, but with different parameters declared in the class. The two add() methods
take in two parameters of int and float types respectively. Within the main()
method, depending on the type of value passed, the appropriate method is invoked through
te
static polymorphism. The sum of the specified numbers is then printed to the console.
en
Slide 14
Let us understand about output of Method Overloading.
C
Explain the output of the code. Explain how add() was overloaded using slide 14.
© Aptech Limited
Slide 15
Let us understand about Method Overloading using built-in abs() method.
Method Overloading [4-4]
Has several
overloaded versions
Returns the absolute Java determines the
such as abs(int
value of the numeric correct overloaded
y
num), abs(float
parameter passed to abs() method to
num), and
it. invoke.
abs(double
nl
num).
O
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 15
se
Explain an example of method overloading used in Java libraries using slide 15.
Explain that Method overloading is also used extensively in the Java API. One example is the
rU
built-in abs() method of the Math class present in the java.lang package. This
method returns the absolute value of the numeric parameter passed to it. There are several
overloaded versions of the abs() method, such as abs(int num), abs(float
te
num), and abs(double num). Based on the parameter passed to the abs() method
at runtime, Java determines the correct overloaded abs() method to invoke.
en
Slide 16
Let us understand about Method Overriding.
C
Explain and define method overriding using slide 16. In an inheritance hierarchy, a subclass
can override the methods of the superclass. This feature, known as method overriding, is
defined as creating a method in the subclass that has the same return type and signature as
a method defined in the superclass. Method overriding is a form of dynamic polymorphism
because the decision to call a particular implementation over other implementations is
dynamically taken at runtime. The call decision is taken dynamically at runtime based on the
object from which the operation is called.
© Aptech Limited
Slides 17 and 18
Let us understand Method Overriding with the help of code.
Method Overriding [2-4]
package com.classdesign.demo;
class Animal {
void getMessage() {
System.out.println("Message from Animal.");
}
}
y
class Dog extends Animal {
@Override
nl
void getMessage() {
System.out.println("Bow-wow! Message from Dog.");
}
}
O
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 17
se
Method Overriding [3-4]
}
rU
System.out.println("Meow! Message from Cat.");
te
}
public class MethodOverridingDemo {
public static void main(String[] args) {
Animal animal1 = new Dog();
en
}
h
ec
Explain about the dynamic polymorphism using slide 17. The code creates an inheritance
pt
hierarchy with Animal as the base class containing the getMessage() method. Two
classes, Dog and Cat, inherit Animal and override the getMessage() method to
rA
assigns them to the Animal types, animal1 and animal2. Polymorphism ensures that
calls to getMessage() on the animal types are dispatched at runtime to the actual
instances.
© Aptech Limited
Slide 19
Let us understand the output of Method Overriding.
Method Overriding [4-4]
y
nl
O
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 19
se
Explain the output of the code. Explain how getMessage() method was overridden using
slide 19.
Slide 20 rU
Let us understand the syntax of super () constructor and super keyword.
te
super() Constructor Call and super Keyword
[1-4]
en
super();
Or
super(parameter list);
h
Note: super() call must be the first statement inside the constructor
ec
Syntax
super.<method_name>;
rA
Explain the two syntax shown on the slide. First, discuss the super() constructor call then
Fo
discuss the super keyword using slide 20. Here, you see two set of syntax. The first discusses
the super() constructor call whereas the second one about the super keyword. In the first
set, super() calls the superclass no-argument constructor and super(parameter_
list) calls the superclass constructor with a matching parameter list that
parameter_list in the syntax represents.
Explain that in the second syntax, method_name is the overridden method name of the super
class and the super keyword is used.
© Aptech Limited
Slides 21 and 22
Let us understand about method overriding to implement dynamic polymorphism.
super() Constructor Call and super Keyword
[2-4]
◆ The code shows the use of the super() constructor call and
the super keyword.
Code Snippet
package com.classdesign.demo;
class SuperClass {
public SuperClass() {
System.out.println("Message from SuperClass default
constructor.");
}
y
void print() {
System.out.println("Message from SuperClass print().");
nl
}
}
public class SuperCallDemo extends SuperClass {
public SuperCallDemo() {
O
super();
se
super() Constructor Call and super Keyword
[3-4]
}
constructor.");
@Override
rU
System.out.println("Message from SuperCallDemo default
te
void print() {
System.out.println("Message from SuperCallDemo print().");
super.print();
}
en
}
h
ec
Explain about method overriding to implement dynamic polymorphism. Explain that the
pt
code creates a SuperClass class with a default constructor and a print() method.
The SuperCallDemo class extends SuperClass in order to inherit from it. The
rA
© Aptech Limited
Slide 23
Let us understand about output of super() constructor call and super keyword.
super() Constructor Call and super Keyword
[4-4]
y
nl
O
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 23
se
Explain the output shown on slide 23.
Slide 24
rU
Let us understand about Package and Import Statements.
Package and Import Statements [1-2]
te
SYDNEY?
en
OR
C
h
ec
Explain about conflicts that can be caused by identical class names using slide 24.
Consider Sydney, which is a city in Australia as well as in Canada. You can easily distinguish
Fo
between the two cities by associating them with their respective countries. Similarly, when
working on a huge project, there may be situations where classes have identical names. This
may result in name conflicts. This problem can be solved by having the classes in different
packages. By doing this, classes can have identical names without any resultant name
clashes.
In Java, a package is used to group classes and interfaces logically and prevent name clashes
between those with identical names. Packages reduce any complexities when the same
program is required in another application.
© Aptech Limited
Slide 25
Let us understand about different Java Packages.
Package and Import Statements [2-2]
y
• Bundles the classes to implement networking
nl
java.net
applications.
O
java.time • Bundles the classes to work with date and time.
se
Explain about packages using slide 25. Although it is not mandatory to use packages for the
Java classes or interfaces of an application, it is highly recommended to arrange classes and
rU
interfaces in packages to avoid naming conflicts as the application grows.
All the built-in Java classes and interfaces, based on their functionalities, are bundled into
packages.
te
Some of these packages are as follows:
• java.lang: Bundles the classes that are fundamental to the design of the Java
en
programming language.
• java.io: Bundles the classes to perform input output operations.
• java.collections: Bundles the classes and interfaces that are part of the Java collection
C
framework.
• java.net: Bundles the classes to implement networking applications.
h
Slide 26
Let us understand the rules to declare package.
pt
© Aptech Limited
Explain the package keyword using slide 26. A package is declared with the package
keyword. A package declaration must be the first statement in a Java class. Rules to declare a
package are as follows: A package must be declared with class outside its namespace can be
accessed by specifying its namespace followed by the dot operator and the class name.
The name of the package must match the directory structure where the corresponding
bytecode resides.
Slide 27
Let us understand the keyword package.
package Keyword [2-5]
y
◆ The code shows the use of a user-defined package for a Java
nl
class.
Code Snippet
O
package com.classdesign.demoA;
public class ClassA {
public void getMessage(){
se
System.out.println("Message from ClassA in
com.classdesign.demoA package ");
}
}
rU
te
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 27
en
Explain about the use of a user-defined package for a Java class using slide 27. The code
declares a package using a hierarchical naming structure where each part of the hierarchy is
separated by the dot operator. The hierarchical naming structure can be related with the
C
Slide 28
ec
◆ The code shows a Java class with the same name as the class in
rA
package com.classdesign.demoB;
public class ClassA {
Fo
Explain about a Java class with the same name as the class in the earlier code snippet, but in
a different package using slide 28.
© Aptech Limited
Slide 29
Let us understand the code of Java class using different packages.
package Keyword [4-5]
◆ The code shows a Java class using the two ClassA classes that
are part of different packages.
Code Snippet
package com.classdesign.demo;
public class PackageDemo {
public static void main(String[] args) {
com.classdesign.demoA.ClassA obj1 = new
com.classdesign.demoA.ClassA();
com.classdesign.demoB.ClassA obj2 = new
y
com.classdesign.demoB.ClassA();
obj1.getMessage();
nl
obj2.getMessage();
}
}
O
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 29
se
Explain about a Java class using the two ClassA classes that are part of different packages
using slide 29. The code uses the full qualified name, which is the class name along with the
rU
package name, to instantiate both the ClassA classes and calls their doMessage()
methods.
te
Slide 30
Let us understand the output of code for package keyword.
en
© Aptech Limited
Slide 31
Let us understand the importing types and packages.
Importing Types and Packages [1-3]
y
To avoid typing the fully qualified name each time a class
nl
needs to be used, Java enables single-type import.
O
you can use the class with only the class name.
se
Explain about single-type import using slide 31. It is not convenient to type the fully qualified
name each time a class needs to be used. To overcome this issue, Java enables importing a
rU
class once and thereafter, you can use the class with only the class name. This feature is
called a single-type import.
te
Slide 32
Let us understand the code of importing ClassA.
en
package com.classdesign.demo;
import com.classdesign.demoA.ClassA;
ec
}
rA
Note: Java does not allow importing classes with the same name in
different packages through single type import.
Fo
© Aptech Limited
Slide 33
Let us understand the code importing entire package.
Importing Types and Packages [3-3]
package com.classdesign.demo;
import com.classdesign.demoA.*;
public class PackageDemo {
public static void main(String[] args) {
ClassA obj1 = new ClassA();
y
obj1.getMessage();
}
nl
}
O
the compiler does it by default for all classes.
se
Explain about importing the entire com.classdesign.demoA package and using the
ClassA class of that package using slide 33. Similar to single-type importing, Java does not
rU
allow importing two complete packages with the wildcard (*) symbol if they have classes
with the same name. In such situations, you need to use the fully qualified name.
te
Slide 34
Let us understand about Abstract Class.
en
abstract keyword.
Explain about abstract class using slide 34. Java allows designing a class specifically to be
used only as a base class by declaring it an abstract class. Such class can be referred to as an
incomplete base class, as it cannot be instantiated, but it can only be sub-classed.
An abstract class contains one or more methods declared with the abstract keyword. An
abstract method does not contain implementation. An abstract class is used to declare
classes that only define common properties and behavior of other classes.
© Aptech Limited
Slides 35 and 36
Let us understand the code to create an Abstract class.
Abstract Class [2-3]
package com.classdesign.demo;
abstract class TestAbstract {
abstract void getMessage();
}
public class AbstractClassDemo extends TestAbstract {
void getMessage() {
System.out.println("Message from abstract
class.");
y
}
public static void main(String[] args) {
nl
TestAbstract abstractClass = new
AbstractClassDemo();
abstractClass.getMessage();
O
}
}
se
Abstract Class [3-3]
rU
Following is the output of the code:
te
en
C
h
ec
Explain about how to create and use an abstract class. The code creates an abstract class
pt
© Aptech Limited
Slide 37
Let us understand about static and final Keywords.
static and final Keywords
y
Member variables
Class
Method
nl
Variable
Code block
Method
Nested class
O
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 37
se
Explain anonymous inner class using slide 37. In Java, static and final are two important
keywords that are extensively used while writing Java code. The static keyword is primarily
• Member variables
• Method
rU
used for memory management and can be applied to the following:
te
• Code block
• Nested class
en
Explain the final keyword is used to restrict access in an inheritance hierarchy and can be
applied to:
C
• Class
• Variable
h
• Method
ec
Slide 38
Let us understand the concept of Static Variable.
pt
Static method
© Aptech Limited
Explain static method using slide 38. Explain that the static keyword can also be applied to
methods of a class. Such a method, known as static method, belongs to the class and not to
the any instance of the class. A static method can only access other static variables and call
other static methods. Also, a static method cannot refer to the this and super keywords.
Similar to static variables, a static method can be accessed directly by the class name.
Slide 39
Let us understand how to create and use static variable.
Static Variable [2-2]
y
Code Snippet
nl
package com.classdesign.demo;
public class StaticDemo {
O
static String message = "Hello! Message from static
variable";
public static void main(String[] args) {
String msg = StaticDemo.message;
se
}
}
rU
te
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 39
Explain about how to create and use an abstract class using slide 39. The code creates a
en
static variable of type String and accesses it from the main() method. Observe that no
new instance is created using the new keyword to access the static variable. The Java class
library has many classes with static fields. For example, the Math class defines PI as:
C
Slide 40
ec
Code Snippet
package com.classdesign.demo;
public class StaticDemo {
private static String message = "Hello! Message
from static variable";
Fo
© Aptech Limited
Explain about how to create and use a static method using slide 40. The code creates a
private static variable of type String and returns it from the static getMessage()
method. The main() method, which itself is a static method, calls the static
getMessage() method.
Slide 41
Let us understand about Static Blocks.
Static Blocks [1-3]
◆ A static block:
Is a normal block of code enclosed in curly braces {} and marked
y
◈
nl
◈ Can be multiple static blocks inside the class body.
O
◆ For multiple static blocks:
◈ The blocks are called in the order that they appear in the class
body.
se
◈ JVM executes the code of static blocks when it loads the class.
◈ JVM joins them into one single static block before executing it.
methods.
© Aptech Ltd.
rU
Code inside a static block can refer static variables and
Java Class Design and Advanced Class Design/Session 14 41
te
Explain static block using slide 41. A static block, also known as static initialization block, is a
normal block of code enclosed in curly braces {} and marked with the static keyword. There
en
can be multiple static blocks inside the class body. For multiple static blocks, the blocks are
called in the order that they appear in the class body. The JVM executes the code of static
blocks when it loads the class. When there are multiple static blocks, the JVM joins them
C
into one single static block before executing it. Code inside a static block can refer static
variables and methods.
h
ec
Slide 42
Let us understand the code to create and use static block.
pt
Code Snippet
package com.classdesign.demo;
public class StaticDemo {
private static String message = "Hello! Message from
Fo
static variable";
public static String getMessage(){
return StaticDemo.message;
}
public static void main(String[] args) {
String msg = StaticDemo.getMessage();
System.out.println("Called from main: "+msg);
}
static {
System.out.println("Hello! Message from static
block");
System.out.println("Called from static block: " +
StaticDemo.getMessage());
}
}}
© Aptech Limited
Explain about how to create and use static block using slide 42. The code creates a private
static variable of type String and returns it from the static getMessage() method.
The main() method, which itself is a static method, calls the static getMessage()
method. The static block at the end of the class prints out a message and the output
returned by a call to the getMessage() method.
Slide 43
Let us understand the output of code for static block.
Static Blocks [3-3]
y
Following is the output of the code:
nl
O
se
© Aptech Ltd.
rU Java Class Design and Advanced Class Design/Session 14 43
te
Explain about the output on executing the StaticDemo class using slide 43.
In the output, observe that the static block is executed ahead of the main() method.
en
Slide 44
C
Static variable
Language
enhancements
Static import
pt
Static import
rA
class name.
Explain language enhancements in Java and static import using slide 44. A language
enhancement introduced in Java 5 is static import. Prior to static imports, a static variable or
method was required to be accessed by prefixing the class name separated by a dot (.)
symbol. Starting from Java 5, static import allows importing static variables and methods of a
class and use them, as they are declared in the same class. Static imports can greatly reduce
code size by allowing to use static variables and methods of another class without prefixing
the class name.
© Aptech Limited
Slide 45
Let us understand code which shows the use of static import.
Static Imports [2-4]
package com.classdesign.demo;
import static java.lang.Integer.MAX_VALUE;
y
/*Accessing static member without static import*/
nl
System.out.println(Integer.MAX_VALUE);
}
}
O
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 45
se
Explain about the use of static import using slide 45. The code performs a static import of
the MAX_VALUE static variable of Integer. The main() method prints out the value of
MAX_VALUE both with and without static imports.
Slide 46
rU
te
Let us understand the output of code uses static imports.
Static Imports [3-4]
en
Explain about the output on executing the StaticImportDemo class using slide 46.
In the output, observe that the static block is executed ahead of the main() method.
© Aptech Limited
Slide 47
Let us understand the Integer and Long classes using MAX-VALUE.
Static Imports [4-4]
y
nl
O
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 47
se
Explain static imports using slide 47. Although static imports, reduce code size, many
programmers prefer using the traditional class name prefix instead of static imports for
rU
increased readability. For example, both the Integer and Long classes contain the static
MAX_VALUE variable. With static import, although it is possible to refer the variable directly
as MAX_VALUE instead of Integer. MAX_VALUE, it is unclear of which class the variable
te
belongs to. Therefore, it is recommended to use static imports only when frequent access to
static members from one or two classes are required.
en
Slide 48
Let us understand about the Final Class.
C
sub-classed.
benefits.
© Aptech Limited
Explain how classes are declared final using slide 48. In an inheritance hierarchy, a class can
be prevented from being sub classed by marking it with the final keyword. Such a class is
known as a final class. Typically, a class is declared as final to confer security and efficiency
benefits. Another reason to declare a class as final is to standardize the behavior of a class
by preventing it from being extended. This is because if a class is extended it can be made to
behave differently. Hence, to avoid this, a class can be declared final.
Several Java classes, such as the System and String classes of the java.lang package, are
declared as final.
Slide 49
Let us understand the syntax for declaring final classes.
y
Final Class [2-2]
nl
◆ The syntax for declaring a final class is as follows:
O
Syntax
se
◆ The code shows a final class.
Code Snippet
}
final class FinalClass{
rU
package com.classdesign.demo;
te
en
Explain about the syntax and code for declaring a final class using slide 49.
C
The code creates a final class. If any other class attempts to extend FinalCLass, the
compiler will report a "cannot inherit from final FinalClass" error.
h
ec
Slide 50
Let understand Variables and Methods.
pt
© Aptech Limited
Explain final variables and methods using slide 50. Similar to classes, variables and methods
can also be declared as final. A variable declared as final cannot be assigned a different
value. In Java, a constant that is used to map an exact and unchanging value to a variable
name is declared as final. A method declared as final cannot be overridden in a
subclass.
Slide 51
Let us understand the syntax for Final variables and Methods.
Final Variables and Methods [2-3]
y
Syntax
nl
<access_modifier> final <variable_name> = <value>;
O
◆ The syntax for declaring a final method is as follows:
Syntax
se
<access_modifier> final <return_type>
<method_name>(<parameter_optional>)
{}
rU
te
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 51
Explain the syntax to declare final variables and final methods using slide 51.
en
Slide 52
Let us understand the code for Final Variables and Methods.
C
Code Snippet
package com.classdesign.demo;
class FinalMemberDemo{
pt
}
Fo
Explain about the final variable and a final method using slide 52. The code creates a
initialCount final variable and a getMessage() final method. For an attempt to
assign a new value to initialCount, the compiler will report a "cannot assign a
value to final variable initialCount" error.
For an attempt to override the getMessage() method in a subclass, the compiler will
report a "cannot override getMessage() in FinalMemberDemo
overridden method is final" error.
© Aptech Limited
Slide 53
Let us understand about Inner Classes.
Inner Classes
y
nl
Local inner class
O
Static nested class
se
Explain inner class using slide 53. You can also define a class within another class or
interface. Such a class defined within the body of another class or interface is known as
are as follows:
• Member inner class
rU
inner or nested class. Java supports nesting of classes. The different types of inner classes
te
• Anonymous inner class
• Local inner class
en
Slide 54
C
Syntax
class
◆ The <outer_class>{
rA
Explain about the syntax for declaring a member inner class using slide 54. When you
compile a class containing an inner class, the compiler creates two class files. To instantiate
the inner class, the instance of the outer class is required. The outer class instance holds the
inner class instance.
© Aptech Limited
Slide 55
Let us understand the code which shows use of member inner class.
Member Inner Class [2-3]
package com.classdesign.demo;
public class Outer {
private String message="Hello from outer class.";
class Inner{
void getMessage(){
System.out.println(message);
System.out.println("Hello from inner class.");
y
}
}
public static void main(String[] args) {
nl
Outer outer = new Outer();
Inner inner = outer.new Inner();
inner.getMessage();
O
}
}
se
Explain about the use of a member inner class using slide 55. The code creates a top-level
class with a member inner class. Observe that the member inner class is accessing the
rU
private variable of the enclosing outer class. The main() method creates an outer class
instance and uses it to create an inner class instance. The getMessage() method is then
called on the inner class instance.
te
Slide 56
en
The code creates a top-level class with a member inner class. Observe that the
h
member inner class is accessing the private variable of the enclosing outer class.
The main() method creates an outer class instance and uses it to create an inner
ec
class instance. The getMessage() method is then called on the inner class
instance.
pt
Explain the code and discuss the output using slide 56.
© Aptech Limited
Slide 57
Let us understand Anonymous inner class.
Anonymous Inner Class [1-4]
y
nl
O
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 57
se
Explain anonymous inner class using slide 57. An inner class without a class name is known
as an anonymous inner class. An anonymous inner class is declared and instantiated at the
rU
same time. Inner classes are typically used to override the method of a concrete class,
abstract class, or interface.
te
Slide 58
Let us understand the syntax of an anonymous inner class.
en
Syntax
........
}
};
pt
rA
Fo
Explain about the syntax of an anonymous inner class using slide 58. In the syntax,
extended_name is the name of the parent class or interface whose method is overridden
by the inner class.
© Aptech Limited
Slide 59
Let us understand Anonymous Inner Class.
Anonymous Inner Class [3-4]
package com.classdesign.demo;
abstract class Greet {
abstract void getGreeting();
}
public class AnonymousInnerClass {
public static void main(String[] args) {
Greet g = new Greet()
y
{
void getGreeting() {
nl
System.out.println("Hello from anonymous
Inner class.");
}
};
O
g.getGreeting();
}}
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 59
se
Explain about the use of an anonymous inner class using slide 59. The code creates an
abstract Greet class with an abstract getGreeting() method. The main() method
rU
of the class, AnonymousInnerClass uses an anonymous inner class to instantiate a
Greet object by overriding the getGreeting() method. Finally, the
getGreeting() method is invoked on the Greet object named g.
te
Slide 60
en
Explain the code and discuss the output using slide 60.
© Aptech Limited
Slide 61
Let us understand about Local Inner Class.
Local Inner Class [1-4]
y
nl
O
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 61
se
Explain local inner class using slide 61. A class defined inside a method is known as a local
inner class. Similar to a local variables defined within a method, a local inner class is scoped
rU
within the method. Once the method exits, the local inner class instance stops to exist. Also,
a local inner class can be instantiated only from within the method where it is declared.
te
Slide 62
Let us understand about syntax of local inner class.
en
Syntax
class <local_inner_name>{
//Code
ec
}
}
pt
rA
Fo
Explain about the syntax of an local inner class using slide 62. In the syntax, method_name
is the method that contains the local inner class.
© Aptech Limited
Slide 63
Let us understand the code using Local Inner Class.
Local Inner Class [3-4]
class LocalInnerClassDemo{
void display(){
String msg="Hello";
class Local{
void getMessage(){
System.out.println("Message from local inner class: "+msg);
}
y
}
Local l = new Local();
nl
l.getMessage();
public static void main(String args[]){
LocalInnerClassDemo obj = new LocalInnerClassDemo();
obj.display();
O
}
}
se
Explain about the local inner class with its use using slide 63. In the syntax, method_name
is the method that contains the local inner class and how to use local inner class.
Slide 64 rU
Let us understand the output of code using Local Inner Class.
te
Local Inner Class [4-4]
en
The code creates a local inner class named Local inside the
display() method. The display() method instantiates the local
inner class and invokes the getMessage() method on it.
C
In the display() method, observe that the local inner class refers to
the msg local variable.
h
Explain the code and talk about the output of the local inner class using slide 64.
Fo
© Aptech Limited
Slide 65
Let us understand Static Inner Class.
Static Inner Class [1-4]
y
Created before an instance of the outer class.
nl
Accessed directly with the class name of the outer class.
O
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 65
se
Explain static inner class using slide 65. An inner class that is a static member of the outer
class is known as a static inner class. A static inner class is similar to a member inner class.
rU
The difference is that by being a static member of the outer class, a static inner class is
created before an instance of the outer class. Also, a static inner class can be accessed
directly with the class name of the outer class.
te
Slide 66
en
class <outer_class>{
ec
//code
static class <inner_class>{
//code
}
}
pt
rA
Fo
Explain the syntax for static inner class using slide 66.
© Aptech Limited
Slide 67
Let us understand the code for Static Inner Class.
Static Inner Class [3-4]
package com.classdesign.demo;
public class Outer {
static String msg="Hello";
static class StaticInner{
static void display(){
System.out.print("Message from static inner class:
"+msg+"\n");
}
y
}
public static void main(String[] args) {
nl
Outer.StaticInner.display();
}
}
O
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 67
se
Explain about the use of a static inner class using slide 67. The code creates a static inner
class named StaticInner within the Outer class. The StaticInner class contains a static
rU
display() method. The main() method calls the display() method of StaticInner without
creating any instance of both the Outer and StaticInner classes.
te
Slide 68
Let us understand the output of code using the static inner class.
en
Explain about the output of the static inner class using slide 68.
© Aptech Limited
Slide 69
Let us understand about Advanced Types.
Advanced Types
y
nl
O
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 69
se
Explain advanced types using slide 69. In addition to the regular types, such as top-level,
abstract, and inner classes, Java supports advanced types, such as the enum type and
immutable classes.
Slide 70
rU
te
Let us understand about the enum.
enum Type
en
Explain Java enum using slide 70. Java enum is a special type that defines a fixed set of
constants. Similar to a Java class, an enum can contain constructors, variables, and methods.
Internally, the compiler treats an enum as an advance type of class holding a set of
constants. While compiling an enum, the compiler automatically adds some special methods
to the enum. One such method is the static values() method. This method returns the values
of the enums in the order they are declared as an array and is useful to iterate over the
values of an enum. Also, the compiler generates subclasses for each entry present in the
enum. Therefore, an enum cannot be declared as final.
© Aptech Limited
Enum is defined using the enum keyword. All enums implicitly extends the Enum class.
Therefore, as Java does not support multi-inheritance, an enum cannot extend from another
class.
Constant values of an enum are typed in uppercase letters. In addition, these values are
implicitly static and final. Also, if an enum is used as a member of a class, it is implicitly
defined as static.
Slide 71
Let us understand about Immutable Class.
Immutable Classes [1-4]
y
• is a class whose object's state
nl
cannot be changed once
instantiated.
O
• is inherently thread safe.
An
se
immutable
• state cannot change once
class: instantiated.
Explain immutable class using slide 71. A class whose object’s state cannot be changed once
instantiated is called an immutable class. An immutable class is inherently thread safe. Their
state cannot change once instantiated. Therefore, when working with immutable objects in
C
Slide 72
Let us understand the steps for creating Immutable class.
pt
Mutable objects that the Steps for The class should not
instance fields refer to creating an contain setter methods to
should not change. modify fields or objects
immutable referred to by fields.
class
© Aptech Limited
Explain steps for creating an immutable class using slide 72. Some of the steps to consider
for creating an immutable class are as follows:
• The class should be declared final to disable method overriding. Alternatively, the class
constructor should be declared private and instances should be constructed through
factory methods.
• The class should not contain setter methods to modify fields or objects referred to by
fields.
• All fields should be declared private and final.
• Mutable objects that the instance fields refer to should not change.
Slide 73
y
Let us understand the code for Immutable Class.
nl
Immutable Classes [3-4]
O
◆ The code shows an immutable class.
Code Snippet
se
package com.classdesign.demo;
}
this.lName = lName;rU
public ImmutableClassDemo(final String fName, final String lName) {
this.fName = fName;
Explain the code given on slide 73. Using slide 74, Here, the code creates an immutable class
through the following design:
h
© Aptech Limited
Slide 74
Let us underderstand design for immutable class.
Immutable Classes [4-4]
are provided.
y
nl
O
© Aptech Ltd. Java Class Design and Advanced Class Design/Session 14 74
se
Slide 75
Let us summarize the session.
Summary
◆
rU
An access modifier controls the access of class members and
te
variables by other objects.
◆ Inheritance enables a class to inherit variables and methods from
en
another class.
◆ Polymorphism is the ability of different object types to respond
to the same message, each one in its own way.
C
Using this slide, summarize the key points of this session. Explain the following points in
rA
brief:
An access modifier controls the access of class members and variables by other
Fo
objects.
Inheritance enables a class to inherit variables and methods from another class.
Polymorphism is the ability of different object types to respond to the same
message, each one in its own way.
In Java, a package is used to group classes and interfaces logically and prevent name
clashes between those with identical names.
An abstract class contains one or more methods declared with the abstract keyword.
An inner class without a class name is known as an anonymous inner class.
© Aptech Limited
14.3 Post Class Activities for Faculty
You should familiarize yourself with the topics of the next session.
Tips: You can also check the Articles/Blogs/Expert Videos uploaded on the OnlineVarsity site
to gain additional information related to the topics covered in the next session.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
© Aptech Limited
Session 15: Effective Programming with
Lambda
15.1 Pre-Class Activities
Before you commence the session, you should familiarize yourself with the topics of this
session in-depth. Prepare a question or two that will be a key point to relate the current
session objectives.
y
15.1.1 Objectives
nl
By the end of this session, learners will be able to:
O
Explain lambdas
se
Identify the built-in functional interfaces
Explain code refactoring for readability using lambdas
Describe debugging of lambda
You should teach the concepts in the theory class using the images provided. For teaching in
the class, you are expected to use slides and LCD projectors.
h
Tips:
ec
It is recommended that you test the understanding of the students by asking questions in
between the class.
pt
In-Class Activities
rA
© Aptech Limited
Overview of the Session
Give the students an overview of the current session in the form of session objectives. Read
out the objectives on slide 2.
Slide 2
Objectives
◆ Explain lambdas
◆ Identify the built-in functional
interfaces
y
◆ Explain code refactoring for
nl
readability using lambdas
◆ Describe debugging of lambda
O
se
© Aptech Ltd.
rU Effective Programming with Lambda/Session 15 2
Slides 3 and 4
Let us understand the definition of lambda and the types of lambda.
Lambda Usage [1-2]
C
◆ Lambda expressions
h
Introduced in Java 8
ec
© Aptech Limited
Lambda Usage [2-2]
Object Inline
lambda lambda
y
nl
O
© Aptech Ltd. Effective Programming with Lambda/Session 15 4
Let us begin with the definition of lambda. A lambda expression, or simply lambda,
introduced in Java 8 is an unnamed block of code that facilitates functional programming.
se
There are two types of lambdas object lambda and inline lambdas. Irrespective of how
lambdas are written, lambdas can use inferred types. This allows passing parameters to the
rU
expression body without specifying the parameter types. Also, the expression body of a
lambda can contain multiple statements and have a return type.
te
Slides 5 to 7
Let us understand about the different types of lambdas.
en
Code Snippet
package lambdaexpressiondemo;
h
import java.util.Arrays;
ec
@FunctionalInterface
interface FunctionalA {
int doWork(int a, int b);
pt
}
public class LambdaExpressionDemo {
public static void main(String[] args) {
/*Lambda 1: Using basic lambda */
rA
© Aptech Limited
Lambda Types [2-5]
/*Lambda 2: Using lambda with inferred types */
FunctionalA functionalA2 = (num1, num2) -> num1 +
num2;
System.out.println("5+10= " +
functionalA2.doWork(5, 10));
/*Lambda 3: Using lambda with expression body
containing return statement */
FunctionalA functionalA3 = (num1, num2) -> {
return num1 + num2;
};
System.out.println("5+15= " +
functionalA3.doWork(5, 15));
/*Lambda 4: Using lambda with expression body
containing multiple statements */
y
nl
O
© Aptech Ltd. Effective Programming with Lambda/Session 15 6
se
FunctionalA functionalA4 = (num1, num2) -> {
int sum = num1 + num2;
};
rU
int result = sum * 10;
return result;
System.out.println("(5+10)*10= " +
functionalA4.doWork(5,
te
10));
/*Lambda 5: Passing lambda as method parameter to
Arrays.sort() method*/
en
Arrays.sort(words,
h
Explain the code creates a functional interface, named FunctionalA. The code then uses
several lambdas in the LambdaExpressionDemo class based on the FunctionalA functional
interface.
pt
rA
Fo
© Aptech Limited
Slide 8
Let us understand the output of FunctionalInterfacesDemo class.
Lambda Types [4-5]
(first, second) -> Integer.compare(first.length(),
second.length()));
System.out.println("Sorted array by length using
lambda= "+ Arrays.toString(words));
}
}
y
nl
O
© Aptech Ltd. Effective Programming with Lambda/Session 15 8
se
Explain about the output of the code that uses the FunctionalInterfacesDemo class.
Slide 9
Let us understand each type of lambda.
Lambda Types [5-5]
rU
te
◆ The lambdas used in the code are:
Lambda 1: Uses basic lambda syntax to assign the value of a
en
Explain that the code uses five types of lambdas. Lambda 1 to lambda 5
o Lambda 1: Uses basic lambda syntax to assign the value of a lambda expression
Fo
© Aptech Limited
Slide 10
Let us understand the Built-in Functional Interfaces.
y
Function<T, R apply(T t) Represents an operation that takes an
nl
R> argument and returns some result to
the caller
Supplier<T> T get() Represents an operation that does not
O
take any argument but returns a value
to the caller
se
© Aptech Ltd. Effective Programming with Lambda/Session 15 10
Java 8 comes with a large number of built-in functional interfaces as part of the new
rU
java.util.function package. Some of the functional interfaces are listed here.
te
en
C
h
ec
pt
rA
Fo
© Aptech Limited
Slides 11 and 12
Let us understand the Built-in Functional Interfaces with the help of code.
package lambdaexpressiondemo;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
y
static void testPredicate() {
Predicate<String> result = arg -> (arg.equals("Hello
nl
Lambda"));
String testStr = "Hello Lambda";
System.out.println(result.test(testStr));
O
}
se
© Aptech Ltd. Effective Programming with Lambda/Session 15 11
rU
public class FunctionalInterfacesDemo {
static void testConsumer() {
Consumer<String> result = str ->
System.out.println(str.toUpperCase());
te
result.accept("hello lambda");
}
}
ec
© Aptech Limited
Lastly, the testProducer()
o Uses lambda for the T get() method of Supplier.
o The lambda simply returns back a string to the caller.
Slide 13
Let us understand the output of Built-in Functional Interface code.
Built-in Functional Interfaces [4-4]
public static void main(String[] args) {
testPredicate();
testConsumer();
testFunction();
y
testProducer();
}}
nl
O
Following is the output of the code:
se
© Aptech Ltd. rU Effective Programming with Lambda/Session 15
Explain about the output of the code that uses the FunctionalInterfacesDemo class.
13
te
en
C
h
ec
pt
rA
Fo
© Aptech Limited
Slide 14
Let us understand about primitive versions of functional interfaces.
Primitive Versions of Functional Interfaces [1-3]
y
nl
Java 8 provides primitive versions for
functional interfaces.
O
© Aptech Ltd. Effective Programming with Lambda/Session 15 14
se
Explain in brief about the primitive versions of functional interfaces. Explain the functional
interfaces Predicate<T>, Consumer<T>, Function<T, R>, and Supplier<T> are generic and
rU
therefore, operate on reference type objects. Primitive values, such as int, long, float, or
double cannot be used with them. Therefore, Java 8 provides primitive versions for such
functional interfaces. Give an example tell them that the IntPredicate, LongPredicate, and
te
DoublePredicate are primitive versions of the Predicate interface. Similarly, IntConsumer,
LongConsumer, and DoubleConsumer are primitive versions of the Consumer interface.
en
Slide 15
Let us understand the primitive versions of Predicate and Consumer functional Interfaces.
C
Code Snippet
pt
package lambdaexpressiondemo;
import java.util.function.IntPredicate;
rA
import java.util.function.LongConsumer;
public class PrimitiveFunctionalInterfacesDemo {
static void testIntPredicate() {
IntPredicate result = arg -> (arg==10);
System.out.println("IntPredicate.test() result:
Fo
"+result.test(11));
}
Explain about the use of the primitive versions of the Predicate and Consumer functional
interfaces.
© Aptech Limited
Slide 16
Explain the code that uses the PrimitiveFunctionalInterfacesDemo class.
y
}
nl
Following is the output of the code:
O
se
© Aptech Ltd. Effective Programming with Lambda/Session 15 16
Explain about the output of the code that uses the PrimitiveFunctionalInterfacesDemo class.
Slide 17 rU
Let us understand the binary versions of the functional interfaces with an example.
te
Binary Versions of Functional Interfaces [1-3]
en
C
Explain the binary versions of the functional interfaces with an example. You have learned
about primitive versions of functional interfaces, we will now learn binary versions of
functional interfaces. The abstract methods of the Predicate, Consumer, and Function
functional interfaces accept one argument. Java 8 provides equivalent binary versions of
such functional interfaces that can accept two parameters. The binary functional version
interfaces are prefixed with Bi, such as BiPredicate, BiConsumer, and BiFunction.
© Aptech Limited
Slide 18
Let us understand Predicate and Consumer functional interfaces.
Binary Versions of Functional Interfaces [2-3]
package lambdaexpressiondemo;
import java.util.function.BiPredicate;
import java.util.function.BiConsumer;
public class BinaryFunctionalInterfacesDemo {
static void testBiPredicate() {
y
BiPredicate<Integer, Integer> result = (arg1, arg2) ->
arg1
nl
< arg2;
System.out.println("BiPredicate.test() result:
"+result.test(5,10));
}
O
© Aptech Ltd. Effective Programming with Lambda/Session 15 18
se
Explain about the different uses of the binary versions of the Predicate and Consumer
functional interfaces. Explain how the code uses the BiPredicate binary version of the
rU
Predicate interface in the testBiPredicate() method. It tests if the first Integer parameter is
less than the second one. Explain in the testBiConsumer() method, the BiConsumer primitive
version of the Consumer interface adds and prints the two string parameters.
te
Slide 19
en
System.out.println("BiConsumer.accept() result:
"+arg1+arg2);
ec
}
}
rA
Explain about the output of the code that uses the BinaryFunctionalInterfacesDemo class.
© Aptech Limited
Slide 20
Let us understand the UnaryOperator functional interface.
UnaryOperator Interface [1-2]
◆ UnaryOperator
Present in the
java.util.function
package
Is a specialized version of
the Function
y
interface.
nl
Can be used on a single
operand when the types
O
of the operand and result
are the same.
© Aptech Ltd. Effective Programming with Lambda/Session 15 20
se
Explain the UnaryOperator functional interface. Explain that the java.util.function package
contains a UnaryOperator functional interface that is a specialized version of the Function
rU
interface. UnaryOperator can be used on a single operand when the types of the operand
and result are the same.
te
en
C
h
ec
pt
rA
Fo
© Aptech Limited
Slide 21
Let us understand the use of UnaryOperator through a code example.
UnaryOperator Interface [2-2]
y
}
}
nl
}
O
© Aptech Ltd. Effective Programming with Lambda/Session 15 21
se
Explain about the use of UnaryOperator through a code example. Explain that the code uses
a UnaryOperator as the assignment target for a lambda. The lambda expression accepts a
rU
string parameter, converts it into upper case, and returns the result as a string. The apply()
method that UnaryOperator inherits from function executes the lambda. Also, talk about the
output of the code that uses the UnaryOperator class.
te
Slide 22
en
◆ Lambda
o Is useful for Java programmers for
h
Explain the refactoring for improved readability. Provide the benefits of lambdas to Java
programmers. Lambda introduced in Java 8 can greatly increase readability of code. Java
programmers can use lambdas to express problems in many situations in a shorter and more
readable way than it was possible before. Explain the introduction of lambdas does not
break code. Existing code can run as it is with new code containing lambdas running
alongside. However, developers might want to refactor their existing code to use the more
convenient lambdas. Typically, refactoring will be done to remove existing boilerplate code
and make the code more concise.
© Aptech Limited
Slide 23
Let us understand how to create a Runnable object and call its run() object.
Refactoring for Improved Readability [2-3]
package lambdaexpressiondemo;
public class MultiThreadedAnonymousDemo {
public static void main(String[] args) {
Runnable r1 = new Runnable(){
@Override
y
public void run(){
System.out.println("Hello from anonymous");
nl
}
};
r1.run();
}
O
}
se
Explain that in multithreaded applications, one way to implement a new thread is to create a
Runnable object and call its run() object. Prior to Java 8, it was achieved through an
rU
anonymous class. Explain the code given on the slide 23.
Slide 24
te
Let us understand the use of Lambda to write a Runnable instance.
Refactoring for Improved Readability [3-3]
en
Code Snippet
package lambdaexpressiondemo;
h
Runnable r1 = () -> {
System.out.println("Hello from lambda");
};
r1.run();
pt
}
}
rA
Explain about how Runnable contains a single abstract method, void run(), and so is as a
functional interface. For increased readability, a lambda can be used to represent the code
to execute. The lambda can then be assigned to a Runnable instance variable to be executed
later through a call to the run() method.
© Aptech Limited
Slide 25
Let us understand the Comparator interface.
Refactoring Comparison Code [1-5]
◆ Comparator Interface:
Enables comparing the elements of a collection that
need to be sorted.
y
nl
❑ When a collection or array needs to be sorted, a Comparator
object is passed to the Collections.sort() or
O
Arrays.sort() method.
se
Explain the Comparator interface. Let us now take a look at the comparator interface. The
Comparator interface enables comparing the elements of a collection that need to be
rU
sorted. Comparator is a functional interface that contains the single int compare(T o1, T o2)
method. When a collection or array needs to be sorted, a Comparator object is passed to the
Collections. sort() or Arrays.sort() method. Prior to Java 8, a Comporator can be passed to
te
the sort() method as an anonymous class.
en
Slide 26
Let us understand Comparator using anonymous inner classes.
C
Code Snippet
. . .
Collections.sort(employeeList, new Comparator<Employee>() {
pt
@Override
public int compare(Employee emp1, Employee emp2) {
return emp1.getLastName().compareTo(emp2.getLastName());
}
rA
});
System.out.println("=== Sorted Employee by last name in
ascending order ===");
for (Employee emp : employeeList) {
System.out.println(emp.getFirstName() + " " +
Fo
emp.getLastName());
}
. . .
Explain that the code shown here applies a Comparator using an anonymous inner class to
sort a List of objects. For greater readability, you can use a lambda instead of the inner class
to pass the comparison code for the sort() method.
© Aptech Limited
Slides 27 and 28
Let us understand how Comparator is applied using a lambda to sort a List of Employee
objects.
Refactoring Comparison Code [3-5]
package lambdaexpressiondemo;
import java.util.ArrayList;
y
import java.util.Collections;
import java.util.Comparator;
nl
import java.util.List;
class Employee{
private String firstName;
O
se
© Aptech Ltd. Effective Programming with Lambda/Session 15 27
rU
private String lastName;
public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
te
}
public String getFirstName() {
return firstName;
en
}
public String getLastName() {
return lastName;
}
}
C
Explain about how a Comparator is applied using a lambda to sort a List of Employee
objects.
rA
Fo
© Aptech Limited
Slide 29
Let us understand the output of the code that uses the ComparatorLambdaDemo class.
Refactoring Comparison Code [5-5]
employeeList.add(new Employee("David", "Cook"));
Comparator<Employee> sortedEmployee = (Employee emp1,
Employee emp2) -> emp1.getLastName()
.compareTo(emp2.getLastName());
System.out.println("=== Sorted Employee List by last
name in ascending order
===");
Collections.sort(employeeList,sortedEmployee);
for (Employee emp : employeeList) {
System.out.println(emp.getFirstName() + " " +
emp.getLastName());
}}}
y
Following is the output of the code:
nl
O
© Aptech Ltd. Effective Programming with Lambda/Session 15 29
se
Explain about the output of the code that uses the ComparatorLambdaDemo class.
Slide 30
Let us understand Callable and Future.
rU
te
Refactoring Concurrency Code [1-5]
Explain that Callable and Future are extensively used in multithread Java applications to
implement asynchronous processing. Callable is similar to Runnable in that both can be used
Fo
to create a task which can be executed by threads in parallel. However, unlike Runnable that
cannot return a value, Callable can return a value. In addition, the call() method of Callable
can throw checked exception, which is not possible for the run() method of Runnable.
Callable is a functional interface in the java.util.concurrent package. The Callable interface
have a single V call() abstract method. When a Callable is passed to a thread pool
maintained by ExecutorService, the pool selects a thread and execute the Callable. On
execution, the thread returns a Future object that holds the result of computation once
done. The get() method of Future returns the computation result or block if the computation
is not complete.
© Aptech Limited
Slide 31
Let us understand anonymous class.
y
try{
Thread.sleep(10);
return Thread.currentThread().getName();
nl
}
catch(InterruptedException ie){
ie.printStackTrace();
O
}
return Thread.currentThread().getName();
}
};
Future<String> future = executor.submit(callable);
se
. . .
© Aptech Ltd. Effective Programming with Lambda/Session 15 31
rU
Explain about how a use of an anonymous class runs a piece of code in a different thread
with Callable and Future.
te
en
C
h
ec
pt
rA
Fo
© Aptech Limited
Slides 32 and 33
Let us understand the use of Callable construct using Lambda.
Refactoring Concurrency Code [3-5]
package lambdaexpressiondemo;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
y
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
nl
import java.util.concurrent.Future;
public class CallableLambdaDemo {
public static void main(String[] args) {
O
ExecutorService executor =
Executors.newFixedThreadPool(5);
se
Refactoring Concurrency Code [4-5]
rU
List<Future<String>> list = new ArrayList<>();
Callable callable = () -> {
try {
Thread.sleep(10);
te
return Thread.currentThread().getName();
} catch (InterruptedException ie) {
ie.printStackTrace();
en
}
return Thread.currentThread().getName();
};
for (int i = 0;i < 10; i++) {
Future<String> future = executor.submit(callable);
C
list.add(future);
}
for (Future<String> future : list) {
try {
h
System.out.println(future.get());
} catch (InterruptedException | ExecutionException e)
{
ec
Explain about the code. Here, we see the complete code refactored to construct a Callable
using lambda instead of an anonymous and to submit the Callable to an ExecutorService.
rA
Fo
© Aptech Limited
Slide 34
Let us understand CallableLambdaDemo class.
Refactoring Concurrency Code [5-5]
e.printStackTrace();
}
}
executor.shutdown();
}
}
y
nl
O
© Aptech Ltd. Effective Programming with Lambda/Session 15 34
se
Explain about the output of the code that uses the CallableLambdaDemo class.
Slides 35 to 37
Let us understand how to debug lambda.
Debugging Lambdas [1-5]
rU
te
The code snippet demonstrates a Java class with lambda that you can
en
debug in NetBeans.
Code Snippet
package lambdaexpressiondemo;
C
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
h
class Employee{
ec
this.lastName = lastName;
}
rA
© Aptech Limited
Debugging Lambdas [2-5]
y
emp1.getLastName().compareTo(emp2.getLastName());
nl
O
© Aptech Ltd. Effective Programming with Lambda/Session 15 36
se
System.out.println("Sorted Employee by last name
in ascending order");
}
rU
Collections.sort(employeeList,sortedEmployee);
for (Employee emp : employeeList) {
System.out.println(emp.getFirstName() + " " +
emp.getLastName());
te
}
}
en
C
h
Explain how the code on screen uses a lambda to compare two Employee objects based on
the lastName field and stores it in a Comparator variable.
pt
rA
Fo
© Aptech Limited
Slides 38 and 39
Let us understand the testing process for lambdas and how to debug them in NetBeans.
y
nl
o Select Debug Debug Project from the main menu of NetBeans. The
O
program execution stops in the first breakpoint.
o Observe the first name and last name values in the Variables window
displayed. At this point, the lambda is yet to perform the sorting.
se
© Aptech Ltd. Effective Programming with Lambda/Session 15 38
rU
te
Employee Values before Sorting
o Select Debug Continue from the main menu to continue debugging until
en
Explain the testing process for lambdas and how to debug them in NetBeans. Describe in
pt
detail the step by step procedure to test lambdas. Also explain how to debug them in
NetBeans.
rA
Fo
© Aptech Limited
Slides 40 and 41
Let us summarize the session.
Summary [1-2]
y
◆ Java 8 also provides equivalent binary versions of
some functional interfaces that can accept two
nl
parameters.
O
© Aptech Ltd. Effective Programming with Lambda/Session 15 40
se
Summary [2-2]
rU
UnaryOperator interface is used on a single
operand when the types of the operand and
result are the same.
Java programmers can use lambdas to express
te
◆
Using slides 40 and 41, summarize the key points of this session. Explain the following points
pt
in brief:
rA
functional interfaces.
Java 8 provides primitive versions for functional interfaces to operate on primitive
values.
Java 8 also provides equivalent binary versions of some functional interfaces that
can accept two parameters.
UnaryOperator interface is used on a single operand when the types of the
operand and result are the same.
Java programmers can use lambdas to express problems in a shorter and more
readable way.
© Aptech Limited
Lambda expressions can be debugged in NetBeans like any piece of Java code by
setting breakpoints.
Tips: You can also check the Articles/Blogs/Expert Videos uploaded on the OnlineVarsity site
to gain additional information related to the topics covered in the next session.
y
nl
O
se
rU
te
en
C
h
ec
pt
rA
Fo
© Aptech Limited
Session 16: Java Data Structures
16.1 Pre-Class Activities
Before you commence the session, you should familiarize yourself with the topics of this
session in-depth. Prepare a question or two that will be a key point to relate the current
session objectives.
16.1.1 Objectives
y
By the end of this session, learners will be able to:
nl
Explain the Enumeration interface
O
Describe the BitSet class
Describe the Stack classes
se
Explain the Dictionary classes
You should teach the concepts in the theory class using the images provided. For teaching in
the class, you are expected to use slides and LCD projectors.
C
Tips:
It is recommended that you test the understanding of the students by asking questions in
h
In-Class Activities
pt
© Aptech Limited
Overview of the Session
Give the students an overview of the current session in the form of session objectives. Read
out the objectives on slide 2.
Slide 2
Objectives
y
nl
O
se
© Aptech Ltd.
Methods of the
ec
Enumeration interface
pt
hasMoreElements():
nextElement(): Returns the
Checks whether or not the
rA
© Aptech Limited
Slides 4 and 5
Let us understand the code using enumeration.
Enumeration [2-5]
◆ The code for using an Enumeration to iterate through the elements of an
array.
Code Snippet
package com.datastructures.demo;
import java.lang.reflect.Array;
import java.util.Enumeration;
y
{
private final int arraySize;
nl
private int arrayCursor;
private final Object array;
public CustomEnumeration(Object obj) {
O
arraySize = Array.getLength(obj);
array = obj;
}
se
© Aptech Ltd. Java Data Structures/Session 16 4
Enumeration [3-5]
@Override rU
public boolean hasMoreElements() {
}
return (arrayCursor < arraySize);
te
@Override
public Object nextElement() {
return Array.get(array, arrayCursor++);
en
}
}
C
h
ec
Explain that Enumeration is used to iterate through the elements of an array. The code
shown on slides 4 and 5 creates a CustomEnumeration class that implements the
rA
Enumeration interface. The class constructor accepts an Object and stores its size and the
object itself to the arraySize and array variables respectively. The overridden
hasMoreElements() method returns true if the arrayCursor variable is less than the arraySize
Fo
© Aptech Limited
Slides 6 and 7
Let us understand how to use custom enumeration.
Enumeration [4-5]
package com.datastructures.demo;
import java.util.Enumeration;
public class EnumerationDemo {
public static void main(String[] args) {
String[] strArray = new String[]{“One”, “Two”,
“Three”};
y
Enumeration customEnumeration = new
CustomEnumeration(strArray);
nl
while (customEnumeration.hasMoreElements()) {
System.out.println(customEnumeration.nextElement(
));
O
}
}
}
© Aptech Ltd. Java Data Structures/Session 16 6
se
Enumeration [5-5]
rU
Following is the output of the code:
te
en
C
h
ec
Explain how to use the custom enumeration defined in earlier code using slide 6. Explain
pt
that the code creates a CustomEnumeration instance initialized with an array. Explain the
hasMoreElements() method in the while loop checks for more elements in the array. If
rA
hasMoreElements() method returns true, the nextElement() method prints out the array
element. Also ask students to observe the output on slide 7.
Fo
© Aptech Limited
Slides 8 and 9
Let us understand about BitSet objects.
BitSet Class [1-3]
package com.datastructures.demo;
import java.util.BitSet;
public class BitSetDemo {
y
bitSet1.set(8);
bitSet2.set(3);
nl
bitSet2.set(6);
bitSet2.set(9);
System.out.println(“Values in bitSet1:
“+bitSet1+”\nValues in bitSet2: “+bitSet2);
O
}
}
se
BitSet Class [2-3]
rU
Following is the output of the code:
te
en
C
h
ec
Explain that the code creates two BitSet objects and calls the set()method to initialize
pt
them. Finally, the BitSet objects are printed out using slides 8 and 9.
rA
Fo
© Aptech Limited
Slide 10
Let us understand about Stack and its methods.
BitSet Class [3-3]
y
push(E item) Pushes an object onto the top of this Stack.
search(Object o)
nl
Returns the position of an object from the top of
the Stack. This method returns 1 for the object at
the top of the Stack, 2 for the object below it, and
O
so on. If an object is not found, this method returns
-1.
se
Explain that Stack is a collection of objects based on the Last-in First-out (LIFO) principle. In
a Stack, the last element added, or pushed to the stack is the first element to be removed, or
popped out of the stack. The Stack class extends the Vector class and in addition to the
rU
inherited methods of Vector, Stack defines five methods, as listed in the table given on the
slide.
te
Slides 11 to 13
Let us understand the use of Stack class through a code example.
en
package com.datastructures.demo;
import java.util.Stack;
ec
stack.push(“obj2”);
stack.push(“obj3”);
stack.push(“obj4”);
return stack;
rA
}
Fo
© Aptech Limited
Stack Class [2-3]
public static void main(String[] args) {
Stack initializedStack =
StackDemo.getInitializedStack();
System.out.println(“Object at top: “ +
initializedStack.peek());
System.out.println(“Position of obj2 from
top: “ +
initializedStack.search(“obj2”));
System.out.println(“Object popped out: “ +
initializedStack.pop());
System.out.println(“Object at top: “ +
initializedStack.peek());
System.out.println(“---Elements in Stack---
”);
for (Object obj : initializedStack) {
y
System.out.println(obj);
}
}
nl
}
O
© Aptech Ltd. Java Data Structures/Session 16 12
se
Following is the output of the code:
rU
te
en
C
h
Explain that the getInitializedStack() method of the code creates a Stack and
pushes four objects to it. The main() method calls the peek() method to retrieve and
print the object at the top of the Stack. The search() method obtains and prints the
pt
position of the obj2 object from the top. The pop() method pops out the element at
rA
the top and the peek() method again obtains and prints the element currently at the top.
Finally, the enhanced for loop prints each element present in the Stack.
Fo
© Aptech Limited
Slide 14
Let us understand Dictionary Classes.
Dictionary Classes
y
nl
The Dictionary abstract class of the
java.util package is the super class of all
dictionary implementation classes.
O
© Aptech Ltd. Java Data Structures/Session 16 14
se
Explain dictionary classes. In Java collections, a dictionary is used to store key-value pairs.
Every key and value in a dictionary is an object. The Dictionary abstract class of the java.util
rU
package is the super class of all dictionary implementation classes. Examples of dictionary
implementation classes are Hashtable and Properties.
te
Slide 15
Let us understand the Hashtable Class.
en
o implements a collection of key-value pairs that are organized based on the hash
code of the key.
o is significantly faster as compared to other dictionaries.
h
◆ A hash code is a signed number that identifies the key. Based on the
hash code, a key-value pair, when added to a Hashtable, gets
pt
Explain that in Java collections, a Hashtable is used to store key-value pairs. Every key and
value in a Hashtable is stored in bucket.
© Aptech Limited
Slides 16 to 18
Let us understand the use of Hashtable class.
Hashtable Class [2-4]
Code Snippet
package com.datastructures.demo;
import java.util.Enumeration;
import java.util.Hashtable;
public class HashtableDemo {
private static Hashtable initializeHashtable() {
Hashtable hTable = new Hashtable();
hTable.put(“1”, “East”);
y
hTable.put(“2”, “West”);
hTable.put(“3”, “North”);
nl
hTable.put(“4”, “South”);
return hTable;
}
O
© Aptech Ltd. Java Data Structures/Session 16 16
se
Hashtable Class [3-4]
rU
public static void main(String[] args) {
Hashtable initializedHtable =
HashtableDemo.initializeHashtable();
Enumeration e = initializedHtable.keys();
System.out.println(“---Hashtable Key-Value
te
Pairs---”);
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key + “ : “ +
en
initializedHtable.get(key));
}
e = initializedHtable.keys();
System.out.println(“---Hashtable Keys---”);
while (e.hasMoreElements()) {
C
System.out.println(e.nextElement());
}
e = initializedHtable.elements();
System.out.println(“---Hashtable Values---”);
h
while (e.hasMoreElements()) {
ec
System.out.println(e.nextElement());
}
}
rA
Explain about the use of the Hashtable class. Explain the initializeHashtable() method of the
code creates and initialize a Hashtable with key-value pairs. The main() method creates an
Enumertion of the Hashtable with a call to the keys() method. The get(key) method retrieves
© Aptech Limited
the value of a particular key. The elements() method returns all the values of the Hashtable
as an Enumeration object. The code uses the Enumeration object to print the key-value
pairs, keys, and values of the Hashtable.
Slide 19
Let us understand in brief about the Properties class.
Properties Class [1-3]
Properties class
y
nl
O
extends Hashtable inherits the put()
to implement a method to add a
collection of key-value key-value pair, you
se
pairs. should avoid it.
© Aptech Ltd.
rU Java Data Structures/Session 16
Explain in brief about the properties class. Explain that the Properties class extends
19
Hashtable to implement a collection of key-value pairs where both the types of the keys
te
and values are String. Although being a Hashtable subclass, the Properties class
inherits the put() method to add a key-value pair, however, you should avoid it. This is
en
because, if you add a non-string key or value, the method will fail at runtime. Instead, you
should use the setProperty() method to add key-value pairs and the
C
© Aptech Limited
Slides 20 and 21
Let us understand the use of Properties class.
Properties Class [2-3]
y
properties.setProperty(“1”, “East”);
properties.setProperty(“2”, “West”);
nl
properties.setProperty(“3”, “North”);
properties.setProperty(“4”, “South”);
return properties;
O
}
public static void main(String[] args) {
Properties initializedProperties =
© Aptech Ltd. Java Data Structures/Session 16 20
se
Properties Class [3-3]
rU
PropertiesDemo.initializeProperties();
Set = initializedProperties.keySet();
Iterator itr = set.iterator();
while (itr.hasNext()) {
String str = (String) itr.next();
System.out.println(“The value of “
te
+ str + “ is “ +
initializedProperties.getProperty(str) + “.”);
}
en
}
}
object and initializes it with key-value pairs through calls to the setProperty() method.
The main() method calls the keyset() method to retrieve a Set object containing a
rA
collection of keys. The iterator() method returns an Iterator object that is used to
iterate through the key-value pairs. For each iteration, the key-value pairs are printed by the
Iterator.next() and Properties.getProperty().
Fo
© Aptech Limited
Slide 22
Let us summarize the session.
Summary
a collection.
◆ BitSet is a collection of bit values.
collection.
◆ Dictionary is used to store key-value pairs.
y
◆ Hashtable stores key-value pairs where keys are organized based
nl
on their hash code.
◆ Properties stores key-value pairs where both the types of the
O
© Aptech Ltd. Java Data Structures/Session 16 22
se
Using this slide, summarize the key points of this session. Explain the following points in
brief:
rU
Java includes a few legacy data structures such as Enumeration, BitSet, and so on for
backward compatibility.
Enumeration interface is used to iterate through the elements of a collection.
te
BitSet is a collection of bit values.
Stack extends Vector to provide an implementation of a LIFO collection.
en
Properties stores key-value pairs where both the types of the keys and values are String.
You should familiarize yourself with the topics of the next session.
pt
Tips: You can also check the Articles/Blogs/Expert Videos uploaded on the OnlineVarsity site
to gain additional information related to the topics covered in the next session.
rA
Fo
© Aptech Limited
Session 17: Java Logging API and
ResourceBundle
17.1 Pre-Class Activities
Before you commence the session, you should familiarize yourself with the topics of this
session in-depth. Prepare a question or two that will be a key point to relate the current
session objectives.
y
17.1.1 Objectives
nl
By the end of this session, learners will be able to:
O
Describe the Log4J architecture
se
Identify Log4J configuration options
Explain the file appender
Explain the JDBC appender
Identify the ResourceBundle class rU
17.1.2 Teaching Skills
te
To teach this session, you should be well versed with the concepts of Java Programming.
en
You should be familiar with the difference between Professional Programming in Java. You
should also know the advantages and disadvantages of Java.
C
You should teach the concepts in the theory class using the images provided. For teaching in
the class, you are expected to use slides and LCD projectors.
h
ec
Tips:
It is recommended that you test the understanding of the students by asking questions in
pt
In-Class Activities
© Aptech Limited
Overview of the Session
Give the students an overview of the current session in the form of session objectives. Read
out the objectives on slide 2.
Slide 2
Objectives
y
◆
nl
O
se
© Aptech Ltd.
database
◆ Is composed of three primary components:
◈ Loggers, Appenders, and Layouts
Fo
Explain that Log4J is an open-source logging framework for Java applications. It enables
generating log messages from different parts of the application. Log messages allow
debugging the application for errors and tracing the execution flow. Log4J assigns different
level of importance, such as ERROR, WARN, INFO, and DEBUG to log messages. With Log4J,
log messages can be routed to different types of destinations. Some of these destinations
include console, file, and database. The Log4J architecture is composed of three primary
components, which are Loggers, Appenders, and Layouts.
© Aptech Limited
Slide 4
Let us understand about loggers.
Loggers [1-3]
◆ Logger
◈ Is the primary Log4J component that is responsible for logging messages
◆ Developers can:
Create their own application-specific
loggers
y
nl
◆ Log4J2 searches for an application-specific logger or uses the
O
root logger
se
Explain that logger is the primary Log4J component that is responsible for logging messages.
Developers can create their own application-specific loggers or use the Log4J root logger. All
rU
Log4J loggers inherit from the root logger. Therefore, whenever a piece of code logs some
message, Log4J2 searches for an application-specific logger. If none are found, Log4J uses
the root logger.
te
Slide 5
en
LoggerManager.getRootLogger()
ec
It is recommended to name the logger with the fully qualified name of the
class that will perform logging.
Fo
Explain that in an application, the root logger can be instantiated and retrieved by calling the
LoggerManager. getRootLogger() method. Application loggers can be instantiated and
retrieved by calling the LoggerManager.getLogger(String loggerName) method that accepts
the name of the desired logger as a parameter. Although, any name can be passed to the
getLogger() method as a String, it recommend to name the logger with the fully qualified
name of the class that will perform logging.
© Aptech Limited
Slide 6
Let us understand about the Log4J log levels.
Loggers [3-3]
◆ Loggers are assigned log levels where TRACE is the lowest level. The levels
move up from TRACE through DEBUG, INFO, WARN, and ERROR, until the
highest FATAL level.
◆ When a higher level is assigned to a logger:
◈ All log messages of that level and the levels below it are logged
y
nl
O
◈ For example, if the INFO level is assigned to a logger, then INFO, DEBUG, and
TRACE messages are logged by the logger.
© Aptech Ltd. Java Logging API and ResourceBundle/Session 17 6
se
Explain that the figure given on the slide displays the Log4J log levels. Loggers are assigned
log levels where TRACE is the lowest level. The levels move up from TRACE through DEBUG,
INFO, WARN, and ERROR, until the highest FATAL level.
rU
When a higher level is assigned to a logger, all log messages of that level and the levels
below it are logged. For example, if the INFO level is assigned to a logger, then INFO, DEBUG,
te
and TRACE messages are logged by the logger. Mention that in addition to the standard log
levels, Log4J defines two special levels, named ON and OFF. The ON level turns on all levels
en
Slides 7 and 8
C
Appenders [1-2]
ec
Example
ConsoleAppender logs messages to the console,
FileAppender logs messages to a file, and
JDBCAppender log messages to a relational database table.
© Aptech Limited
Appenders [2-2]
y
nl
O
© Aptech Ltd. Java Logging API and ResourceBundle/Session 17 8
Loggers log messages to output destinations, such as console, file, and database. Such
output destinations are known as appenders. Log4J provides a number of appender classes
se
to log messages to various destinations. For example, ConsoleAppender logs messages to
the console, FileAppender logs messages to a file, and JDBCAppender log messages to a
rU
relational database table. Log4J also allows defining custom appenders. A customer
appender extends from the AppenderSkeleton class that defines the common logging
functionality. The core method of AppenderSkeleton that a custom appender should
te
override is the append() method.
en
Slide 9
Let us understand about layout.
C
Layout
h
◆ Layouts:
ec
Log4J also supports custom layout that can be created by extending the
abstract AbstractStringLayout class.
Explain that layouts define how log messages are formatted in the output destination.
Layouts are associated with appenders. Before an appender sends a log message to the
output destination, it uses the associated layout to format the log message. Log4J provides
built-in layout classes, such as PatternLayout, Htmlayout, JsonLayout, and XmlLayout. Log4J
also supports custom layout that can be created by extending the abstract
AbstractStringLayout class.
© Aptech Limited
Slide 10
Let us understand NetBeans project to include the Log4J JAR files.
y
• Open NetBeans.
Step 3
nl
• Create a Log4JDemo Java application project.
Step 4
O
• Select Files → Project Properties (Log4JDemo) from the main menu
Step 5 of NetBeans.
se
© Aptech Ltd. Java Logging API and ResourceBundle/Session 17 10
Explain the steps to configure a NetBeans project to include the Log4J JAR files are:
https://logging.apache.org/log4j/2.0/ download.html. rU
• Download the Log4J binary file from the official Website,
Slide 11
Let us understand how to configure a NetBeans project to include the Log4J JAR files
C
Continue to explain the steps to configure a NetBeans project to include the Log4J JAR files
and explain the figure given on the slide. In the next step, you need to select Files → Project
Properties (Log4JDemo) from the main menu of NetBeans.
© Aptech Limited
Slide 12
Let us understand ProjectProperties window.
Step 6 • In the Project Properties – Log4JDemo dialog box, select Libraries, and then click Add JAR/Folder.
y
nl
O
se
© Aptech Ltd. Java Logging API and ResourceBundle/Session 17 12
In the Project Properties – Log4JDemo dialog box that appears, select Libraries and then
click Add JAR/Folder.
Slide 13
rU
te
Let us understand how to add JAR files.
en
• In the Add JAR/Folder dialog box, browse to downloaded Log4J directory, and
Step 7 select log4j-api-2.x.x.jar and log4j-core-2.x.x.jar files by pressing Ctrl button.
C
h
ec
pt
rA
In the Add JAR/Folder dialog box that appear, browse to the downloaded Log4J directory,
and select the log4j-api-2.x.x.jar and log4j-core-2.x.x.jar files by pressing the Ctrl button.
© Aptech Limited
Slide 14
Let us understand how to open a project and how to add Log4J.
Project Configuration [5-5]
• Click Open.
Step 8
y
Log4JDemo dialog box. This adds the
Step 9 required Log4J JAR files to the project.
nl
O
© Aptech Ltd. Java Logging API and ResourceBundle/Session 17 14
se
Let us learn about the next steps.
Step 8: Click Open.
rU
Step 9: Click OK in the Project Properties – Log4JDemo dialog box. This adds the required
Log4J JAR files to the project.
te
Slide 15
Let us understand about Logging Methods.
en
Proceed to talk about the log methods. Read out the table given on the slide for the
students and explain the list.For each of the log levels, Log4J defines a corresponding log
method.
© Aptech Limited
Slides 16 and 17
Let us understand LoggerDemo class that uses all the log methods.
y
LogManager.getLogger("LoggerDemo.class");
public void performLogging(){
nl
logger.debug("This is a debug message");
logger.info("This is an info message");
logger.warn("This is a warn message");
logger.error("This is an error message");
O
logger.fatal("This is a fatal message");
}
se
Logging Methods [3-4]
}
}
rU
public static void main(String[] args){
LoggerDemo logger =new LoggerDemo();
logger.performLogging();
te
◆ The code calls the getLogger() method of LogManager passing the
en
Explain the code snippet to demonstrate a LoggerDemo class that uses all the log methods.
pt
rA
Fo
© Aptech Limited
Slide 18
Let us understand code output explained on slide 17.
Logging Methods [4-4]
◆ Following figure displays the output of the LoggerDemo class:
y
with the ERROR log level. Therefore, only ERROR and FATAL
messages got logged.
nl
O
© Aptech Ltd. Java Logging API and ResourceBundle/Session 17 18
se
This is the continuation of the code output explained on slide 17. Explain the important lines
in this too.The code calls the getLogger() method of LogManager passing the name of the
rU
class as parameter. The getLogger() method returns a Logger object for the class. The
performLogging() method calls the log methods on the Logger object. The main() method
calls the performLogging() method. Explain the figure that displays the output of the
LoggerDemo class.The error message in the output is generated because no Log4J
te
configuration file exists yet. As a result, Log4J uses the default configuration of the root
logger. By default, root logger is configured with the ERROR log level. Therefore, only ERROR
en
and FATAL messages got logged.Log4J can be configured to use specific loggers, appenders,
and layouts. The two most common configuration options are through properties and XML
C
files.
h
ec
pt
rA
Fo
© Aptech Limited
Slide 19
Let us understand Log4J properties configuration file.
name = PropertiesConfig
appenders = consoleappender
appender.consoleappender.type = console
appender.consoleappender.name = STDOUT
y
appender.consoleappender.layout.type =
PatternLayout
nl
appender.consoleappender.layout.pattern =
%d{yyyy-MM-dd HH:mm:ss.SSS} %msg%n
rootLogger.level = debug
O
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT
se
© Aptech Ltd. Java Logging API and ResourceBundle/Session 17 19
Explain that Log4J properties configuration file contains key-value pairs that specifies logging
rU
configuration options. By default, Log4j expects a properties file with the name
log4j2.properties in the project classpath. In a NetBeans Java application project, the
log4j2.properties file should be under the src directory. Explain the code snippet to
demonstrate a log4j2.properties configuration file.
te
en
C
h
ec
pt
rA
Fo
© Aptech Limited
Slide 20
Let us understand the configuration code.
Properties File Configuration [2-3]
y
◈ The rootLogger.level property configures the root logger with the
DEBUG level.
nl
◈ The rootLogger.appenderRefs and
O
© Aptech Ltd. Java Logging API and ResourceBundle/Session 17 20
se
Explain the configuration code.In the configuration code, the name and appenders
properties specify the name of the configuration and the appender to use respectively. The
properties starting with appender configures the appender to use. The
rU
appender.consoleappender.type property specifies console to use the Log4J console
appender. The appender. consoleappender. layout. type and appender.
consoleappender.layout.pattern properties specifies the pattern layout to use for the
te
appender and the specific pattern to use. The pattern contains a date and time format
represented by %d option. The %msg option outputs the application supplied message and
en
Slide 21
ec
© Aptech Limited
Slide 22
Let us understand a log4j2.xml configuration file.
Code Snippet
<?xml version="1.0" encoding="UTF-8"?>
<Configuration name="PropertiesConfig">
<Appenders>
<Console name="consoleappender" target="STDOUT">
<PatternLayout>
<pattern>
%d{yyyy-MM-dd HH:mm:ss.SSS} %msg%n
y
</pattern>>
</PatternLayout>
nl
</Console>
</Appenders>
<Loggers>
<Root level="DEBUG">
O
<AppenderRef ref="consoleappender"/>
</Root>
</Loggers>
</Configuration>
se
© Aptech Ltd. Java Logging API and ResourceBundle/Session 17 22
Explain and display the code snippet that shows a log4j2.xml configuration file. Log4J also
rU
support configurations through XML file. Similar to properties file, a log4j2.xml file must be
present in the project classpath.
Slide 23
te
Let us understand the elements of XML Configuration File.
en
element
The <Appenders> element contains a <Console> element to
configure a console appender.
h
use with the appender and the <pattern> element specifies the
formatting pattern to use.
pt
The level attribute of the <Root> element assigns the DEBUG log
level to the root logger the ref attribute of the <AppenderRef>
element assigns the console appender to the root logger.
Fo
Explain the elements of XML File Configuration. ExplainLog4J XML configuration file contains
the <Configuration> root element. The <Appenders> element contains a <Console> element
to configure a console appender. The <PatternLayout> element specifies the pattern layout
to use with the appender and the <pattern> element specifies the formatting pattern to use.
The <Loggers> element contains the <Root> element to configure the root logger. The level
attribute of the <Root> element assigns the DEBUG log level to the root logger. Finally, the
ref attribute of the <AppenderRef> element assigns the console appender to the root logger.
© Aptech Limited
Slide 24
Let us understand the output of LoggerDemo class.
XML File Configuration [3-3]
y
nl
O
© Aptech Ltd. Java Logging API and ResourceBundle/Session 17 24
se
Explain that this is the continuation of the Log4J XML configuration file. Display the figure
given on the slide that shows the output on executing the LoggerDemo class.
Slide 25
Let us understand File Appender.
rU
te
File Appender [1-2]
en
<Configuration name="PropertiesConfig">
<Appenders>
<File name="fileappender" fileName="applogs/logfile.log" >
<PatternLayout>
<pattern>
h
</PatternLayout>
</File>
</Appenders>
<Loggers>
pt
<Root level="DEBUG">
<AppenderRef ref="fileappender"/>
</Root>
</Loggers>
rA
</Configuration>
© Aptech Ltd. Java Logging API and ResourceBundle/Session 17 25
Explain and display the code snippet given on the slide that shows the use of a file appender.
Fo
The file appender is used to send log messages to a file. A file appender can be configured
with the <File> element in an XML configuration file.
© Aptech Limited
Slide 26
Let us understand the content of logfile.
File Appender [2-2]
y
nl
O
© Aptech Ltd. Java Logging API and ResourceBundle/Session 17 26
se
Explain and display the output of code snippet given on the slide that shows the use of a file
appender.
Slide 27
Let us understand JDBC Appender and its use.
rU
te
JDBC Appender [1-2]
en
Explain JDBC Appender and how to use a JDBC Appender. The JDBC Appender supports
Fo
storing log messages in a database table. The <JDBC> element configures a JDBC appender.
To use a JDBC appender, you need the following mandatory information:
• The connection URL to the database
• The database table name to insert log messages
• The columns in the table to write log messages
To use the JDBC appender, a relational database server is required. One popularly used
database for Java application is MySQL. You can download MySQL from:
http://dev.mysql.com/downloads/windows/installer/5.7.html
Once MySQL is installed, you need to create a database and a table in it to store logging
information.
© Aptech Limited
Slide 28
Code Snippet
y
LEVEL varchar(100), LOGGER
varchar(100), MESSAGE varchar(100) );
nl
O
se
© Aptech Ltd. Java Logging API and ResourceBundle/Session 17 28
Explain the code snippet that demonstrates the statements to create a database and a table.
Slide 29
Let us understand JDBC Appender.
rU
te
Connection Factory [1-4]
en
https://commons.apache.org/proper/commons-
dbcp/download_dbcp.cgi.
rA
Explain how to use the JDBC appender. In order to use the JDBC appender, the application
Fo
needs a connection to the database. You can create a connection factory using the Apache
commons-dbcp package. This package relies on code in the commons-pool package to
manage connection pool. Tell the students that commons-pool package can be downloaded
from https://commons.apache.org/proper/commons-pool/download_pool.cgi.
© Aptech Limited
Slides 30 and 31
Let us understand MySqlConnectionFactory.
y
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
nl
import org.apache.commons.pool.impl.GenericObjectPool;
public class MySqlConnectionFactory {
private static interface Singleton {
O
final MySqlConnectionFactory INSTANCE = new
MySqlConnectionFactory();
}
private final DataSource dataSource;
se
© Aptech Ltd. Java Logging API and ResourceBundle/Session 17 30
rU
private MySqlConnectionFactory() {
Properties properties = new Properties();
properties.setProperty("user", "root");
te
properties.setProperty("password", "root");
GenericObjectPool pool = new GenericObjectPool();
DriverManagerConnectionFactory connectionFactory = new
en
DriverManagerConnectionFactory(
"jdbc:mysql://127.0.0.1/log4jlog", properties);
new PoolableConnectionFactory(connectionFactory, pool,
null, "SELECT 1", 3, false, false,
Connection.TRANSACTION_READ_COMMITTED);
C
return Singleton.INSTANCE.dataSource.getConnection();
}}
ec
© Aptech Limited
Slide 32
Let us understand the outcomes of Connection Factory.
Connection Factory [4-4]
A MySqlConnectionFactory as a singleton.
y
that it constructs.
◆ The getDatabaseConnection() static method:
nl
Is responsible for returning a Connection object.
O
© Aptech Ltd. Java Logging API and ResourceBundle/Session 17 32
se
Explain that the code creates a MySqlConnectionFactory as a singleton.Class constructor
uses a Properties object to set up the database user name and password credentials. The
rU
constructor then initializes a DataSource object from a PoolableConnectionFactory that it
constructs. The getDatabaseConnection() static method is responsible for returning a
Connection object.
te
Slide 33
en
◆ Code snippet demonstrates the log4j2.xml file to configure the JDBC appender.
Code Snippet
<?xml version="1.0" encoding="UTF-8"?>
h
<Configuration status="error">
<Appenders>
ec
</Appenders>
<Loggers>
<Root level="DEBUG">
<AppenderRef ref="databaseAppender" />
</Root>
</Loggers>
Fo
</Configuration>
Explain the Log4J2 configuration file. Explain the Log4J2 configuration file is responsible for
configuring the JDBC appender to use the connection returned by the
MySqlConnectionFactory class for inserting logging information. Explain the code snippet
that demonstrates the log4j2.xml file to configure the JDBC appender.
© Aptech Limited
Slide 34
Let us understand outcomes of Configuration file.
Configuration File [2-3]
◆ The code uses the <JDBC> element to configure the JDBC appender.
y
◆ The <Column> maps:
nl
◈ The table columns with the logging data that the columns will hold.
O
The <Loggers> element associates the JDBC appender with the root
logger.
se
Explain that this is the continuation of the previous slide. Explain the output of the code
snippet. Explain the code uses the <JDBC> element to configure the JDBC appender. The
rU
name and tableName attributes of the <JDBC> element specifies the appender name and
the table name to which logging data will be inserted. The class and method attributes of
the <Appenders> element specifies the connection factory class and the method that
te
returns a connection. The <Column> maps the table columns with the logging data that the
columns will hold. Finally, the <Loggers> element associates the JDBC appender with the
en
root logger.
Slide 35
C
Explain that this is the continuation of the previous slide. Explain the output of the Logging
Data in Database Table on executing the LoggerDemo class.
© Aptech Limited
Slide 36
Let us understand the ResourceBundle Class.
ResourceBundle Class [1-2]
Example
A String, the program loads it from the
ResourceBundle based on the current locale of the
user.
y
• The PropertyResourceBundle and ListResourceBundle
classes extend ResourceBundle.
nl
• The PropertyResourceBundle is a concrete class to represent
locale-specific information stored as key-value pairs in properties file.
• The ListResourceBundle is an abstract class to represent locale-
O
specific information stored in list-based collections.
se
Explain in brief the ResourceBundle class. Explain that the ResourceBundle class of the
java.util package enables creating localized programs that can display the UI and output in
rU
different languages. An object of the ResourceBundle class represents locale-specific
information. When a program needs a locale-specific resource, for example, a String, the
program loads it from the ResourceBundle based on the current locale of the user. The
te
PropertyResourceBundle and ListResourceBundle classes extend ResourceBundle. The
PropertyResourceBundle is a concrete class to represent locale-specific information stored
en
Slide 37
Let us understand the methods of ResourceBundle Class.
h
class loader.
containsKey(String key) Checks whether or not the specified key exists in the
resource bundle.
getKeys() Returns an Enumeration of all keys in the resource
bundle.
keySet() Returns a Set of all keys in the ResourceBundle.
Explain that the table given on the slide lists some of the key methods available in the
ResourceBundle class. Read it out for the students.
© Aptech Limited
Slide 38
Let us summarize the session.
Summary
y
programs based on user locales.
nl
O
© Aptech Ltd. Java Logging API and ResourceBundle/Session 17 38
se
Using this slide, summarize the key points of this session. Explain the following points in
brief:
rU
The Log4J architecture is composed of loggers, appenders, and layouts.
Properties and XML files are two most common approaches to specify Log4J configuration
options.
The file appender redirects logging data to a file.
te
Java 8 provides equivalent binary versions of some functional interfaces that can accept two
parameters.
en
You should familiarize yourself with the topics of the next session.
ec
Tips: You can also check the Articles/Blogs/Expert Videos uploaded on the OnlineVarsity site
pt
to gain additional information related to the topics covered in the next session.
rA
Fo
© Aptech Limited
Session 18: Java Documentation and
Networking
18.1 Pre-Class Activities
Before you commence the session, you should familiarize yourself with the topics of this
session in-depth. Prepare a question or two that will be a key point to relate the current
session objectives.
y
18.1.1 Objectives
nl
By the end of this session, learners will be able to:
O
Explain the Javadoc tool
se
Describe the key classes of the java.net package
Explain socket programming
Explain URL processing
You should teach the concepts in the theory class using the images provided. For teaching in
the class, you are expected to use slides and LCD projectors.
h
Tips:
ec
It is recommended that you test the understanding of the students by asking questions in
between the class.
pt
In-Class Activities
rA
© Aptech Limited
Overview of the Session
Give the students an overview of the current session in the form of session objectives. Read
out the objectives on slide 2.
Slide 2
Objectives
y
◆
nl
◆ Explain URL processing
O
se
© Aptech Ltd.
rUJava Documentation and Networking/Session 18 2
Slide 3
Let us understand the features of Javadoc tool.
Javadoc Tool
C
Explain that Javadoc tool enables creating HTML-based API documentation of Java source
code. Javadoc relies on documentation tags present in the source code. This tool can be
used to create documentation of packages, classes, interfaces, methods, and fields.
© Aptech Limited
Slides 4 and 5
Let us understand Documentation in Java.
Documentation in Java [1-2]
◆ The Java API is a large collection of types where each type can
have a large number of constructs, such as constructors, fields,
and methods.
◆ Developers need to:
Know the purpose of the types and its
constructs
y
their constructs
nl
Describe everything that another developer
would require to use the API
O
© Aptech Ltd. Java Documentation and Networking/Session 18 4
se
Explain using slide 4 Java API is a large collection of types where each type can have a large
number of constructs, such as constructors, fields, and methods.
◆ In Java:
C
JDK path
Explain using slide 5 in Java, API documentation is created using documentation tags. Based
on the tags, the Javadoc tool generates API documentation in HTML.
The tool is automatically installed as part of the Java SDK. It can be found in the bin folder of
the JDK path. IDE tools such as Eclipse and NetBeans also have support for Javadoc.
© Aptech Limited
Slide 6
Let us understand about Javadoc tags.
Javadoc Tags [1-14]
◆ The Javadoc tags can be primarily divided into:
Class-level Tags
Tag Description
@author Inserts the author name of the class
{@code} Inserts text in code format
y
@since Inserts a Since heading used to specify from when
nl
this class exists
@deprecated Inserts a comment to indicate that this class is
O
deprecated and should no longer be used
se
Explain that Javadoc tags can be primarily divided into class-level and method-level tags.
Read out the table given on the slide to the students and explain the list of class level Tags.
Slide 7
Let us understand how to use class-level tags.
rU
te
Javadoc Tags [2-14]
en
/**
* @author Carl Boynton
* @author Andy Payne
* @see Collection
h
* @see Vector
* @since JDK1.0
ec
*/
public class MathDemo {
/*Code implementation*/
}
pt
The class MathDemo will have information indicating who are the authors
of the code, which classes to see further, and since which version the class
rA
Explain the code snippet to demonstrate the use of class-level tags. Explain the output of the
Fo
code. The class MathDemo will have information indicating who are the authors of the code,
which classes to see further, and since which version the class has been existing.
© Aptech Limited
Slide 8
Let us understand Method-level Tags.
Javadoc Tags [3-14]
Method-level Tags
Tag Description
@param Inserts a parameter that the method accepts
@return Inserts the return type of the method
y
@since Inserts a Since heading with a text to specify from
nl
when this class exists
@deprecated Inserts a comment to indicate that this method is
O
deprecated, and should no longer be used
se
Explain that method-level tags are the second type of Javadoc Tags. Read out the table given
on the slide to the students and explain the list of tags mention on the slide.
Slide 9 rU
Let us understand how to use the method-level tags.
te
Javadoc Tags [4-14]
en
/**
C
*/
public int addInt(int num1, int num2) {
return num1 + num2;
}
pt
class failing which the Javadoc tool will report a compilation error.
© Aptech Ltd. Java Documentation and Networking/Session 18 9
Explain the code snippet to students that demonstrates the use of the method-level tags.
Fo
The @see annotation in the code specifies an addLong(long, long) method in the MathDemo
class. This method must be defined in the MathDemo class failing which the Javadoc tool
will report a compilation error.
© Aptech Limited
Slides 10 to 12
Let us understand the use of Javadoc tags and documentation comments.
Javadoc Tags [5-14]
◆ Following code snippet demonstrates the use of Javadoc tags and
documentation comments:
Code Snippet
/**
* The {@code MathDemo} class implements a calculation
algorithm to
* add two integers.
* @author Carl Boynton
* @author Andy Payne
* @see Math
* @since JDK8.0
y
*/
public class MathDemo {
nl
/**
* Constructs a MathDemo instance.
*/
O
© Aptech Ltd. Java Documentation and Networking/Session 18 10
se
Javadoc Tags [6-14]
public MathDemo() { }
}
/**
rU
public long addLong(long num1, long num2) {
return num1 + num2;
/**
* This is the main method to use addInt method.
* @param args Unused.
* @exception java.io.IOException on input error.
Fo
* @see java.io.IOException
*/
public static void main(String[] args) throws
java.io.IOException{
MathDemo mathDemo = new MathDemo();
System.out.println(mathDemo.addInt(5, 8)); }
}
Explain the code to the students that demonstrates the use of Javadoc tags and
documentation comments.
© Aptech Limited
Slides 13 to 19
Let us understand two ways of generating Java documentation.
Javadoc Tags [8-14]
y
nl
◆ The command javadoc MathDemo.java given at the
O
command prompt results in an HTML file containing the
Javadoc generated documentation.
se
You can generate Java documentation for this code snippet using one of two ways: at the
command prompt using the Javadoc tool or using the IDE option and generating Javadoc is
rU
to use the Javadoc generation features of an IDE, such as NetBeans.
If you type the command prompt: javadoc MathDemo.java, it results in an HTML file
containing the Javadoc generated documentation.
te
Javadoc Tags [9-14]
en
Explain the figure on slide 14 that displays the Javadoc generated documentation opened in
Fo
the browser.
© Aptech Limited
Javadoc Tags [10-14]
◆ NetBeans:
◈ Enables automatically inserting Javadoc comments and tags,
generating Javadoc, and viewing Javadoc documentation
◈ Assists in writing Javadoc through hints and the code-completion
feature
◈ Can be automatically generated in source files
◆ For a Javadoc comment, typing /** and pressing the TAB and
ENTER key:
◈ Automatically generates a Javadoc comment block
◆ For a method, typing /** and pressing the TAB and ENTER
key:
◈ @param and @return tags
◆ For other tags:
y
◈ A hint appears as a pop up as a Javadoc tag is typed
On clicking a tag or pressing the ENTER key:
nl
◆
O
© Aptech Ltd. Java Documentation and Networking/Session 18 15
Explain that NetBeans enables automatically inserting Javadoc comments and tags,
generating Javadoc, and viewing Javadoc documentation.
se
NetBeans assists in writing Javadoc through hints and the code-completion feature. Using
the code-completion feature, basic Javadoc comments can be automatically generated in
rU
source files. For a Javadoc comment, typing /** and pressing the TAB and ENTER key
automatically generates a Javadoc comment block. For a method, typing /** and pressing
the TAB and ENTER key additionally generates @param and @return tags depending on the
te
parameter numbers, types, and return type of the method being documented. For other
tags, a hint appears as a pop up as a Javadoc tag is typed. On clicking a tag or pressing the
en
Explain that once you document a Java class, you can easily generate the documentation of
the class using the integrated Javadoc tool of NetBeans. To generate Javadoc
documentations, open the class in NetBeans. Explain the figure given on slide 16.
© Aptech Limited
Javadoc Tags [12-14]
◆ Select Run → Generate Javadoc from the main menu of NetBeans to show the
following figure that displays the Javadoc Documentation Generation in
NetBeans:
y
nl
O
© Aptech Ltd. Java Documentation and Networking/Session 18 17
Explain that NetBeans generates the Javadoc in the dist->javadoc folder of the project
directory. Once Javadoc is generated it can be viewed on the browser. To view the
se
documentation of a class, right-click the class in the code editor. Explain the figure given on
slide 17 that displays the Javadoc Documentation Generation in NetBeans.
The browser displays the documentation. Explain the figure given on slide 18 that displays
the Viewing Javadoc in NetBeans.
Fo
© Aptech Limited
Javadoc Tags [14-14]
y
nl
O
© Aptech Ltd. Java Documentation and Networking/Session 18 19
Explain the figure given on slide 19 that displays the Javadoc generated documentation in
the browser.
se
Slide 20
Let us understand java.net Package.
java.net Package
rU
te
◆ The java.net package:
en
DatagramSocket
Socket
ec
ServerSocket
InetAddress
URL
pt
URLConnection
rA
Explain the java.net Package to students. Tell to students that java.net package contains
classes and interfaces for network programming. Using the java.net package, developers can
Fo
create applications that communicate over networks in the client-server model. The package
contains specialized classes to create transport layer client and server sockets and also
perform communication over the Internet.
Some of the important classes of the java.net package are as follows:
• DatagramPacket
• DatagramSocket
• Socket
• ServerSocket
• InetAddress
• URL
• URLConnection
© Aptech Limited
Slide 21
Let us understand DatagramPacket Class.
DatagramPacket Class [1-2]
y
Are routed differently
nl
O
Note: DatagramPacket object can have a maximum size of 65507
bytes.
© Aptech Ltd. Java Documentation and Networking/Session 18 21
se
Explain that the DatagramPacket class represents datagram packets that are used for
communication using the User Datagram Protocol (UDP) protocol. The UDP protocol is a
rU
lightweight transport-layer protocol used for connectionless delivery of data packets, also
known as datagram packets. A datagram packet contains information about itself and its
destination, based on which the packet is transferred from the source to destination.
te
Datagram packets might be routed differently. In addition, UDP does not guarantee
datagram packet delivery and that datagram packets will arrive in a specific order.
en
Slide 22
C
Method Description
setData(byte[] buf) Sets the data of a packet as a byte[]
pt
Read out the table given on slide 22 for the students and explain the list of methods
specified in table.
© Aptech Limited
Slide 23
Let us understand DatagramSocket Class.
DatagramSocket Class
◆ The DatagramSocket class is responsible for sending and receiving
datagram packets as DatagramPacket objects.
Method Description
connect(InetAddress address, int Connects the socket to the IP address and port
port) of a remote computer
y
disconnect() Disconnects the socket
send(DatagramPacket packet) Sends a DatagramPacket object to a
nl
destination
receive(DatagramPacket packet) Receives a DatagramPacket object
O
se
© Aptech Ltd. Java Documentation and Networking/Session 18 23
Explain about DatagramSocket Class. Read out the table given on slide 23 for the students
and explain the list of methods. The DatagramSocket class is responsible for sending and
receiving datagram packets as DatagramPacket objects.
Slides 24 to 26
rU
te
Let us understand the Socket Class.
en
Represents the socket used by both the client and server for
communicating
h
represents
Guarantees both because both the client and server sockets remains
rA
connected
Explain that the Socket class represents the socket used by both the client and server for
communicating data. The Socket class is used for communication over the Transmission
Control Protocol (TCP) protocol. Similar to UDP, TCP is a transport layer protocol. TCP is
positioned above Internet Protocol (IP), and therefore, is also referred as TCP/IP. However,
unlike UDP, TCP maintains a connection between endpoints that Socket objects represents.
In both the client and the server, Socket objects are used to send and receives TCP packets.
Unlike UDP that does not guarantee packet deliveries and packet ordering, TCP guarantees
both because both the client and server sockets remains connected. On account of the
overhead of maintaining a connection, TCP is slower than UDP.
© Aptech Limited
Socket Class [2-3]
y
to the server by:
nl
Invoking the public Socket(String host, int port)
constructor of the Socket class
O
© Aptech Ltd. Java Documentation and Networking/Session 18 25
se
Explain that how socket class is used to transmit data to a server, a client creates an object of
the Socket class. However, the server never instantiates a Socket. The server obtains a
rU
Socket object by calling the accept() method of the ServerSocket class. A client can create a
Socket to represent a connection to the server by invoking the public Socket (String host, int
port) constructor of the Socket class. In the constructor, the first parameter specifies the IP
te
address of the server and the second address specifies the port number that the server
listens for messages.
en
Method Description
h
getInputStream()
method to receive data.
getOutputStream() Returns an OutputStream object of the Socket.
rA
Read out the table given on slide 26 for the students and explain the list.
© Aptech Limited
Slide 27
Let us understand ServerSocket Class.
ServerSocket Class
y
specified port or the socket times out.
getLocalPort() Returns the port number as an int value that a
ServerSocket object is listening to.
nl
setSoTimeout(int timeout) Sets a timeout in milliseconds after which a
ServerSocket object stops accepting client
connections.
O
isClosed() Returns a boolean value to indicate whether or
not a ServerSocket object is closed.
se
Explain about ServerSocket Class. Read out the table given on slide 27 for the students and
explain the list. Explain that the ServerSocket class is used by servers to listen for incoming
rU
connections from clients. Typically, a server invokes the ServerSocket(String port)
constructor to instantiate a ServerSocket object. Once the server obtains a ServerSocket
object, the server can call various methods of ServerSocket to accept connections and
te
obtain information about the ServerSocket object.
en
Slide 28
Let us understand InetAddress Class.
C
InetAddress Class
object as a byte[]
Explain InetAddress Class. Read out the table given on slide 28 for the students and explain
the list. The InetAddress class represents an Internet address to perform a Domain Name
System (DNS) look-up and reverse look-up. An Internet address, or IP address that the
InternetAddress class represents is a 32-bit number, often represented as a set of four 8-bit
numbers separated by periods. For example, 127.0.0.1 is the IP address of a local computer.
© Aptech Limited
Slide 29
Let us understand the URL class and its methods.
URL Class
◆ The URL class represents a Uniform Resource Locator (URL) that points to a resource on
the Web.
◆ Following table explains the important methods of the URL class:
Method Description
getPath() Returns the path of the URL as a String
getQuery() Returns the query part of the URL as a String
getPort() Returns the port of the URL as an int value
getDefaultPort() Returns the default port for the protocol of the URL as
y
an int value
getProtocol() Returns the protocol of the URL as a String
nl
getHost() Returns the host of the URL as a String
getFile() Returns the filename of the URL as a String
O
openConnection() Opens a connection to the URL and returns a
URLConnection object
se
© Aptech Ltd. Java Documentation and Networking/Session 18 29
Proceed to talk about the URL class. Read out the tables given on slide 29 for the students
rU
and explain the list. The URL class represents a Uniform Resource Locator (URL) that points
to a resource on the Web. A URL can be a Web page, a document, an image, or any other
file.
te
en
C
h
ec
pt
rA
Fo
© Aptech Limited
Slides 30 and 31
Let us understand about the URLConnection class.
URLConnection Class [1-2]
◆ The openConnection() method of the URL class returns an implementation of the
URLConnection class.
◆ Following table explains the important methods of the URLConnection class:
Method Description
getURL() Returns the URL that the URLConnection object is
connected to as a URL object
setDoInput(boolean Accepts a boolean value to indicate whether the
input) URLConnection object will be used for input. The default
value is true
setDoOutput(boolean Accepts a boolean value to indicate whether the
output) URLConnection object will be used for output. The default
y
value is false
getInputStream() Returns the input stream of the URLConnection as an
nl
InputStream object. This method is called to read from a
URL
getOutputStream() Returns the output stream of the URLConnection as a
O
OutputStream object. This method is called to write to a
URL
getContent() Returns an Object of the contents of the URLConnection
se
© Aptech Ltd. Java Documentation and Networking/Session 18 30
Method
getContentEncoding()
rU Description
Returns the content-encoding header field of the of the
URLConnection as a String object
te
getContentLength() Returns the content-length header field of the of the
URLConnection as an int value
getContentType() Returns the content-type header field of the of the
en
Explain about the URLConnection class. Read out the tables given on the slide for the
students and explain the list. The openConnection() method of the URL class returns an
rA
class. Read out the tables given on slide 31 for the students and explain the list.
© Aptech Limited
Slide 32
Let us understand Socket Programming and URL Processing.
A server
y
nl
A client
Socket
O
programming
involves
se
© Aptech Ltd. Java Documentation and Networking/Session 18 32
rU
Explain the Socket Programming and URL Processing. The Socket and ServerSocket classes of
the java.net package enables socket programming over TCP. Socket programming involves a
server and a client.
te
en
C
h
ec
pt
rA
Fo
© Aptech Limited
Slide 33
y
Step 2
nl
• Create input and output streams to receive and send
Step 3 data respectively
O
• Perform communication with the client
Step 4
se
© Aptech Ltd. Java Documentation and Networking/Session 18 33
Explain the steps to create a client and server programs. In a client/server programs that
rU
communicates using TCP/IP, a server is created to listen for client connections. Then, a client
is created to connect with the server and exchange data packages.
The steps to create a server class are as follows:
te
1. Create the server socket as a ServerSocket object
2. Wait for a client request
en
3. Create input and output streams to receive and send data respectively
4. Perform communication with the client
5. Close the socket
C
Slides 34 to 38
h
Let us understand the code snippet to demonstrate the use of ServerSocket to create a
ec
server.
Client/Server Program [2-6]
pt
Code Snippet
package com.io.demo;
import java.io.DataInputStream;
import java.io.DataOutputStream;
Fo
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class Server extends Thread {
private ServerSocket serverSocket;
public Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
}
public void run() {
© Aptech Limited
Client/Server Program [3-6]
Code Snippet
while (true) {
try {
System.out.println(“Listening for
client message on port “ +
serverSocket.getLocalPort());
Socket =
serverSocket.accept();
DataInputStream in = new
DataInputStream(
socket.getInputStream());
y
DataOutputStream out = new
DataOutputStream(socket.
nl
getOutputStream());
out.writeUTF(“Hello from server.”);
}
O
catch (SocketTimeoutException sTException)
{
se
Client/Server Program [4-6]
Code Snippet
}
rU
sTException.printStackTrace();
te
catch (IOException ioException) {
ioException.printStackTrace();
} finally {
try {
en
serverSocket.close();
}
catch (IOException ioException) {
ioException.printStackTrace();
}
C
}
}
}
public static void main(String[] args) {
h
ec
Code Snippet
public static void main(String[] args) {
try {
Thread = new Server(6060);
Fo
thread.start();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
© Aptech Limited
Client/Server Program [6-6]
y
nl
O
© Aptech Ltd. Java Documentation and Networking/Session 18 38
Explain the output of the code. The code creates a Server class that extends Thread. The
constructor creates a ServerSocket object with the specified port passed as parameter. In the
se
overridden run() method of the Thread class, the code calls the accept() method of
ServerSocket to obtain a Socket object. The code then constructs a DataOutputStream
rU
object and uses it to write out a message. The main() method creates a Server object as a
Thread and starts it.
te
Slide 39
Let us understand steps to create a client.
en
◆
h
© Aptech Limited
Slides 40 and 41
Let us understand code snippet that demonstrates the use of the Socket class to create a
client.
Creating a Client [2-3]
◆ Following code snippet demonstrates the use of the Socket class to
create a client:
Code Snippet
package com.io.demo;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
y
import java.net.Socket;
nl
public static void main(String[] args) {
try {
Socket clientSocket = new
O
Socket(“localhost”, 6060);
InputStream inFromServer ==
clientSocket.getInputStream();
se
© Aptech Ltd. Java Documentation and Networking/Session 18 40
rU
System.out.println(“Message received from
server: “ + in.readUTF());
clientSocket.close();
} catch (IOException e) {
te
e.printStackTrace();
}
}
}
en
Explain the code snippet that demonstrates the use of the Socket class to create a client.
The code creates a Client class. In the main() method, the code creates a Socket object
rA
passing the IP address and port of the server. The code then constructs a DataInputStream
from an InputStream object and uses it to write out the message received from the server.
Fo
© Aptech Limited
Slides 42 and 43
Let us understand URL Processing with code.
Code Snippet
package com.io.demo;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
y
import java.io.OutputStream;
import java.net.Socket;
nl
public class Client {
public static void main(String[] args) {
try {
Socket clientSocket = new
O
Socket(“localhost”, 6060);
InputStream inFromServer =
clientSocket.getInputStream();
se
© Aptech Ltd. Java Documentation and Networking/Session 18 42
rU
DataInputStream in = new
DataInputStream(inFromServer);
System.out.println(“Message received from
server: “ + in.readUTF());
clientSocket.close();
te
} catch (IOException e) {
e.printStackTrace();
}
}
en
Explain URL Processing. Then, explain the code snippet that demonstrates the shows the use
pt
with a URL. Using both the URL and URLConnection classes, you can create a URL to a Web
page can be created, establish a connection to the Web page, and retrieve the Web page
content.
Fo
Explain the figure on slide 43 that displays the output of the URLProcessingDemo class.
In the main() method, the code creates a URL object for the http://www.google.com URL.
The getConnection() method returns an URLConnection object that is casted to an
HttpURLConnection object. The getInputStream() method of URLConnection retrieves an
InputStream that is used to create an InputStreamReader object. Then, the code creates a
BufferReader object of InputStreamReader and uses the readLine() method inside a while
loop to retrieve each line of content from the http://www.google.com URL. Finally, the
retrieved content is printed out.
© Aptech Limited
Slide 44
Let us summarize the session.
Summary
◆ The Javadoc tool relies on documentation tags present in
the source code to create API
documentation.
◆ Javadoc can be generated using the Javadoc tool from the
command line or the in-built Javadoc options of NetBeans.
◆ Classes and interfaces of the java.net package supports
network programming.
◆ Socket programming over UDP is supported by the
DatagramPacket and DatagramSocket classes.
y
◆ Socket programming over TCP is supported by the Socket
nl
and ServerSocket classes of the java.net package.
◆ URL processing can be done by the URL and URLConnection
O
classes.
se
© Aptech Ltd. Java Documentation and Networking/Session 18 44
Using this slide, summarize the key points of this session. Explain the following points in
brief:
rU
The Javadoc tool relies on documentation tags present in the source code to create
API documentation.
te
Javadoc can be generated using the Javadoc tool from the command line or the in-
built Javadoc options of NetBeans.
en
DatagramSocket classes.
Socket programming over TCP is supported by the Socket and ServerSocket classes
h
Tips: You can also check the Articles/Blogs/Expert Videos uploaded on the OnlineVarsity site
to gain additional information related to the topics covered in the session.
Fo
© Aptech Limited