Вы находитесь на странице: 1из 134

Day 1

Generics
Sequential Collections
Associative Collections
Exception Handling
String and String Builder
Generics

• Building Generic classes


• Creating Generic Interfaces
• Building Generic Methods
• Building Generic Classes With Different Types
• Exercises
Generics Introduction
• The Java Generics programming is introduced
in J2SE 5 to deal with type-safe objects.
• Generics in Java is similar to templates in C++.
The idea is to allow type (Integer, String, … etc
and user defined types) to be a parameter to
methods, classes and interfaces.
Advantage of Java Generics

• There are mainly 3 advantages of generics.


They are as follows:
• Type-safety : We can hold only a single type
of objects in generics.
• Code Reuse: We can write a
method/class/interface once and use for any
type we want.
• Type casting is not required: There is no need
to typecast the object.
Generic Class
• Like C++, we use <> to specify parameter types
in generic class creation.
• To create objects of generic class, we use
following syntax.
• Type Parameters
• The type parameters naming conventions .The
commonly type parameters are as follows:
• T - Type
• E - Element
• K - Key
• N - Number
• V - Value
• We can pass single Type parameters in
Generic classes.
• We can also pass multiple Type parameters in
Generic classes.
Generic Functions
• We can also write generic functions that can
be called with different types of arguments
• Based on the type of arguments passed to
generic method, the compiler handles each
method appropriately
Generic Interface
• Generics also work with interfaces. Thus, you
can also have generic interfaces. Generic
interfaces are specified just like generic
classes.
• If a class implements a specific type of generic
interface, then the implementing class does
not need to be generic.
• . The generic interface offers two benefits.
First, it can be implemented for different types
of data. Second, it allows you to put
constraints (that is, bounds) on the types of
data for which the interface can be
implemented.
• In the Mathematics example, only types
that extends the Number class can be passed
to T.
• Examples
• Java Collections
• Sequential Collections
• Associative Collections
A Collection is a group of individual objects represented as a single
unit. Java provides Collection Framework which defines several
classes and interfaces to represent a group of objects as a single
unit.
Advantages of Collection Framework:
Consistent API : The API has a basic set of interfaces like Collection, Set,
List, or Map.
All classes (ArrayList, LinkedList, Vector, etc) that implement these
interfaces have some common set of methods.
Reduces programming effort: A programmer doesn’t have to worry about
the design of Collection, and he can focus on its best use in his program.
Increases program speed and quality: Increases performance by providing
high-performance implementations of useful data structures and
algorithms.
The difference between Set and Map interface is that in Set we have only keys, whereas in Map, we have key, value pairs.
List<E>
• List interface is the child interface of
Collection interface. It inhibits a list type data
structure in which we can store the ordered
collection of objects. It can have duplicate
values.
• List interface is implemented by the classes
ArrayList, LinkedList, Vector, and Stack.
ArrayList
• It uses a dynamic array to store the duplicate
element of any types.
• The ArrayList class maintains the insertion
order and is non-synchronized.
• The difference between a built-in array and
an ArrayList in Java, is that the size of an array
cannot be modified (if you want to add or
remove elements to/from an array, you have
to create a new one).
• Methods of ArrayList
• add elements to the ArrayList, use the add()method
• To access an element in the ArrayList, use
the get() method and refer to the index number
• To modify an element, use the set() method and refer
to the index number
• To remove an element, use the remove() method and
refer to the index number
• To remove all the elements in the ArrayList, use
the clear() method
LinkedList

• LinkedList implements the Collection


interface. It uses a doubly linked list internally
to store the elements. It can store the
duplicate elements. It maintains the insertion
order and is not synchronized.
Vector
• Vector uses a dynamic array to store the data
elements. It is similar to ArrayList. However, It is
synchronized
• Difference between Synchronized and Non
Synchronized Collection
• Non synchronized -It is not-thread safe and can't
be shared between many threads without proper
synchronization code. While, Synchronized- It is
thread-safe and can be shared with many threads
Stack

