Module 3

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 60

MODULE 3

OBJECT CLASS:
1. It is an inbuilt java library class.
2. The object class is present in the “java.lang” package.
3. It is the super most class in java and every class is either directly or indirectly a
child of object class.
4. It defines some of the most common methods needed by all java programs.
METHODS OF OBJECT CLASS:
1.toString()
2.hashCode()
3.equals()
4.wait()
5.wait(long a)
6.wait(long a, long b)
7.notify()
8.notifyAll()
9.finalize()
10.clone()
11.getClass()
toString():
1. Method declaration:
public String toString()
2. The toString() method used to get string representation of the object .
String representation: fully qualified Class name + @ + hexadecimal pseudo address.
3. programmer can override the toString() method and change the
implementation.
hashCode():
1. Method declaration: public int hashCode()
2. The hashCode() method used get unique integer ID of the object assigned by
JVM.
3. Programmer can override the hashCode() method and change the
implementation.
4. This integer ID is the decimal representation of the hexadecimal pseudo
address.
equals():
1. Method declaration: public boolean equals(object obj)
2. The equals() method is used to compare the content between two object.
3. We have to override this method to perform equality comparison like
using “==” operator.

Wait(), wait(long a), wait(long a, int b):


1. wait() method is overloaded in three version in object class
2. Method declaration:
1. public final void wait()
2. public final void wait(long a)
3. public final void wait (long a, int b)
3. wait() method is used to pause program execution internally by the JVM
till the occurrence of an event or for a certain time interval.
notify():
1. Method declaration: public final void notify()
2. The notify() method is used to notify a particular thread about the
occurrence of an event.
notifyAll():
1. Method declaration: public final void notifyAll()
2. The notifyAll() method is used to notify all the occurrence of an
event.
Finalize():
1. Method declaration: protected void finalize()
2. Before destroying an object and removing it from the heap area the
garbage collector executes before the finalize() method.
3. The finalize() method contains clean up code that has to be
executed before an object is destroyed.
Clone():
1. Method declaration: protected object clone()
2. The clone() method is used to create an exact replica of the current
object.
3. Clone is a restricted process and has to be controlled.
1. Cloning works only on objects of class that implements cloneable.
2. It is mandatory to perform Downcasting on all cloned copies.
3. Cloning is risky and may cause CloneNotSupportedException.
//Cloning:
1. Creating an exact replica of the current object we can perform cloning using
clone() method.

Cloned object
Original object Object class
GetClass():
1. Method declaration: public final String getClass()
2. The getClass() method return the fully qualified class name of the
current instance.
Exception handling:
1. What is exception?
an exception is an unexpected event that occurs at the runtime
and causes the program to terminate abnormally.
2. It will be happened Scenario like:
1. Dividing a number by zero.
2. Accessing member with null reference
3. Trying to reach an invalid array index etc.
Type of exception:
In java exceptions are widely classified into two categories.
1. Checked exceptions:
1. looking at the source code if compiler can detect that code is risky and may cause
an exception it is called a checked exception.
2. Since it is detected, so It is mandatory to handle the checked exception
eg: IOException, ClassNotFoundException etc,
1. Unchecked exception:
1. Looking at the source code if compiler cannot detect that code is risky and may
cause an exception it is called a unchecked exception.
2. since it is not detected so it is not mandatory to handle the unchecked exceptions.
eg:ArithmeticException, NullPointerException etc.
1. When exception occurs the object is created by the JVM to
represent the exception.
2. There is inbuilt library class to represent each and every Exception
in java.
3. The JVM then expects at the programmer to handle the exception.
4. If the programmer fails to handle the exception JVM call the default
handler.
Exception hierarchy:

Object

Throwable

Exception

Run time Exception IOException SqlException InterruptException


1. ArithmeticException 1. FileNotFoundException
2. NullPointerException 2. EOFException
3. ClassCastException
4. IndexOutOfBound
try, catch and finally:
1. A programmer can handle an exception in java using the blocks.
1. try
2. catch
3. finally
Try block:
1. The risky instructions are written in the try block.
2. Every try block should be followed by at least one catch block.
3. In try block when ever the exception occurs, immediately the
control will be traveled from try to catch block.
Catch block:
1. The catch block is written after the try block.
2. The catch block executes only when there is an exception.
3. The catch block takes the exception object as an argument which is
created by JVM.
4. We can write multiple catch blocks after a single try block.
Finally block:
1. Finally is a special block used in exception handling.
2. It is a written after the try and catch block.
3. Finally block contains code that has to mandatorily execute.
Default handler:
1. The JVM calls the default handler when the programmer fails to
handle an exception.
2. The default handler performs the following actions
1. Stops program execution
2. Performs stack trace
3. Display details of exception
Throws keyword:
1. Throws keyword is used in the method declaration.
2. It is used to delegate the task of exception handling to the calling
method.
3. We can delegate multiple exceptions task using the throws keyword
throws throw

