8. Class Loader
• The Java Classloader is a part of the Java
Runtime Environment that dynamically loads
Java classes into the Java Virtual Machine on
demand (i.e. Lazy Loading)
• When the JVM is started, three class loaders
are used:
– Bootstrap class loader (native implementation)
– Extensions class loader (loads code in extensions
dir)
– System class loader (loads code found on
java.class.path)
9.
10. Custom Class Loaders
• The Java class loader is written in Java. It is
therefore possible to create your own class
loader without understanding the finer details
of the Java Virtual Machine
• This makes it possible (for example):
1. To load or unload classes at runtime
2. To change the way the byte code is loaded
3. To modify the loaded byte code
11.
12. Building a SimpleClassLoader
• A class loader starts by being a subclass of
java.lang.ClassLoader
• The only abstract method that must be
implemented is loadClass()
13. Building a SimpleClassLoader
• The flow of loadClass() is as follows:
– Verify class name
– Check to see if the class requested has already
been loaded
– Check to see if the class is a "system" class
– Attempt to fetch the class from this class loader's
repository
– Define the class for the VM
– Resolve the class
– Return the class to the caller
19. Object Class
• The Object class is the parent class of all the
classes in java by default. In other words, it is
the topmost class of java
20. Object Class
public final Class getClass()
returns the Class class object of this
object. The Class class can further be used
to get the metadata of this class.
public int hashCode()
returns the hashcode number for this
object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws
CloneNotSupportedException
creates and returns the exact copy (clone)
of this object.
public String toString()
returns the string representation of this
object.
protected void finalize()throws
Throwable
is invoked by the garbage collector before
object is being garbage collected.
21. Object Class
public final void notify()
wakes up single thread, waiting on this
object's monitor.
public final void notifyAll()
wakes up all the threads, waiting on this
object's monitor.
public final void wait(long
timeout)throws InterruptedException
causes the current thread to wait for the
specified milliseconds, until another
thread notifies (invokes notify() or
notifyAll() method).
public final void wait(long timeout,int
nanos)throws InterruptedException
causes the current thread to wait for the
specified miliseconds and nanoseconds,
until another thread notifies (invokes
notify() or notifyAll() method).
public final void wait()throws
InterruptedException
causes the current thread to wait, until
another thread notifies (invokes notify()
or notifyAll() method).
24. Collections
• Collections in java is a framework that provides
an architecture to store and manipulate the
group of objects
• All the operations that you perform on a data
such as searching, sorting, insertion,
manipulation, deletion etc. can be performed by
Java Collections
• Java Collection simply means a single unit of
objects. Java Collection framework provides
many interfaces (Set, List, Queue, etc.) and
classes (ArrayList, Vector, LinkedList,, HashSet,
LinkedHashSet, TreeSet, etc.)
28. Collection Interface
public boolean add(Object element) is used to insert an element in this collection.
public boolean addAll(Collection c)
is used to insert the specified collection
elements in the invoking collection.
public boolean remove(Object element)
is used to delete an element from this
collection.
public boolean removeAll(Collection c)
is used to delete all the elements of specified
collection from the invoking collection.
public boolean retainAll(Collection c)
is used to delete all the elements of invoking
collection except the specified collection.
public int size()
return the total number of elements in the
collection.
public void clear()
removes the total no of element from the
collection.
public boolean contains(Object element) is used to search an element.
29. public boolean containsAll(Collection c)
is used to search the specified collection in
this collection.
public Iterator iterator() returns an iterator.
public Object[] toArray() converts collection into array.
public boolean isEmpty() checks if collection is empty.
public boolean equals(Object element) matches two collection.
public int hashCode() returns the hashcode number for collection.
30. Java.util.Collections Class
• The java.util.Collections class consists
exclusively of static methods that operate on
or return collections
31. Sample Methods in Collections class
• static <T> int binarySearch(List<? extends
Comparable<? super T>> list, T key)
This method searches the specified list for the
specified object using the binary search
algorithm
• static <T> int binarySearch(List<? extends T>
list, T key, Comparator<? super T< c)
This method searches the specified list for the
specified object using the binary search
algorithm.
32. Sample Methods in Collections class
• static <T> T min(Collection<? extends T> coll,
Comparator<? super T> comp)
This method returns the minimum element of
the given collection, according to the order
induced by the specified comparator.
• static <T> T max(Collection<? extends T> coll,
Comparator<? super T> comp)
This method returns the maximum element of
the given collection, according to the order
induced by the specified comparator.
33. Sample Methods in Collections class
• static void reverse(List<?> list)
This method reverses the order of the elements
in the specified list.
• static <T> void sort(List<T> list, Comparator<?
super T> c)
This method sorts the specified list according to
the order induced by the specified comparator.
34. Comparable Interface
• Comparable interface is used to order the
objects of user-defined class
• public int compareTo(Object obj): is used to
compare the current object with the specified
object.
35. Comparator Interface
• Comparator interface is used to order the
objects of user-defined class
• public int compare(Object obj1,Object obj2):
compares the first object with second object
37. Why?
• Beginners usually start off by returning error
codes
• The inner working of your program should not
have a protocol
38. From the Clean Code book
if (deletePage(page) == E_OK) {
if (registry.deleteReference(page.name) == E_OK) {
if (configKeys.deleteKey(page.name.makeKey()) == E_OK){
logger.log("page deleted");
} else {
logger.log("configKey not deleted");
}
} else {
logger.log("deleteReference from registry failed");
}
} else {
logger.log("delete failed");
return E_ERROR;
}
Bad
try {
deletePage(page);
registry.deleteReference(page.name);
configKeys.deleteKey(page.name.makeKey());
}
catch (Exception e) {
logger.log(e.getMessage());
}
Good
Motive:
Error Codes awful nested IFs
But using Exceptions now, we can read the normal flow
39. Three Categories of Exceptions(1/3)
1. Checked exceptions: is an exception that
occurs at the compile time, these are also
called as compile time exceptions. These
exceptions cannot simply be ignored at the
time of compilation, the Programmer should
take care of (handle) these exceptions
40. Three Categories of Exceptions(2/3)
2. Unchecked exceptions: is an exception that
occurs at the time of execution, these are
also called as Runtime Exceptions, these
include programming bugs, such as logic
errors or improper use of an API. Runtime
exceptions are ignored at the time of
compilation
(e.g.ArrayIndexOutOfBoundsException and
NullPointerException).
41. Three Categories of Exceptions(3/3)
3. Errors: These are not exceptions at all, but
problems that arise beyond the control of the
user or the programmer. Errors are typically
ignored in your code because you can rarely
do anything about an error. For example, if a
stack overflow occurs, an error will arise.
They are also ignored at the time of
compilation
44. Catching an Exception(2/2)
• Since Java 7 you can handle more than one
exceptions using a single catch block, this
feature simplifies the code
45. Finally block
• The finally block follows a try block or a catch
block. A finally block of code always executes,
irrespective of occurrence of an Exception
• Using a finally block allows you to run any
cleanup-type statements that you want to
execute, no matter what happens in the
protected code
48. Java I/O
• Java I/O (Input and Output) is used to process
the input and produce the output based on
the input
• Java uses the concept of stream to make I/O
operation fast. The java.io package contains
all the classes required for input and output
operations
49. Stream
• A stream is a sequence of data. In Java a
stream is composed of bytes.
• In java, 3 streams are created for us
automatically. All these streams are attached
with console:
1. System.out: standard output stream
2. System.in: standard input stream
3. System.err: standard error stream
51. OutputStream class
• OutputStream class is an abstract class. It is
the superclass of all classes representing an
output stream of bytes. An output stream
accepts output bytes and sends them to some
sink
public void write(int)throws IOException:
is used to write a byte to the current
output stream.
public void write(byte[])throws
IOException:
is used to write an array of byte to the
current output stream.
public void flush()throws IOException: flushes the current output stream.
public void close()throws IOException:
is used to close the current output
stream.
52.
53. InputStream class
• InputStream class is an abstract class. It is the
superclass of all classes representing an input
stream of bytes.
public abstract int read()throws
IOException:
reads the next byte of data from the input
stream.It returns -1 at the end of file.
public int available()throws IOException:
returns an estimate of the number of
bytes that can be read from the current
input stream.
public void close()throws IOException: is used to close the current input stream.
54.
55. When to use what?
• For simple and primitive reads and writes, use
FileInputStream and FileOutputStream
• For writing byte array into multiple files, use
ByteArrayOutputStream and ByteArrayInputStream
• For reading data from multiple streams, use
SequenceInputStream
• Java FileWriter and FileReader classes are used to
write and read data from text files.
• Java Buffered Stream classes uses an internal buffer to
store data. It adds more efficiency than to write data
directly into a stream. So, it makes the performance
fast.
57. Serialization in Java
• Serialization in java is a mechanism of writing
the state of an object into a byte stream
• The reverse operation of serialization is called
deserialization.