• The stack is the subclass of Vector. It


implements the last-in-first-out data structure,
i.e., Stack. The stack contains all of the
methods of Vector class and also provides its
methods like boolean push(), boolean peek(),
boolean push(object o), which defines its
properties.
Queue Interface

• Queue interface maintains the first-in-first-out order. It can


be defined as an ordered list that is used to hold the
elements which are about to be processed. There are
various classes like PriorityQueue, Deque, and ArrayDeque
which implements the Queue interface.
• PriorityQueue doesn't allow null values to be stored in the
queue.
• In Deque, we can remove and add the elements from both
the side. Deque stands for a double-ended queue which
enables us to perform the operations at both the ends.
• ArrayDeque is faster than ArrayList and Stack and has no
capacity restrictions.
Set Interface

• It represents the unordered set of elements


which doesn't allow us to store the duplicate
items. We can store at most one null value in
Set. Set is implemented by HashSet,
LinkedHashSet, and TreeSet.
HashSet
• The important points about Java HashSet class are:
• HashSet stores the elements by using a mechanism
called hashing.
• HashSet contains unique elements only.
• HashSet allows null value.
• HashSet class is non synchronized.
• HashSet doesn't maintain the insertion order. Here,
elements are inserted on the basis of their hashcode.
• HashSet is the best approach for search operations.
• The initial default capacity of HashSet is 16, and the
load factor is 0.75.
Treeset
• The important points about Java TreeSet class
are:
• Java TreeSet class contains unique elements only
like HashSet.
• Java TreeSet class access and retrieval times are
quiet fast.
• Java TreeSet class doesn't allow null element.
• Java TreeSet class is non synchronized.
• Java TreeSet class maintains ascending order.
• Examples
Map
• A map contains values on the basis of key, i.e.
key and value pair. Each key and value pair is
known as an entry. A Map contains unique
keys.
• A Map is useful if you have to search, update
or delete elements on the basis of a key.
HashMap
• Java HashMap class contains values based on the
key.
• Java HashMap class contains only unique keys.
• Java HashMap class may have one null key and
multiple null values.
• Java HashMap class is non synchronized.
• Java HashMap class maintains no order.
• The initial default capacity of Java HashMap class
is 16 with a load factor of 0.75.
TreeMap
• Java TreeMap contains values based on the
key.
• Java TreeMap contains only unique elements.
• Java TreeMap cannot have a null key but can
have multiple null values.
• Java TreeMap is non synchronized.
• Java TreeMap maintains ascending order.
Exception Handling
• try
• catch
• throw
• throws
String vs StringBuilder vs StringBuffer
Day 2 Topics
• Network Programming
• NIO
• JDBC
Network Programming/Socket
Programming
• Java Socket programming is used for communication
between the applications running on different JRE.
• Java Socket programming can be connection-oriented
or connection-less.
• Socket and ServerSocket classes are used for
connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used
for connection-less socket programming.
• The client in socket programming must know two
information:
• IP Address of Server, and
• Port number.
• Socket class
• A socket is simply an endpoint for
communications between the machines. The
Socket class can be used to create a socket.
ServerSocket class

• This object is used to establish


communication with the clients.
Steps to create and Execute a Socket
Program
• Create a Client Program
• Create a Server Program
• Execute the program in Eclipse
• Compile both of them on two different terminals
or tabs
• Run the Server program first
• Then run the Client program
• Type messages in the Client Window which will
be received and showed by the Server Window
simultaneously.
Chat Program
• Chat communication is the process of exchanging
messages between two systems continuously
• Reading from keyboard. Uses an input stream
like BufferedReader connected to System.in.
• Sending data to the other system what is read
from keyboard. Uses an output stream like
PrintWriter connected to getOutputStream()
method of Socket.
• Receiving data from the other system. Uses an
input stream like BufferedReader connected to
getInputStream() method of Socket.
Java NIO

• Java has provided a second I/O system called