1. Used in method declaration. 1. Used in method definition.


2. Used to delegate the task of 2. Used to manually throw the
exception handling. exception object.
3. We can delegate multiple 3. We can throw only one
exception. exception object at a time
Creating custom exception:
A java programmer can declare and create customized exception using
the following steps.
1. Creating a class that extends Exception.
2. Design trigger logic for exception event.
3. Handle the exception event when it occurs
String:
1. Definition: in java string is a library class that is used to represent a
sequence of characters.
2. In java we represent string values using String class objects.
3. We can create string class object in 2 ways
1. String literals
2. String object via new keyword
4. String class is final class.
5. When using both literal and new keyword approach's object of
string class is created in the memory.
Memory with string object:
1. String object allocates memory in a special part of the heap area is
called as the string pool.
2. The string pool is internally divided into two segment
1. Constant pool
2. Non constant pool
3. When String object is created using literals that’s memory will be
allocated in the constant pool and the JVM will check the duplicates
in the constant pool before allocating memory.
4. When String object is created using new keyword that’s memory
will be allocated in the non constant pool and here the JVM will not
check duplicates in the non constant pool before allocating memory.
OVERRIDEN METHOD OF OBJECT CLASS:
1. String class inherits all the method of object class and it overrides
1. toString(): this method is overridden to return the string value.
2. hashCode():this method is overridden to return the Unicode value of the
current string.
3. Equals():this method is overridden to compare 2 string values for equality.
STRING OBJECTS ARE COMPARABLE:
1. String class implements an Interface called comparable hence string
class objects can be compared.
2. We can compare string class objects using the compareTo() method
inherited from comparable.
3. Based on the value returned on comparison we can compare values.
1. +ve value(current string after given string)
2. -ve value(current string before given string)
3. 0 value(current string equals to given string)
STRING CLASS OBJECTS ARE IMMUTABLE:
1. Once we create a string object in memory we cannot modify it in
any way.
2. If we try to modify a string after creating it will internally create a
new string objects.
3. Because of we cannot modify after creating it is called an
immutable class.
4. This is a drawback because number of object creation is increased
therefore memory space will be increased.
STRING BUFFER AND STRING BUILDER:
1. These two library classes can be used as an alternate to string class.
2. Both StringBuffer and StringBuilder are inbuilt library class that are
present in “java.lang” package.
3. We can create the object for StringBuffer and StringBuilder using
the new keyword only.
1. StringBuffer sb1=new StringBuffer(“Qspiders”);
2. StringBuilder sb2=new StringBuilder(“Qspiders”);
4. StringBuffer and StringBuilder are both final class and mutable.
WRAPPER CLASS:
1. They are inbuilt library class that are present in “java.lang” package.
2. Wrapper class are used to support each and every primitive
datatypes in java.
3. Using wrapper class we can perform following three operation.
1. Boxing
2. Unboxing
3. Parsing
4. Boxing: the process of representing primitive as a wrapper class
object.
5. Unboxing: the process of representing a wrapper class object as a
primitives
6. Parsing: the process of extracting the primitive value embedded in a
string.
Parsing:
1. Extracting a primitive value that is embedded in a string is called as
parsing.
2. We can do parsing with help of parser method.
3. Parser method is provided inside each wrapper class.
wrapper parser

1. Byte 1. parseByte()
2. Short 2. parseShort()
3. Integer 3. parseInteger()
4. Long 4. parseLong()
5. Float 5. parseFloat()
6. Double 6. parseDouble()
7. Character 7. No parser
8. Boolean 8. parseBoolean()
File handling:
1. File handling: it is the concept of manipulating the file and folder
present in the file system.
File manipulating:
1. The common file manipulation are
1. Create a file
2. Create a folder
3. Delete a folder
4. Write data to a file
5. Read data from a file
2. Java provides a feature rich file handling API
3. All java classes related to file handling are present in “java.io”
package.
File class:
1. It is an inbuilt library class
2. It is present in “java.io” package
3. File class helps the programmer to perform some basic file
manipulation.
4. Some of the files class methods are
1. exist()
2. mkdir()
3. createNewFile()
4. delete()
Writing data to a text file:
Write() Flush()
fileWriter Demo.txt
Writer.java
close()