NIO (New I/O). Java NIO provides the different
way of working with I/O than the standard I/O
API's. It is an alternate I/O API for Java (from
Java 1.4).
• It supports a buffer-oriented, channel based
approach for I/O operations.
• It was introduced in Java 7
• Channels and Buffers: In standard I/O API the character
streams and byte streams are used. In NIO we work with
channels and buffers. Data is always written from a buffer
to a channel and read from a channel to a buffer.
• Selectors: Java NIO provides the concept of "selectors". It is
an object that can be used for monitoring the multiple
channels for events like data arrived, connection opened
etc. Therefore single thread can monitor the multiple
channels for data.
• Non-blocking I/O: Java NIO provides the feature of Non-
blocking I/O. Here the application returns immediately
whatever the data available and application should have
pooling mechanism to find out when more data is ready.
IO streams versus NIO blocks
• original I/O deals with data in streams, whereas NIO deals
with data in blocks.(whole data)
• An input stream produces one byte of data, and an output
stream consumes one byte of data.
• Cannot move forth and back in the data in a stream. If you
need to move forth and back in the data read from a
stream, you must cache it in a buffer first
• A block-oriented I/O system deals with data in blocks. Each
operation produces or consumes a block of data in one
step. Processing data by the block can
be much faster than processing it by the (streamed) byte.
You can move forth and back in the buffer as you need to.
This gives you a bit more flexibility during processing.
• Java IO’s various streams are blocking or
synchronous. That means, that when a thread
invokes a read() or write(), that thread is blocked
until there is some data to read, or the data is
fully written.
• In NIO it is asynchronous , a thread can request
that some data be written to a channel, but not
wait for it to be fully written. The thread can then
go on and do something else in the mean time.
Channels and Buffer
• A Buffer object can be termed as container
for a fixed amount of data. It acts as a
holding tank, or temporary staging area,
where data can be stored and later
retrieved.
• Buffers work hand in glove with channels.
• Channels are actual portals through which I/O
transfers take place; and buffers are the
sources or targets of those data transfers.
Buffer Attributes

• Capacity : The maximum number of data


elements the buffer can hold. The capacity is set
when the buffer is created and can never be
changed.
• Limit The count of live elements in the buffer.
• Position : The index of the next element to be
read or written. The position is updated
automatically by relative get() and put() methods.
• Mark : A remembered position.
• There are two types of channels: file and
socket. FileChannel class
and SocketChannel classes
• FileChannel object can be obtained only by
calling the getChannel() method on an
open RandomAccessFile, FileInputStream,
or FileOutputStream object.
• Closing the channel
Example of copying data from one file
to another using Channels
JDBC using Oracle DB
• Getting Started with Oracle
• SqlPlus Command Prompt
• Username: Enter system for the user name.
• Password: Enter the password that was specified
when Oracle Database XE was installed.
• Oracle11g Express has an inbuilt user Hr which is
locked
• To Unlock it , ALTER USER hr ACCOUNT UNLOCK;
• ALTER USER hr IDENTIFIED BY <hr-password>;
• Connect hr/hr
JDBC
• JDBC (Java Database Connectivity) API allows Java
programs to connect to databases

• Database access is the same for all database vendors

• The JVM uses a JDBC driver to translate generalized


JDBC calls into vendor specific database calls

• There are four general types of JDBC drivers


– We will look at Type 4 …
Pure Java Driver (Type 4)
• These drivers convert the JDBC API calls to direct
network calls using vendor-specific networking
protocols by making direct socket connections
with the database
• It is the most efficient method to access database,
both in performance and development time
• It is the simplest to deploy
• All major database vendors provide pure Java
JDBC drivers for their databases and they are also
available from third party vendors
Pure Java Driver
Server
DB Client
Java
Application

Data Source

JDBC
JDBC Driver
API
Typical JDBC Programming Procedure

1. Load the database driver


2. Obtain a connection
3. Create and execute statements (SQL queries)
4. Use result sets (tables) to navigate through the
results
5. Close the connection
Driver Manager
• The purpose of the java.sql.DriverManger
class in JDBC is to provide a common access layer
on top of different database drivers used in an
application

• DriverManager requires that each driver


required by the application must be registered
before use, so that the DriverManager is aware of
it
• Load the database driver using ClassLoader :
– Class.forName
(“oracle.jdbc.driver.OracleDriver”);
Connecting to a Database
• Type 4 JDBC Driver – Oracle Server

• Class.forName (“oracle.jdbc.driver.OracleDriver”);
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");

• Type 4 JDBC Driver – MySQL Server


• Class.forName("com.mysql.jdbc.Driver");
• Connection con=DriverManager.getConnection(
• "jdbc:mysql://localhost/Training","root","admin@123");
Configure oracle driver in java project
• Oracle provides the JDBC connector jar with the product and is available in the
following location in Windows,

• C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib

• There will be multiple jars like,

• ojdbc5.jar – Classes for use with JDK 1.5.


• ojdbc6.jar – Classes for use with JDK 1.6.

• We will be using “ojdbc6.jar”

• Create a new Java Project and name it as JDBCOracle.

• right click on your Java Project -> Properties -> Buildpath -> Libraries -> Add
External JAR and select the odbc6.jar file.
Java Database Connectivity with
MySQL
• Driver class: The driver class for the mysql database
is com.mysql.jdbc.Driver.
• Connection URL: The connection URL for the mysql
database is jdbc:mysql://localhost/DbName where jdbc is
the API, mysql is the database, localhost is the server name
on which mysql is running, we may also use IP address,
3306 is the port number and sonoo is the database name.
We may use any database, in such case, we need to replace
the sonoo with our database name.
• Username: The default username for the mysql database
is root.
• Password: It is the password given by the user at the time
of installing the mysql database.
Configure MySql to JDBC programs
• To connect java application with the mysql
database, mysqlconnector.jar file is required
to be loaded.
• Download this file and add it as external jar to
Java Application
• https://dev.mysql.com/downloads/file/?id=48
0091
• Example of Insert, Select using Oracle DB
Day 3
• JDBC using MySql
• Threads
• Serialization
• Regular Expression
• Additional Java Features
Threads
• Threads Overview
• Creating threads in Java
• Synchronization
• wait() and notify()
• sleep
• Thread Pools
• Exercise
Threads Overview
– Threads allow the program to run tasks in parallel
– In many cases threads need to be synchronized,
that is, be kept not to handle the same data in memory concurrently
– There are cases in which a thread needs to wait for another thread before
proceeding

68
Threads in Java
Option 1 – extending class Thread (cont’):

public class Thread2 extends Thread {

@Override
public void run() {

}
}

69
Threads in Java
Option 2 – implementing Runnable:

public class Thread2 implements Runnable {

@Override
public void run() {

}
}

70
Synchronization
Synchronization of threads is needed for in order to control threads
coordination, mainly in order to prevent simultaneous operations on data

For simple synchronization Java provides the synchronized keyword

For more sophisticated locking mechanisms, starting from Java 5, the


package java.concurrent.locks provides additional locking options

71
wait() and notify() allows a thread to
wait for an event

A call to notifyAll() allows all threads that are


on wait() with the same lock to be released

A call to notify() allows one arbitrary thread