Steps:
1. Create an instance of file writer.
2. Write data to file writer object using write() method.
3. Transfer data to physical file using flush() method.
4. Close fileWriter object by calling close() method.
Reading data from a text file:
ABC
read()
abc Reader.java
123 FileReader
Demo.text
close()

steps:
1. Create an instance of fileReader.
2. Read data from file using read() method
3. Close file reader instance using close() method.
Collection framework:
What is a collection : a collection is a group of object that are stored
together.
Collection framework contains inbuilt class and interface that helps the
programmer to store a group of object together.
And there are commonly three types of collection
1.list 2.queue 3.set
COLLECTION INTERFACE:
1. Collection Interface is the root of the collection hierarchy.
3. It is present in the java.util package.
4. It was Introduced in version 1.2.
5. All collection objects are growable in nature.
6. Collection Interface declares the most common methods that are applicable
for any collection object.
Some methods defined by the collection interface are :
1. boolean add(Object o)
2. boolean addAll(Collection c)
3. boolean remove(Object o)
4. boolean removeAll(Collection c)
5. boolean retainAll(Collection c)
6. void clear()
7. boolean contains(Object o)
8. boolean containsAll(Collection c)
9. boolean isEmpty()
10. int size()
11. Iterator iterator()

NOTE: There is no concrete class that directly