that is on a wait() with the same lock to be
released
RegEx
• The Java Regex or Regular Expression is an API to define a
pattern for searching or manipulating strings.
• Java Regex API provides 1 interface and 3 classes
in java.util.regex package.
• The Matcher and Pattern classes provide the facility of Java
regular expression.
• The java.util.regex package provides following classes and
interfaces for regular expressions.
• MatchResult interface
• Matcher class
• Pattern class
• PatternSyntaxException class
Find and Replace Text
• The replaceFirst() and replaceAll() methods
replace the text that matches a given regular
expression. As their names indicate,
replaceFirst replaces the first occurrence, and
replaceAll replaces all occurrences.
Examples
• Validate Phone Number
Eg : should be 10 digits. 607-8903234
Validate Password
• Be between 8 and 40 characters long
• Contain at least one digit.
• Contain at least one lower case character.
• Contain at least one upper case character.
• Contain at least on special character from [ @ # $ % ! . ].
• ((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})
• Replace Text with new character using Regular Expression
Serialization
• Serialization is a mechanism of converting the
state of an object into a byte stream.
• Deserialization is the reverse process where
the byte stream is used to recreate the actual
Java object in memory.
• To make a Java object serializable we
implement the java.io.Serializable interface.
• The ObjectOutputStream class
contains writeObject() method for serializing
an Object.
• The ObjectInputStream class
contains readObject() method for
deserializing an object.
• Points to remember
• If a parent class has implemented Serializable
interface then child class doesn’t need to
implement it but vice-versa is not true.
• Only non-static data members are saved via
Serialization process.
• Static data members are not saved via
Serialization process.
• Constructor of object is never called when an
object is deserialized.
Additional Topics
• Enums
• Assertions
• Annotations
Assertions
• Assertions in Java
• An assertion allows testing the correctness of any
assumptions that have been made in the
program.
• Assertion is achieved using the assert statement
in Java. While executing assertion, it is believed to
be true. If it fails, JVM throws an error
named AssertionError. It is mainly used for
testing purposes during development.
Enabling Assertions
• java –ea ClassName
• java –enableassertions ClassName
Setting Java Path
• If you get javac is not recognized as an internal or
external command, means JDK Path is not set.
• Confirm that PATH is not set for Java by typing javac in
command prompt.
• Open Control Panel and Select System and Security
• Select System
• Select Advanced System Settings
• Select Environment Variables
• Select and Edit Path Environment variable
• Verify Java path by typing javac in command prompt
• Where to use Assertions
• Arguments to private methods. Private
arguments are provided by developer’s code
only and developer may want to check his/her
assumptions about arguments.
• Conditional cases.
• Conditions at the beginning of any method.
• Where not to use Assertions
• Assertions should not be used to replace error
messages
• Assertions should not be used to check
arguments in the public methods as they may
be provided by user. Error handling should be
used to handle errors provided by user.
• Assertions should not be used on command
line arguments.
Annotations in Java
• Annotations are used to provide supplement
information about a program.
• Annotations start with ‘@’.
• Annotations do not change action of a compiled
program.
• Annotations help to associate metadata (information)
to the program elements i.e. instance variables,
constructors, methods, classes, etc.
• Annotations are not pure comments as they can
change the way a program is treated by compiler. See
below code for example.
Example
• Java defines seven built-in annotations.
• Four are imported from
java.lang.annotation: @Retention, @Docume
nted, @Target, and @Inherited.
• Three are included in java.lang: @Deprecated,
@Override and @SuppressWarnings
Day 4 Topics
• Java 8 New Features
• Concurrency and Executor Framework
• Typesafe Enums
Java 8 Features
• Java 8 provides following features for Java
Programming:
• Default methods,
• Static methods in interface,
• Functional interfaces,
• Lambda expressions,
• Stream API,
• Collectors class,
• Nashorn JavaScript Engine,
• Parallel Stream with Parallel Processing and
Concurrency
• Type and Repating Annotations,
New in Interfaces
• Default methods,static methods and functional
interface
• Normal Interface Problems so far
• Designing interfaces have always been a tough
job because if we want to add additional
methods in the interfaces, it will require change
in all the implementing classes. As interface
grows old, the number of classes implementing it
might grow to an extent that it’s not possible to
extend interfaces.
Java Interface Default Method

• For creating a default method in java interface, we need to use


“default” keyword with the method signature
• Eg:
• default void log(String str){ System.out.println("I1 logging::"+str); }
• Advantage: when a class will implement Interface1, it is not
mandatory to provide implementation for default methods of
interface. This feature will help us in extending interfaces
• Disadvantage: Diamond Problem would arise. if a class is
implementing both Interface1 and Interface2 and doesn’t
implement the common default method, compiler can’t decide
which one to chose.
• Java interface default methods are also referred to as Defender
Methods or Virtual extension methods.
Java Interface Static Method

• Java interface static method is similar to default method except that


we can’t override them in the implementation classes.
• Java interface static methods are good for providing utility
methods, for example null check, collection sorting etc.
• Java interface static method helps us in providing security by not
allowing implementation classes to override them.
• We can’t define interface static method for Object class methods,
we will get compiler error as “This static method cannot hide the
instance method from Object”. This is because it’s not allowed in
java, since Object is the base class for all the classes and we can’t
have one class level static method and another instance method
with same signature.
Java Functional Interfaces

• An interface with exactly one abstract method


is known as Functional Interface.
• A new annotation @FunctionalInterface has
been introduced to mark an interface as
Functional Interface.
• @FunctionalInterface annotation is a facility
to avoid accidental addition of abstract
methods in the functional interfaces.
• Examples
Lambda Expressions
• Reduced Lines of Code
One of the clear benefit of using lambda
expression is that the amount of code is reduced,
we can create instance of a functional interface
using lambda expression rather than using
anonymous class.
• Sequential and Parallel Execution Support
• Another benefit of using lambda expression is
that we can benefit from the Stream API
sequential and parallel operations support.
Syntax of Lambda Expression
• Java Lambda Expression Syntax
• (argument-list) -> {body}
• Java lambda expression is consisted of three
components.
• 1) Argument-list: It can be empty or non-empty
as well.
• 2) Arrow-token: It is used to link arguments-list
and body of expression.
• 3) Body: It contains expressions and statements
for lambda expression.
Stream API
• The Stream API is used to process collections of
objects. A stream is a sequence of objects that
supports various methods which can be pipelined
to produce the desired result.
• The features of Java stream are –
• A stream is not a data structure instead it takes
input from the Collections, Arrays or I/O
channels.
• Streams don’t change the original data structure,
they only provide the result as per the pipelined
methods.
Different Operations On Streams

Intermediate Operations:
• map: The map method is used to map the items in the collection to
other objects according to the Predicate passed as argument.
List number = Arrays.asList(2,3,4,5);
List square = number.stream().map(x-
>x*x).collect(Collectors.toList());
• filter: The filter method is used to select elements as per the
Predicate passed as argument.
List names = Arrays.asList("Reflection","Collection","Stream");
List result = names.stream().filter(s-
>s.startsWith("S")).collect(Collectors.toList());
• sorted: The sorted method is used to sort the stream.
List names = Arrays.asList("Reflection","Collection","Stream");
List result = names.stream().sorted().collect(Collectors.toList());
• Terminal Operations:
• collect: The collect method is used to return the result of the intermediate
operations performed on the stream.
List number = Arrays.asList(2,3,4,5,3);
Set square = number.stream().map(x->x*x).collect(Collectors.toSet());
• forEach: The forEach method is used to iterate through every element of
the stream.
List number = Arrays.asList(2,3,4,5);
number.stream().map(x->x*x).forEach(y->System.out.println(y));
• reduce: The reduce method is used to reduce the elements of a stream to
a single value.
The reduce method takes a BinaryOperator as a parameter.List number =
Arrays.asList(2,3,4,5);
int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);
Parallel Processing and Concurrency

• What is concurrency?
• Concurrency is the ability to run several programs
or several parts of a program in parallel. If a time
consuming task can be performed
asynchronously or in parallel, this improve the
throughput and the interactivity of the program.
• A modern computer has several CPU’s or several
cores within one CPU. The ability to leverage
these multi-cores can be the key for a successful
high-volume application.
• The Stream API enables developers to create
the parallel streams that can take advantage
of multi-core architectures and enhance the
performance of Java code. In a parallel stream,
the operations are executed in parallel and
there are two ways to create a parallel stream.
• Using the parallelStream() method on a
collection
• Using the parallel() method on a stream
• Parallel Streams must be used only
with stateless, non-interfering, and associative
operations i.e.
• A stateless operation is an operation in which the
state of one element does not affect another
element
• A non-interfering operation is an operation in
which data source is not affected
• An associative operation is an operation in which
the result is not affected by the order of operands
When to use Parallel Streams