implements collection Interface directly.
LIST INTERFACE
1. It is the Child of collection interface.
2. Here the three classes that implements list interface.
ARRAYLIST:
1. ArrayList is the child of list Interface.
2. Its basic data structure is resizable array and its Best Suited Operation is retrieval.
3. Here the Duplicate values and Heterogeneous elements are both allowed
4. Insertion Order is preserved
5. null Insertion is possible.
6. Default capacity of arrayList is 10.
7. When array list becomes full New capacity will be created using the formula
int newCapacity=(OldCapacity * 3/2)+1
8. Which is present in java.util package.
9. It was introduced in jdk version 1.2
10. ArrayList implements Serializable Cloneable and RandomAccess.
VECTOR:
1. Vector is child of list interface.
2. The basic data structure is resizable array and the best suited operation is
retrieval.
3. Duplicate values and Heterogeneous elements are both allowed
4. Insertion order is preserved
5. Null insertion is possible
6. Default capacity of vector is 10
7. When vector becomes full the new capacity is created using the formula int
new capacity= old capacity*2
8. It is present in java.util package
9. Vector was introduced in v1.0
10. Vector implements serializable, cloneable and RandomAccess.
LinkedList:
1. LinkedList is child of List Interface.
2. Its basic data structure is doubly linked list and best suited operation is
insertion and deletion.
3. Duplicate values and Heterogeneous elements are both allowed.
4. Insertion Order is Preserved.
5. Null Insertion is possible.
6. It is present in java.util package.
7. It was introduced in jdk version 1.2
8. It implements Serializable and Cloneable.
Priority Queue:
1. Priority queue is the child of queue interface.
2. Its basic data structure is Priority Based Queue and the Best Suited Operation is
priority based service.
3. Duplicate values are allowed and Heterogeneous elements are not allowed.
4. Insertion Order is not Preserved.
5. Null Insertion is not possible.
6. It is present in java.util package.
7. It was introduced in jdk version 1.5
8. It implements Serializable and Cloneable.
HASHSET:
1. HashSet is the child of Set Interface.
2. Its basic data Structure is HashTable and The Best Suited Operation is Searching.
3. Duplicate values are not allowed and Heterogeneous elements are allowed.
4. Insertion Order is not Preserved.
5. One null insertion is possible.
6. Default Capacity of HashSet is 16 and its fillratio is 0.75f
7. It is present in java.util package.
8. It was introduced in v1.2
9. HashSet implements Serializable and Cloneable.
LINKEDHASHSET:
1. It is the child class of HashSet.
2. The Underlying DataStructure is HashTable +LinkedList and best suited
operation is developing cache Based Applications.
3. Duplicate values are not allowed and Heterogeneous elements are allowed.
4. Insertion order is preserved.
5. One null insertion is possible.
6. Default Capacity of HashSet is 16 and its fillratio is 0.75f
7. it is present in java.util package.
8. It was introduced in v1.4.
9. HashSet implements Serializable and Cloneable.
TREESET:
1. TreeSet is the child of Set Interface.
2. Its Underlying DataStructure is Balanced Tree and Best Suited operation is
Sorting
3. Duplicate values and heterogeneous elements are both not allowed.
4. Insertion order is not preserved.
5. Null Values are not allowed.
6. It is present in the java.util package.
7. It was introduced in v1.2
8. TreeSet implements Serializable and Cloneable.
HASHMAP:
1. HashMap is child class of Map.
2. The Underlying DataStructure is HashTable and best suited operation is
searching.
3. Duplicate Keys are not allowed and Duplicate values are Allowed.
4. Heterogeneous elements are allowed for both Key and Value.
5. Insertion Order is Not Preserved.
6. We can have one null key but multiple number of null values
7. All Elements are Inserted into the HashMap based on the HashCode of
Keys.
8. The default size of HashMap is 16 and its fillratio is 0.75
9. It is present in java.util package.
10. It was introduced in v1.2.
11. HashMap implements Serializable and cloneable.
LinkedHashMap:
1. LinkedHashMap is the child of HashMap.
2. The Underlying data structure is HashTable+LinkedList and the Best Suited
operation is developing cache based application.
3. Duplicate Keys are not allowed, but values are allowed
4. Heterogeneous keys and values are allowed
5. Insertion order is Preserved.
6. We can have one null key but multiple number of null values
7. Default capacity is 16 and its fillratio is 0.75.
8. It is Present in java.util package.
9. It was introduced in jdk v1.4.
10. It implements serializable and cloneable.
TREEMAP:
1. TreeMap is the child class of Map.
2. The Underlying DataStructure is Red-Black Tree and the Best Suited Operation
is Sorting.
3. Duplicate Keys are not allowed, but duplicate values are allowed.
4. Heterogeneous keys are not allowed, but Heterogeneous values allowed.
5. Insertion Order is not preserved.
6. Null key is not allowed, but null values are allowed.
7. It is present in the java.util package.
8. It was introduced in v1.2
9. TreeMap also implements Serializable and Cloneable.
Iterator:
1. Iterator is an interface present in java.util package
2. It is used to retrieve objects from the collection.
3. Each collection internally provides implementation for Iterator.
4. We can access this implementation by calling the iterator methods
in every collection.
5. Iterator provides the following methods.
1. hasNext():used to check if an Object is present in current location.
2. next():used to retrieve object from current location.
3. remove():used to remove an Object from current collection.
GENERIC:
1. Generic was introduced in V1.5
2. Generic is used to provide type safety in collection
3. ArrayList<product>al=new ArrayList<product>();
(type safe<-----only objects of type ptoduct)
4. HashSet<string>hs=new HashSet<string>();
(type safe <------only string)
5. LinkedHashMap<integer,string>ref=new LinkedHashMap<integer,string>();
typesafe (keys-integers)(values-string)
Threads:
What is a thread?
1. A thread is a light weight process.
2. Threads are used to perform multitasking at a program level.
Threads in java:
1. Java programming provides inbuilt support for multithreading.
2. Whenever a java program begin execution the JVM internally creates 3 new
threads
1. Thread scheduler
2. Garbage collector
3. Main thread
3. Garbage collector and thread scheduler are daemon thread.
4. Daemon thread: a thread which is not under the programmer control is called
as a daemon thread.
5. As a java programmer can we create threads in two ways
1. By extending thread class
2. By implementing runnable interface
6. Using multi threading will help enhance the speed of execution a program.
Extending thread class:
1. Create a java class that extends “thread” class.
2. Override run() method in thread class, the run() method should
contain the task to be executed by the thread.
3. Create an object of target class
4. Call start() method to begin the execution of thread.
Implementing runnable interface:
1. Create a java class that implements runnable interface
2. Override run() of runnable interface
3. Create an object of thread class by passing target reference
4. Call start() method.
Role of “start()” method:
1. Start() method is when an actual thread is created in the java
memory space.
2. When start() method in called it performs the following tasks
1. Registers thread object created with jvm
2. Allocates resources needed for execution
3. Internally call run() method
Synchronization:
1. Synchronization is the concept of making a method with thread safe.
2. In java we can do synchronization using the “synchronized” keyword
3. When a method is created with synchronized keyword it can be
accessed by only one thread at a time to making it thread safe.
Thread sleep():
1. Sleep() is a static method present in the thread class
2. Sleep() method is used by the programmer to pause program
execution for a certain time interval
3. Sleep() method is risky and may cause interrupted execution.
Thread life cycle:

waiting wait()

start() run()
new runnable running end

sleep()

sleeping
Thread life cycle:
1. New: in this state thread is a newly created object
2. Runnable: in this state thread is ready to begin execution
3. Running: in this state thread is currently under execution
4. Waiting: in this state thread execution is paused by jvm
5. Sleeping: in this state thread execution is paused by programmer.
6. Dead: in this state the thread will be completed execution

You might also like