• They should be used when the output of the operation is


not needed to be dependent on the order of elements
present in source collection (i.e. on which the stream is
created)
• Parallel Streams can be used in case of aggregate functions
• Parallel Streams quickly iterate over the large-sized
collections
• Parallel Streams can be used if developers have
performance implications with the Sequential Streams
• If the environment is not multi-threaded, then Parallel
Stream creates thread and can affect the new requests
coming in
New Date-Time API in Java 8

• New date-time API is introduced in Java 8 to


overcome the following drawbacks of old date-
time API :
• Not thread safe : Unlike old java.util.Date which
is not thread safe the new date-time API
is immutable and doesn’t have setter methods.
• Less operations : In old API there are only few
date operations but the new API provides us with
many date operations.
New In Datetime API
• Using LocalDate, LocalTime and LocalDateTime
• Working with LocalTime
• Working with LocalDateTime
• Using ZonedDateTime API
• Using Period and Duration
• The Period class represents a quantity of time in terms of years,
months and days and the Duration class represents a quantity of
time in terms of seconds and nano seconds
• 590 different zones and the ZoneId are used to represent them as
follows.
• In this code snippet we create a Zone for Paris:

• ZoneId zoneId = ZoneId.of("Europe/Paris");


• Using Optional instead of Null
• Java Type Annotations
• if you want to avoid NullPointerException in your code, you can
declare a string variable like this:
• @NonNull String str;
• Following are the examples of type annotations:
• @NonNull List<String>
• List<@NonNull String> str
• Arrays<@NonNegative Integer> sort
• @Encrypted File file
• @Open Connection connection
• void divideInteger(int a, int b) throws @ZeroDivisor ArithmeticExce
ption
Java Repeating Annotations

• Java allows you to repeating annotations in


your source code. It is helpful when you want
to reuse annotation for the same class. You
can repeat an annotation anywhere that you
would use a standard annotation.
• Declare a repeatable annotation type
• Declare the containing annotation type
• Declaring of repeatable annotation type must
be marked with the @Repeatable meta-
annotation.
• The value of the @Repeatable meta-
annotation, in parentheses, is the type of the
container annotation that the Java compiler g
• Containing annotation type must have a value
element with an array type. enerates to store
repeating annotations.
How long should an Annotation be
retained
• A retention policy determines at what point annotation should be
discarded.
• Java defined 3 types of retention policies through
java.lang.annotation.RetentionPolicy enumeration. It has SOURCE,
CLASS and RUNTIME.
• Annotation with retention policy SOURCE will be retained only with
source code, and discarded during compile time.
• Annotation with retention policy CLASS will be retained till
compiling the code, and discarded during runtime.
• Annotation with retention policy RUNTIME will be available to the
JVM through runtime.
• The retention policy will be specified by using java built-in
annotation @Retention, and we have to pass the retention policy
type.
• The default retention policy type is CLASS.
Nashorn JavaScript Engine

• With Java 8, Nashorn, a much improved javascript


engine is introduced, to replace the existing
Rhino. Nashorn provides 2 to 10 times better
performance, as it directly compiles the code in
memory and passes the bytecode to JVM.
• jjs
• For Nashorn engine, JAVA 8 introduces a new
command line tool, jjs, to execute javascript
codes at console.
• jjs in Interactive Mode
• Open the console and use the following
command.
Java 11 New Features
• LOCAL PARAMETER TYPE INFERENCE FOR
LAMBDA EXPRESSIONS

• JDK 11 allows var keyword to be used when


declaring the formal parameters of implicitly
typed lambda expressions:
• Function<String, String> append = (var string) ->
string + " World"; String appendedString =
append.apply("Hello");
System.out.println(appendedString);
• The JDK 11 also allow annotations to be
added to lambda’s parameters without having
to write full variable type name. Let’s take a
look at with example:
• Function<String, String> append = (@NonNull
var string) -> string + " World"; String
appendedString = append.apply("Hello");
System.out.println(appendedString);
2. USAGE OF STRING:: REPEAT
METHOD TO COPY A STRING
• var str = "abc";
• var repeated = str.repeat(3);
• System.out.println(repeated);
CREATE A PATH WITH
PATH::OF METHOD
• In Java 11 we can
use Paths::get and Path::of methods
• Path googlePath =
Path.of(URI.create("www.google.com"))
• Path studentFilePath =
Path.of("/home/Students/student.txt")
FILES::READSTRING AND
FILES::WRITESTRING FOR FILE
READING AND WRITING
• String studentFileContent =
Files.readString(Path.of("student.txt"))
• String modifiedStudentContent =
addNewSubject(studentFileContent)
• Files.writeString(Path.of("student-
mod.txt"),modifiedStudentContent)

USAGE OF OPTIONAL::ISEMPTY
INSTEAD OF ISPRESENT
• val optional: Optional<String> =
Optional.empty()
• if (optional.isEmpty) {
• // value is empty
• }
HANDLING REGULAR EXPRESSIONS
WITH PATTERN::ASMATCHPREDICATE
• asPredicate: Under the hood,
the asPredicate method
called matcher(s).find().
• asMatchPredicate: It will checks if the entire
string conforms to this regular expression. This
method behaves like matcher(s).matches().
• USAGE OF THE STRIP, STRIPLEADING, AND
STRIPTRAILING
• . CONVERT COLLECTIONS TO ARRAYS USING
COLLECTION::TOARRAY
• Studen[] studentArray =
studentList.toArray(new Student[0]);
TypeSafe Enums
• enums are implicitly final subclasses
of java.lang.Enum
• if an enum is a member of a class, it's
implicitly static
• new can never be used with an enum, even
within the enum type itself
• enum constants are implicitly public static final
• the order of appearance of enum constants is
called their "natural order"
Creating type-safe enumerations in
older versions of Java
• Prior to JDK 1.5, type-safe enumerations can be
implemented as a regular Java class. They come
in various styles, corresponding to the features
they include:
• a List of VALUES, for iterating over all values of
the enumeration
• implementing a valueOf method for parsing text
into an enumeration element
• implementing Comparable
• implementing Serializable
Different Ways to create TypeSafe
Enums
Another Way
Another Way
Executor Service
• ExecutorService is a framework provided by
the JDK which simplifies the execution of tasks
in asynchronous mode. Generally
speaking, ExecutorServiceautomatically
provides a pool of threads and API for
assigning tasks to it.
• create a thread-pool with 10 threads
• ExecutorService executor =
Executors.newFixedThreadPool(10);
• Directly Create an ExecutorService
• ExecutorService executorService =
• new ThreadPoolExecutor(1, 1, 0L,
TimeUnit.MILLISECONDS,
• new LinkedBlockingQueue<Runnable>());
Assigning Tasks to the ExecutorService
• submit() submits a Callable or a Runnable task to an ExecutorService and
returns a result of type Future.
• Future<String> future =
• executorService.submit(callableTask);
• invokeAny() assigns a collection of tasks to an ExecutorService, causing
each to be executed, and returns the result of a successful execution of
one task (if there was a successful execution).
• String result = executorService.invokeAny(callableTasks);
• invokeAll() assigns a collection of tasks to an ExecutorService, causing each
to be executed, and returns the result of all task executions in the form of
a list of objects of type Future.

• List<Future<String>> futures = executorService.invokeAll(callableTasks);


Shutdown an Executor Service
• executorService.shutdown();
• Thank You

Вам также может понравиться