Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 74

Core Java – Language Fundamentals

1. Exit can be used with labels to perform to similar to jump statement,


2. Core Java with OCJP/SCJP: Language Fundamentals Part-2 || Data Types part-1 16:04
Missing operator overloading, multiple inheritance, Primitive data types

Byte leftmost bit is sign, 0 is positive number, 1 negative number


+ve numbers represented in binary form directly
-ve number is represented in 2's complement form
Byte data type is best for File and network stream, if any other value set compile Error: possible loss of precision
expected :byte found : <the data type given>

Short is very rarely used data type, because its best for 16bit processor like 8085/86

For integer : error is integer number too large, because for long data type should be succeed with l(el)

Version 1.7 enhancement with respect to literals


1. Binary Literals are allowed to define Integral values, earlier it was only decimal, HEXA and octal
2. Usage of underscore between digits (only) of numeric literals double (Eg: d = 123_456.7_8_9)

8 byte long value can be assigned to 4 byte float because both are represented differently in memory

Int[] []a, []b; is invalid declaration, because compiler wont allow the second variable declaration with preceding
braces

Every class has its own class type which is part of the java system itself, such as [I for ubterger [S for short [Z for
boolean

1. Array loopholes:
2. Array can have size 0
3. Array can't have a negative size, no compiler error because compiler checks for a size in integer, but JVM while
allocating space it will have a runtime error, java.lang.NegativeArraySizeException
4. Array can be definecos with a character (that will be converted to its equivalent array value)
5. Array cant be defines with String, boolean, double float, integer, can be defines only with byte, short, integer and
char. Int a[] = new int['a'] is valid, the size is 97
6. If integer value is greater than 2147483647 then error, integer number too large
7. If we provide a array value too high it may result in JVM array size exceed error

Two Dimensional array creation


In java two dimensional array is not implemented as matrix type, sun people followed Array of arrays approach for
multi dimensional array creation, the main advantage is memory utilization will be improved.

When ever a reference variable is printed, internally to string will be called, that is implemented by default to
return the string in the form of Classname@hashcode in decimal form

Reference a null pointer exception to do any operation then we thorown as NullPointer Excemptin, ref following
code
Int[][] x= new int[2][];
SOP(x) => [[I@hexcode
SOP(x[0]) => null
SOP(x[0][0]) => runtime exception

Every Method in Final Class is final Method.

In multi dimension array length of variable is always the base size

Anonymous Array is an array is used for one time use eg total = this.sum(new int[] {10,20,30})

For interface arrays, as array elements its implementation class objects are allowed, but instantiation is not allowed

Element level promotions/conversion are not possible at array level, for eg char to int possible, but char array to int
not possible but Child type array can be promoted to parent type, (Narrow casting)

Array assigning to other array size no need to match because the elements are not copied just the reference
variables will be re-assigned, but the data type should match

Based om position of declaration and behavior variables are divided in to Instance, Static and local

Objects are stored in heap memory

Constructors are always called in downward hierarchy, The constructor of prime class, then first derived class and
next derived class etc

Late Binding is the method that the methods of classes are determined during the rutime, Since final method
cannot be overridden they can be resolved during the compile time, this method of resolving is early binding

Object class is the super class of all classes, it can be referred to any object in Java, Since array is implemented as
class in Java, they can be referred to Object class. When a object is printed, toString method of the object is called
automatically for return value.

Static Variables are created while class loading and destroyed when class unloading, so the scope is exactly same
as .class file. The Variable are stored in Method area, Local variable are stored in stack
When java program is run with java <classfile>
1. Load / Start JVM
2. Create & Start main thread
3. Locate .class file (if not found then exception in thread main, Class not found)
4. Load .class file
5. Execute main method
6. Unload .class file
7. Terminate main thread
8. Shutdown JVM

We can access static variable either by obj reference or class name, class name usage is recommended, but in the
same class its better access directly

For Static Variables JVM provide default values. The Static variable are also called as fields or class level variable
Instance and Static Variable is not thread-safe

Local Variables

Local variables are also considered as stack variable. They are generally created inside a function, constructor or a
block, They are called as local, Temporary, Stack, Automatic.

They are thread safe, if a block is called by multiple threads then multiple copy of local variables are created
Initialization is compulsory since JVM wont provide more support

Local variable should be initialized before using, Else Compiler error will trigger while using
Local variable if modifier is declared then it is not the default modifier, its applicable only for Class and Object only.

When array object is created, irrespective of scope (inst, stat, local) the array objects are initialized

VAR_ARG Methods (Variable number of arguments methods) 1.5 Version of Java


The methods which can take variable number of arguments without overloading a function, it can be declared as
follows m1(int… x), we can call with any number of int values, including 0 number.

If mix with normal parameter and vararg parameter, then vararg should be last parameter and only one vararg
parameter can appear.

M1(int …x, double…d) is invalid because two cararg parameter is present

We cant declare vraarg method and corresponding one dimensional array simeltaniously in a class

VarArg Methood has the least priority in java

We can replace all one dimensional array with vararg code not vice versa

M1(int[]…x) can be called with obj.m1(new int[]{1,2,3}, new int[]{5,6,7})

Main Method
It’s a strict definition but we can have flexibility with declaring array with var_arg , array name order of identifiers
Also can add final, syncronized and strictfp modifiers

If PSVMain method not available in child class but present in Parent, then while executing child the parent's main
method is called.

If PSVM is overridden in child, it is called as method hiding and not overriding

Order of execution of class


1. Identify static members
2. Execute static block and static members assignment
3. Check for main() availability
4. Execute main method, if not available no method main error.

Naming convention
Class name are generally noun and starts with Capital and following words are also starting with capital eg:
StringBuffer
Interface names are Adjectives and follow the same rule as Class
Methods are generally verb or Verb+noun combination, starts with lower class and following words are with initial
capital letter eg: getName(). This is called camel case convention
Variable names are nouns and follow the same rule as methods

Java bean is a simple java class with private properties and public setter and getter methods, Class name endind
with bean is not an official convention from Sun Microsystems

Syntax for public method


Method type should be public, return should be void and should contain at-least one argument

Coding Standard for Listeners


They listen for events and performs appropriate events

Syntax is public void addMyActionListener(myActionListener l)


Method name should be prefixed with add, To unregister remove instead of add

Operators

Nesting of increment or decrement is not allowed because once first operation it is considered as value not variable
Difference between b++ and b=b+1

All constants defined with final keyword will be replaced with actual values during compile time, for eg final int i =
10; SOP(i); will be translated to SOP(10) after compilation, so JVM will receive the constant value instead of
variable name, Also if an expression is there then the constant value of the expression will be generated during
compilation.
From 1.7 version on wards, we get a meaningful error if main method is missing
Element level promotions are not applicable at array level ( Char array cant be promoted to int array, but char
element can be promoted to int type where the ascii values are considered(
Child type array can be promoted to parent type array String[] to Object[]
Whenever arrays are assigned then only the reference is assigned, so no errors, but the data type and dimensions
should match
Execution order

1. Initialize static variables


2. Run static blocks (so in 1.6 version we can code without main method)
3. Run the main method if it is a prime class
Java coding standard
1. Start with package
2. Name the class with proper name
3. If a small work then we can use static method
4. Name the method based on operation
Primitive type values assignement
(byte/char) ==> short ==> int ==>long ==> float ==> double
Naming conventions
Classes are usually Nouns, Starts with upper case, every inner word are uppercase
Interface are usually Adjectives and follow the same as class
Methods are generally Verbs or Verb-Noun Starts with lower case, and every inner word starts with uppercase,
Also called as camel case conventions
Variables are generally nouns Starts with lower case, and every inner word starts with uppercase, Also called as
camel case conventions
Constants are generally nouns Generally names are upper-case and multiple words separated by underscore
Java Bean coding standards Java bean is simple java class, which always contains private members with getter and
setter methods
Java bean classes generally ends with word bean at the end, but it is not an official recommendation from Sun /
Oracle
Listeners
Method should be public void addMyActionListener(myActionListener l)
public void removeMyActionListener(myActionListener l)
Whenever arithmetic operation happens (+,-,/,*,%) the result is type of max(int, type of operator1, type of
ooperator 2... type of opertor x) in case if increment / decrement operator typecasting will be performed
automatically
Operators
1. Increment and Decrement
1. cant apply for constant like ++10, ++ (++x) are invalid
2. it can be applied for any primitive type except Boolean
3. SOP('a'+'b') ==> 195
4. If at-least one operator is string then the + operator acts as concatenation, if both are numbers then it acts as
arithmetic operator (10+20+"Senthil") ==> 30Senthil
in integral arithmetic byte, short, int, long there is no way to represent infinity, so if infinity is the result we get
arithmetic exception in integral arithmetic (10/0) RE: Arithmetic exp division by zero
in floating point arithmetic (double, float) there is way to represent infinity, (10/0.0)
For any X value including NaN the expressions of less, greater, equal returns false, only Not operator will return
true.
Relational operators limitations
1. We can apply relational operator for every primitive type except Boolean
2. Relational operators cant be performed to Objects
3. Nesting of relational operators can't be performed in a single validation (10 < 20 <30) is invalid since after executing
10 < 20 the expression becomes true < 30, which contradicts first rule
Equality operators == and !=
Can be applied on any data types
1. If Obj == Obj2 then both the variables are pointing to the same objectfire
2. If we compare two different Objects then we need some relation between the objects, for eg Java.lang.String ==
Java.object.thread
3. == operator is to check the reference comparison, where .equals() is for comparing the content
4. String s=null; System.out.println(s == null) returns true, though s is an object reference internal value is null
instanceof operator
The relationship between arguments is mandatory
Bit-wise Operator Applicable for Boolean and integral types
Operator ~ applicable for only Integral
Boolean complement operator(!) can be applied only to Boolean operator eg(! true / !false)
Short circuit operator && and ||
Difference as per the example in the table (eg if (cond1 =='a' & cond2=='b'){thenpart}else{Else part} if (cond1 =='a'
&& cond2=='b'){thenpart}else{Else part}
in both the above example code there are two conditions {cond1 =='a' & cond2=='b' } in the expression
&/| Operator &&/|| Operator
Both conditions will be executed even though The second condition will not be executed if the first condition
the first one fails for & fails, so it improves performance for &&
Both condition will be executed even though The second one will not be executed if the first result is true
first one returns true
Applicable for both Boolean and Integral Applicable only for Boolean
Type Casting operator
Implicit = >
1. Automatically done by Java compiler
2. Whenever smaller data type value to bigger data type variable implicit typecasting will be performed
3. Its also called as wide casting
4. No loss of data
Explicit =>
1. Manually specify the target
2. Bigger to smaller assignament
3. Also knows Narrow casting
4. Loss of data can occur
Assignment Operators
1. Simple assignment a=10
2. chain assignment a=b=c=d=10; arithmetic operation, it starts from right to left of the expression
3. compound assignment a+=10; Internal type casting will be performed automatically
The only possible ternary operator is conditional operator (10<20)?30:(40>30)?12:23
The new() operator is to create and Object, and to declare and create arrays.
Operator Precedence
public class LearnJava {
public static void main(String[] args) {
int y = 0;
y = m(1)+m(2)*m(3)/m(4)+m(5)*m(6);
System.out.println(y);
}
public static int m(int i)
{
System.out.println(i);
return i;
}
}
The output is 1 2 3 4 5 6 32
new vs newInstance
if we know the class name for the object we are creating then we use new() operator, if the class name is not
known then we use newInstance method of class Class is used.
in New operator we know the class name and we hard-code the class name in the code, if the class not found in
run-time then NoClassDefFoundErroris triggered
newInstance object should contain no constructor, if in case it is needed for constructor then a constructor with no
argument should be provided, If a constructor present with arguments and no arg constructor is not present then
we get an runtime exception. IE the newInstance method will always calls no arg constructor, so it is mandate to
have no arg constructor. So basically any servlet class should have no-arg constructor. If Class definition not found
then ClassNotFoundException will be triggered, which is a checked expression
new newInsance
its operator in Java Its a method in java.lang.class
we can use it to create a object if we know the name of the class we can use it to create a object if we don't
know the name of the class, and the calling class should extend Throws Exception
Class can have any number of arguments constructor Class should have a no arguments constructor, if not Run-
time Error : Instantiation Exception
At Run-time the .class file not available, we get NoClassDefFoundError, The error is unchecked At Run-time
the .class file not available, we get ClassNotFoundError, The error is checked
ClassNotFoundException NoClassDefFoundError
If Statically (Hard-coded) class is not found in run time the If Dynamic calling to create an object for a class
and that class not found by JVM then the error says the said class is not found
instanceof() vs isInstance()
instanceof isInstance()
Operator in Java Method in Java, and the calling class should define throws Exception
The Object definition is known in coding time The Object definition is known in run time
instanceof Class.forName(<Classname>).isInstance(<obj>). The passing class name should be of absolute paths
Flow Controls
1. Selection Statements
1. if - else
2. Switch ~ case ~ default
2. Iterative Statements
1. while
2. do ~ while
3. for ()
4. for each - Java 1.5 onwards
3. Transfer statements
1. break
2. continue
3. return
4. try ~ catch ~ finally
5. assert - Java 1.4 Version onwards
Selection statements
IF-ELSE
if (argument) { if in case condition is true) } else { in case argument is false } - Argument should always be
binary type, else compile time error, In-Compatible type, found int req boolean
int x = 10
if(x=20)
SOP ("Hello");
else
SOP("Hi");
The result is compile time error, incompatible type, expected boolean found int, because the argument result is
finally value of variable b which is 20 since it used assignment operator "=" not comparison operator "=="
if(true)
int x = 10;
Compile time error : Variable declaration not allowed here, because the scope of the variable declared cannot
going to be used anywhere because without curly braces, the scope of the variable ends immediately after
declaration, which is a waste of compiler and JVM resource, from 1.8 the message of the error is clear, in previous
versions the there will be 4 errors.
in if statement else part and curly braces are optional, without curly braces declarative statements are not allowed.
SWITCH ~ CASE
byte, short, char, int are Allowed
Boolean, long, float, double are not allowed
1. Boolean is not allowed because the maximum possible option is only two, its better to use if else since it
is more easily
2. an empty switch statement (with no case or default or anything inside the curly braces) is perfectly valid,
but we can write the logic only under a case or Default
3. the case expression should be a compiler constant
4. Switch argument and case label can be expression
5. The Case labels should be in the range of switch argument type (or less in size)
6. Duplicate case labels not allowed
7. We can take Default case atmost once, but the default case is executed only if none of the other case
matched, this is true where ever the default case is coded
8. If break is not used then all the statements after the matched cases will be executed, (even within the
other cases) till a break or end of switch occurs. This is code fallthrough and it is used to code for a range of values
switch(month){
case 1:
case 2:
case 3:
Finance("Q1")
case 4:
case 5:
case 6:
Finance("Q2")
case 7:
case 8:
case 9:
Finance("Q3")
case 10:
case 11:
case 12:
Finance("Q4")
}
switch(x) if x=1 ==>1
{ if x=2 ==> 2
default: 3
SOP("def"); if x=3 ==> 3
case 1: if x=4 ==> def
SOP(1); 1
break;
case 2:
SOP(2);
case 3:
SOP(3);
}
Loops:
While Loop
1. If we don't know the loop number then we use while
2. the expression should be Boolean
3. same rules of if statement applies in single line and curly braces
4. Compiler will check for unreachable code if hard-coded as non executable block; Unreachable code is not
allowed by compiler
5. The compiler cannot check the non reachable code if loop is constructed with variables and not finals
Do While
1. do { } While(condition); in this syntax semicolon is mandatory and all the rules of While loop
do while(true)
SOP("Hello");
while(false); is valid because with indentation the code looks like below
do
while(true)
SOP("Hello");
while(false);

For Loop
Same rules as other applies
the loop syntax is as follows
for (declaration and or initialization; condition; increment)
the declaration can contain any number of arguments but of same type
For Each Loop
for ( data type to read from the array: array)
Iterable
An object is iterable only if the class implements java.lang.Iterable(I)
Iterable => Collection =>list / Queue/ Arrays
Iterable implenments one method, iterator()
ClassNotFoundException NoClassDefFoundError
If Statically (Hard-coded) class is not found in run time the If Dynamic calling to create an object for a class
and that class not found by JVM then the error says the said class is not found
Labeled break and continue
public class LearnJava {
public static void main(String[] args) throws Exception
{
l1:
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(i==j)
continue; // break l1 continue l1
System.out.println(i + " ... " + j);
}
}
}
}
If break with label is used then the control goes out of block that starts after the label mentioned. In the above
example it comes out of the i loop.
If continue with label is used then control goes to the last line of the code block that starts after the label, in the
above example it comes to the closing parenthesis of i loop.
do_while vs Continue
public class LearnJava {
public static void main(String[] args) throws Exception
{
int x=0;
l1:
do
{
x++;
System.out.println(x);
if(++x < 5)
continue;
x++;
System.out.println(x);
}while(++x<10);
}
}
The continue will send the control to while statement in the loop. It will not send to the top of the block. the output
is 1 4 6 8 10
Declarations and access modifiers
1. Java Source file Strucure
2. Class level Modifiers
3. Member level Modifiers
4. Interfaces
Source file Structure
A java file can contain any number of classes but at most one public class, if there is no public class than any name
can be used for java source code.
If a java program doesn't contain any public class, then we can use any name for the java class
Compilation is done on java source file with extension .java
on successful compilation the compiler will create class file(s) based on number of class in the source program, one
class file for each class
to run the program, we use syntax java <class-name>, and the corresponding public static void main method will be
executed
Multiple classes in a single source file is not recommended.
Case 1
Import Statement
Class test{
PSVM(String[] args)
{
ArrayList al = new ArrayList();
}}
compile error : cannot find Class Arraylist in class test
to solve this problem by using fully qualified name
java.util.ArrayList l = new java.util.ArrayList();
the problem in fully qualified name is it reduces readability, we can solve this problem using import statement.
When ever we write import statement it is not required to use fully qualified name every time
Explicit import Always recommended to use for improved readability
import java.util.ArrayList;
after this ArrayList l = new ArrayList(); will not throw any compile time error
Implicit import
import java.util.*
Case 2
If we use fully qualified name then we don't need to use import statement
Case 3
import java.util.*;
import java.sql.*;
public class LearnJava{
public static void main(String[] args) throws Exception
{
Date d = new Date();
}
}
while compile the Date is ambiguous error since class Date is available in both the package
The another is ambiguity problem since it is available in util and awt packages.
Case 4
While resolving class names the priority is as follows in classes
1. Explicit import class name
2. Class in current working directory
3. implicit import class name
Case 5
When we use import only the classes available in the package is available, but the classes of sub package is not
available, if we need classes form sub packages then we need to write import till sub package level.
Case 6
All classes and interfaces present in java.lang and default(Current working directory) are by default available to
every Java program, hence we don't need to write import statement for them
Case 7
Compile time is high while using implicit import because it need to validate the class and packages
import statement overhead is related only with the compile time, but there is no effect on execution time
Case 8
Java loads the imported classes only on demand (Load on Demand / Load on Fly / Dynamic include). C language
#include <stdio.h> will include everything at begining
1.5 version new features
1. for each method
2. vararg methods
3. auto boxing and auto unboxing
4. Generics
5. co-varient return types
6. Quueue
7. Annotations
8. enum
9. Static import
Static import
import static java.lang.math.sqrt; or import static java.lang.math.*;
SOP(sqrt(4));
System is a class present in java.lang package
out is a static variable present in system class of type PrintStream
println is a method present in Printstream class
we can access the out class present in System class by import static java.lang.System.out; and using out.println()
directly
While resolving static member names the priority is as follows
1. current class static member
2. explicit static import
3. implicit static import
Normal and static import
Two packages contains contain class or interface with same name is very rare and hence ambiguity problem is very
rare in normal import
Two classes or interfaces contain a method name or variable with same name is very common and hence ambiguity
problem is also very common problem in static import
usage of static import reduces the readability and creates confusion on which class's method is used in a call. It is
not recommended to use static import if there is no specific requirement
The difference between normal and static import is, in Normal we can use it to import a class or interfaces of a
particular package, so we can use the short name instead of fully qualified name, but in static import is to import all
static members of a class
Packages
An encapsulation mechanism A group of related classes and interfaces into a single unit, which is termed as
package
eg1. All classes and interfaces that are required for database operation are grouped into a single package which is
termed as java.sql package
eg2. All classes and interfaces used for file IO operation are grouped into java.IO package
The advantage of package is
At-most only one package statement is allowed per java source file, and the corresponding folder structure is
created and the .class file is placed in if we use javac -d <directory name> <java source file>
Also first non-comment statement should be package statement.
1. Resolve naming conflicts
2. Modular programming
3. Maintenance
4. Security
The naming of package with unique name option to use client's internet domain in reverse. eg
com.icicibank.loan.housing.account where it can be broken into as follows
com.icicibank. => Client
loan. => module name
housing. => submodule name
account => Class name
whenever we write our own classes we have to provide information about our class to JVM like
1. Whether this class can be accessible from anywhere or not
2. whether final or extensible
Top level class
Allowed modifiers are public, <default>, final, abstract and strictfp
Inner Classes
in addition to the above mentioned private, protected and static are allowed
Access Specifiers vs Access Modifiers
public, private, protected default are considered as access specifiers except these remaining are considered as
modifiers, but this rule is applicable for old languages like C++ but not in java.
In java all are considered as modifiers only, there is no word specifiers is used.
Public classes
if a class is declared as public, then we can access that class from anywhere.
package pack1;
public class A
{
public void m1()
{
SOP("M1 of A class");
}
}
compile javac -d . A.java
package pack2
import pack1.a;
Class B
{
PSVM (String[] args)
{
A a = new A();
a.m1();
}
}
javac -d . B.java
java pack2.B
output : M1 of A class
if class A is not publlic, then while compiling B class, we get compile time error as "pack1.A is not public in pack 1;
Cannot be accessed from outside package"
Default classes
if a class is declared as default then we can access that class only within the current package, that is outside
package we cant access the class. the concept of current working directory. The default access is also know as
package level access
Final Modifier
Final is a modifier applicable for classes, methods and variables.
Final Method
Every method present in final class is final by default, but every variable in final in final class need not to be final,
because final values will not be able to modify value
The main advantage of final keyword is we can achieve security and unique
Abstract Modifier
Abstract modifier is applicable for classes and methods but not variables, Abstract and any other implemented
modifiers like final, native, synchronized, static, private, strictfp are not a permitted combination, it triggers illegal
combination of modifiers error
An Abstract class is a class which contains partial implementation. Where we can't create an implementation
Abstract Class
If a class contain at least one abstract method we need to declare class as abstract, else we will get an compile time
error since it is a syntax error : Reason is if a class contains at-least one abstract method, then implementation is
not complete and hence it is not possible to create object, to restrict object instantiation compulsory we should
declare class as abstract
Even though all the methods in a class is concrete, we can declare the class as abstract f we don't want
instantiation, this means an abstract class may contain zero abstract method too.
Every adapter class recommended to define as abstract but it doesn't contain any abstract method.
if a method doesn't have a body then compiler expects it to be defined as abstract
if a abstract method is defined, compiler expects it not to have a body
Abstract Class can contain Final method where as final class can't contain abstract method
Strictfp Strict Floating Point java Version 1.2
It is used to declare for classes and methods but not variables
usually the result of floating point arithmetic the result various from platform to platform, in order to avoid this
then the method is to be defined as strictfp so all floating point arithmetic should follow IEEE754 standard
Abstract modifier never talk about implementation where as strictfp method always talks about implementation,
hence abstract and strictfp combination is illegal for methods
if a class is declared as strictfp every floating point calculation present in concrete method has to follow IEEE754
standatd so we get platform independent results
Abstract and Strictfp combination is legal for classes but illegal for methods
Member level modifiers (Method and Variable)
Public members if a member is declared as public then we can access the member from anywhere but the
container class should be visible, ie before checking member visibility, we need to check the class visibility
Default Members if a member declared as default then we can access that number only within the current package,
from outside of the package we cant access, hence default access is also known as package level access
Private Members if a member is private then we cn access the member only within the class, from outside of class
we cant access.
Abstract methods should be available to the child classes to provide implementation, where as private methods are
not available to the child classes, hence private abstract combination is illegal for members
Protected Members The most misunderstood modifier in java, It can be access from within the package and
inherited classes outside the package and it needs to use the reference to the calling child class reference only
for Eg
if class A in pack 1, is referred in pack 2, class B is child of A and Class C is child of B, inside D we can use D's
Reference to access members of A, C's reference is not allowed
Visibility
Visibility Private <default> Protected Public
Within the same class Visible Visible Visible Visible
From Child class of same package Not Visible Visible Visible
Non child class of same packageNot Visible Visible Visible
From child class of different package Not Not Visible in child class self reference Visible
From non child class of different package Not Not Not Visible
The most restricted access modifier is private, followed by <default>, followed by protected and the least restricted
is public
Recommended modifier for data member (Variable) is Private, recommended modifier for methods is public
Final Variables
Final Instance variables
If the value of the variable is varied from object to object then those variables are called instance variables
For every object a separate copy of instance variables will be created
for in stance variables we don't need to perform initialization explicitly, JVM will always provide default values
if the instance variable is final then we need to initialize the value, else it is compile time error saying variable might
not been initialized
For final instance variable it is compulsory we should perform initialization before constructor completion else it
will throw error, the possible places are while declaration, inside instance block, inside constructor
Final Static Variables
The static variable is created at class level and shared by all objects of the class, its not required to initialize since
JVM provide default value but if it declared as final then initialization is mandatory before class loading completion
that is as below
1. At the time of declaration
2. Static block
Final Local Variables
Sometimes to meet the temporary need of programs we need to define some variable inside a block, those variable
is called automatic / temporary / stack, for local variables we need to provide initialization, if in case we are not
using the variable in the code then it will throw an error. So before using a temporary variable we need to provide
initialization, the same applies for Final Local variable. The only applicable modifier for local variable is final.
If we declare no modifier then it is default, but this rule applicable only for static and instance variable not for local
since its scope is always in the block
Formal parameter
Formal parameters off a method acts as local variables of the method, hence formal parameters can be declared as
final, if they are declared as final, then within a method we can't perform re-assignment
Static Class
We can't define the main class as static, but we can define inner class as static, these classes are called nested class
Instance members can't be accessed from static area, but we can access from instance area,
We can access the static members from both instance and static area
If parent class has main method and child doesn't contain main method, then the main method of parent will be
executed, if the child contains main then only child class's method is executed, this concept is called method hiding
not overriding
if we use any instance method in a method body then the method is instance method, if not then it should be Static
method.
Synchronized modifier
This modifier is available for methods and blocks, If multiple threads trying to operate simultaneous on the same
java object, then there may be a chance of data inconstancy problem. This is called Race condition we can
overcome this problem by using Synchronized keyword. If a method or block declared as Synchronized only one
thread is allowed to execute that method or block on the given object. So data inconstancy will be resolved
But the disadvantage of Synchronized is it increases waiting time of threads and creates performance problems, so
if there is no specific requirement then it is not recommended to use Synchronized keyword.
Synchronized method should contain implementation, so abstract Synchronized is illegal combination of modifiers
for methods
Native Modifier
It is applicable only for methods and cant apply anywhere else. These methods are non java methods (mostly in C
or C++) are called native methods or foreign methods.
For Native methods the implementation is already available in non java language, hence native method declaration
should ends with semicolon and cannot have a body
Native method is illegal with with abstract because it already have an implementation and strictfp because there is
no assurance that those method implementation follow IEEE754 standard
Despite of the advantages of Native we loose the property of platform independent nature
it is used for the following reasons
1. Performance critical since Java is low performer when compared to C or C++
2. Machine level communication is required where Java is not capable of doing it
3. If a functionality is available in other language development then we can use the native option
to ue native method the sudo code is as below
class native
{
static
{
System.load Library("native library name"); //Load native libraries
}
public native void m1(); //declare native methods
}
class child
{
public static void main(String[] args)
{
native n = new native();
n.m1(); //Invoke native method
}
}
Transient
This keyword means not to serialize (don't save), During the time of serialization if we want not to save the value of
a particular variable to meet security constraint then we should declare that variable as transient. At the time of
serialization JVM ignores original value of transient variables and save default value to the file.
1. This modifier is variable specific
2. It plays role in serialization context
Volatile
it is only for variables. If the value of a variable kept on changing by multiple threads then there might be a chance
of data consistency problem, we can solve this using volatile modifier. If a variable declared as volatile, then for
every thread JVM create a separate local copy. This increases load on JVM and system performance and it is nearly
deprecated, so it is discouraged to use it anywhere
Modifier outer Classes Inner classes methods variables Block Outer Interfacce
Inner Interface Outer Enum Inner Enum Constructors
public Yes Yes Yes Yes Yes Yes Yes Yes Yes
private Yes Yes Yes Yes Yes Yes
protected Yes Yes Yes Yes Yes Yes
default Yes Yes Yes Yes Yes Yes Yes Yes Yes
final Yes Yes Yes Yes
abstract Yes Yes Yes Yes Yes
static Yes Yes Yes Yes Yes Yes
synchronized Yes Yes
native Yes
strictfp Yes Yes Yes Yes Yes Yes Yes
transient Yes
volatile Yes
Interfaces
Any service requirement specification (SRS) is called as interface, as described in examples below
1. JDBC API Acts as requirement specification to develop the database driver, Database vendor is
responsible to implement JDBC API
2. Servlet API is SRS where the webserver vendor is responsible for API implementation
Inside interface all methods are abstract, hence interface is considered as pure abstract class
Summary definition
Any service requirement specification or contract between client & service provider or Pure abstract class
1. If we implement an interface then we have to implement all the methods else define the class as
abstract
2. All the methods of interfaces are public and abstract by default even if it is not specified, so the
implementation should contain public keyword for the method implementation
3. A class can extend only one class but implement any number of interfaces
4. An interface can extend any number of interface, but not a class
5. We have to extends first followed by interfaces implementation
Interface Variable
Interfaces variables are always public since it may accessed from outside package
Variables are Static because implementation class can access the variable without implementation
Variables are Final because multiple vendors have access to variables and it will create in-consistency if one
modifies and other expect some value
Always it is public static final variables
Initialization is always during definition because the static final should should be initialized before class load and
interfaces doesn't have static block
Interface naming conflicts
1. If two interfaces a method with same signature then the implementation class implementing both
interfaces we have to provide implementation only once
2. If two interfaces contains method with same return types but different signature (arguments) then both
are needed to be implemented and these methods are called as overloaded methods
3. If two interfaces contains method with different return types but same signature (arguments) then the
class cannot implement both the interfaces
4. If two interfaces contain variable with same name, then there is variable naming conflict, but we can
solve the issue by using interface name
Marker Interface
1. Serialiasable
2. Cloneable
3. RandomAccess
4. SingleThreadModel
The above are examples of marker interface, if an interface doesn't contain any methods and by implementing that
interface, if our objects get some ability, such type of interface are called marker interface
Internally JVM is responsible to provide required ability
Why JVM is providing ability in marker interfaces? It to reduce complexity of programming and make JAVA as
simple as possible
We can make our marker Interface if we create our own JVM
Adapter Classes
Adapter Classes are the classes which implements all interface methods with empty implementation. It reduces
overhead of implementing all methods of interface when we are only interested in few of it.
Since it is empty implementation its better to define the adapter class as abstract
Interfacec Abstract Class
If we just know the requirement specification and nothing about implementation then we go for interfaccec If
we know implementation partially (partial implementation) then abstract class
Every method is always is public and abstract whether we are declaring or not, hence interface is 100% pure
abstract class Every method need not be public and abstract, also we can take concrete method too
All variable are public static final variable can be of various type
Variable initialization is mandatory in interface Variable initialization is not mandatory in abstract class
cant declare static and instance block can declare static and instance block
The abstract class's constructor will execute with child's, to send values to parent constructor is just calling
super(<constructor attributes)
The disadvantages of using Abstract class over Interface
1. We will be able to extend only one class at a time and interface
2. Performance is better in Interface
OOPS
Data Hiding
Data is not allowed to access data from outside access area directly, only after authentication can access the
internal data, This feature ensures the data to be protected well. Its is achieved by declaring all data variable as
private
Hiding internal implementation and highlight the set of service offering is the concept of Abstraction
Binding of data members and corresponding methods into a single unit is Encapsulation, Every class is an example
of encapsulation, It ensures security but slows the execution. A class is set to be tightly encapsulated if all data
members
The above concepts are related to security of the OOPS concepts
IS-A-Relationship
It is also knows as inheritance, using keyword extends, re-usability of code,
Cyclic Inheritance is not allowed in Java
Has a relationship is also known as Composition and aggregation, there is no specific keyword implement has a
relation but most of the times we are depending on new keyword, The main advantage of has a relationship is re-
usability.
Composition
Eg University and Department : Strong association between container and contained objects is called composition,
with out container objects if there is no chance of existing contained objects then the container and Contained
objects are strongly associated, and then this strong association is composition
Aggregation
If there is a chance of contained objects can exist without container object then the container and contained
objects are weakly associated, it is named as aggregation, Eg Department and employee relation, where if the
professor could be re-assigned to another department.
Method Signature
Method signature consists of method name and argument types
Overloaded methods
While resolving overloaded methods compiler will give precedence for child type
public class LearnJava
{
public void m1(String s)
{
System.out.println("String");
}
public void m1(Object o)
{
System.out.println("Object");
}
public static void main(String[] args)
{
LearnJava l = new LearnJava();
l.m1("Senthil");
l.m1(new Object());
l.m1(null);
}
}
The output of above program is
String
Object
String
Since the null is valid for both String and Object, the child gets priority to complete the work.
In situation like old methods vs new method, (eg vararg method and general method)
Always the reference type is preferred in deciding method precedence in method calls, in overloading run-time
object won't play any role in
Overriding
1. If the child class re-defining the method defined in parent then the redefined method is overriding
method, and the parent class's original method is called overridden method.
2. Compiler checks for methods in reference class and JVM checks in run time object, that is called runtime
polymorphism / late binding
Rules for overriding
1. Method signature should be same
2. In overriding return types must be same, but this rule is applicable only 1.4 version only, from 1.5 version
on wards we take co-variant return types, according to this child class method return need not be same as parent
method return type, its child type is also allowed (Also it is allowed only for object and not primitive data types)
1. public object m1() is in parent
2. public String m1() in the extended class (from 1.5 version it is valid)
3. parent class's private methods are not available to the child, and hence overriding concept not applicable
for private methods, so
Overriding rules on Exception
Throwable is the root class for exception classes
If child class method throws any checked exception, so the parent should throw the same exception or parent
exception, If Child throws any checked exception and parent doesn't then it is compiler error,
The rule is only for checked exception, the unchecked exception can be in any order between
Overriding Static methods
Overriding static with non static or vice versa is not allowed, because the method will change the way the method
is called, which could affect the programs which are not aware of it
if both parent and child class method are static then we wont get any compilation error, but it is not overriding and
it is method hiding.
in method hiding, all rules of method hiding is exactly same as overriding except following
1. Both the method is static
2. method resolution by JVM based in object reference
Overriding Vararg methods
We can override vararg method with another vararg method only, if we are trying to override with normal method
then it is overriding and not overloading because the signature are different.
Overriding variables
overriding / Run time polymorphism is only for methods, so the reference of parent will have parent variable name
and child reference will have child reference value, Variable resolution is always taken by compiler based on
reference type, irrespective of the variable is static or non static.
Property Over loading Overriding
Method names Must be same Must be same
Argument typesmust be different (atleast different order) Should be same including order
Return types No restrictions must be same till 1.4, from 1.5 Co variant return type is allowed (Child object type)
Private Static and final Can be overloaded Cannot be overloaded
Access modifiers No restriction The scope of access modifiers cannot be reduced, but can be increased
Throws No Restriction If child class method throws checked exception , then parent class method should throw
same or parent exception.
Method Resolution Compiler based reference determination Always taken care by JVM based on run
time object
Other names Compile time/ Static polymorphism or early binding run time / Dynamic polymorphism or late
binding
Consider the following method in parent calss
public void m1(int x) throws IOException
in the child class check the following methods are valid
1. public void m1(int i) Valid by overriding
2. public static int m1(long l) valid by overloading
3. public static void m1(int i) invalid because of overriding from instance to static
4. public void m1(intt i) throws Exception Invalid because child throwing exception which is not same or
child of parent method throwing exception
5. public static abstract void m1(double d) Invalid combination of modifiers static and abstract
Polymorphism
one name but multiple forms is the concept of polymorphism
1. Method name is same but we an apply different types of arguments (Overloading) eg abs(int) abs(long)
2. Method signature is same but in parent class a different implementation and child another
implementation.
3. Usage of parent reference to hold child object is concept of polymorphism
4. Parent class reference can be used to hold child object, but by using parent reference we can call
parent's Static method and variables but while calling methods non static then it calls method of underlying object
When to use the parent reference to hold child class object?
When we don't know which child class the object will belong to then we use parent object reference to hold child.
For Example if a method is going to return any type of child then use the parent to receive the object without any
issue and we can process based on the instanceof method to determine the object type.
3 Pillars of OOPS
1. Encapsulation talks about security
2. Polymorphism talks about Flexibility to programmers
3. Inheritence talks about Re-Usability
Polymorphism
1. Static / Compile time Polymorphism / Early Binding
1. Overloading
2. Method Hiding
2. Dynamic / Runtime Polymorphism / Late binding
1. Overriding
Copupling
The degree of dependence between objects is called as coupling, if more dependent then it is tightly coupling, and
loosely coupling if less depending
Loosely coupuling is the best programming practice
Cohesion
For every component a clear well defined functionality is required, then that component is said to be follow high
cohesion. High cohesion is a better programming practice, that is a different object for different functionalities,
because it has advantages as below
1. Without affecting any component we can modify any component, so enhancement is easy
2. It promoted re-usability of the code, where ever validation is required, we can reuse the same validate
servlet without re-writing
3. It improves the maintainability of the application
Object typecasting
We can use parent reference to hold child object,
: Runnable r = new Thread();
A b = (C) d;
In the above statement Compiler does checks two condition and JVM will do one.
1. Compiler checks first conversion of d to type C is valid, to be valid it should be either having the
relationship as (Either Child to parent or parent to Child or same type), otherwise CTE: in-convert-able types found
d type , Required C
Eg1: Object o = new String("Durga")
StringBuffer sb = (Stringbuffer) o;
The above is valid since Stringbuffer and Object have parent child relationship
Eg1: String S = new String("Durga")
StringBuffer sb = (Stringbuffer) s;
The above is invalid since both has no relationship Stringbuffer and String has no relationship
Run time checking, The underlying object type of 'd' should be same or derived type of 'C', else RTE: Class cast
exception
class A {
void m1(){
System.out.println("A");}}
class B {
void m1(){
System.out.println("B");}}
class C {
void m1(){
System.out.println("C");}}
The Answers for the below m1 calls are as follows
C c=new C();
c.m1() ==> C
((B)c).m1() ==> C
((A)((B)c)).m1() ==> C
This is because, though the type conversion are done, this is overriding, so method resolution is always based on
run time object type
If the above method is static method, then it is not overriding but method hiding, and method resolution is always
based on reference type not run time, so the answer is C, B, A respectively
class A { int x = 777;}
class B { int x = 888;}
class C { int x = 999;}
The Answers for the below SOP calls are as follows
C c=new C();
SOP(c.x) ==> 999
((B)c).x ==> 888
((A)((B)c)).x ==> 777
This is because for the variable resolution is always based on reference object and the reference object's value is
taken.
Static control flow
When ever we execute a java class, the order of execution is as follows as per static control flow
1. Identification of static blocks from top to bottom [Steps 1 to 6 in the below example]
2. Execution of static variable assignments and static blocks from top to bottom [Steps 7 to 12 in the
following example]
3. Execution of main method [Steps 13 to 15 in the following example]
Consider the following program and output
class StaticProcessing Steps
{
static int i = 10; 1 7 in step 1 i Value set to zero while identifying
variable where it is knows as RIWO(Read Indirectly Write Only)
static 2 8
{
m1();
System.out.println("First block"); 10
}
public static void main(String[] args) 3
{
m1(); 13
System.out.println("Main Method"); 15
}
public static void m1() 4
{
System.out.println(j); 9 14 indirect read
}
static 5
{
System.out.println("Second block"); 11
}
static int j = 20; 6 12
}
The output is as below
0
First Block
Second Block
20
Main Method
if a variable is just identified but initial value not assigned then it is said to be in RIWO state, in this state we can
perform indirect read, if we perform read, ie use it in static block, then we ge cmpile time error, illegal forward
reference.
If a variable is read directly (used ) in a static block then it is Direct read, if it done
Read Indirectly write only
https://www.youtube.com/watch?v=B_tYO3Yn61U&list=PLd3UqWTnYXOmx_J1774ukG_rvrpyWczm0&index=60
39:40
class test{ class test{ class test{
static int x = 10; static static
static { {
{ System.out.println(x); m1();
System.out.println(x); } }
} static int x = 10; public static void m1()
} } {
System.out.println(x);
}
static int x = 10;
}
OP OP OP
10 CTE: Illegal forward reference 0
RTE: No such method error : main RTE: No such method error : main
Static Block
Static blocks will be executed at the time of class loading, hence we can code the activities that needed to be
performed during class load. At the time of java class loading the corresponding native libraries should be loaded.
Hence we have to describe this activity inside static block.
After loading every database driver class, we have to register driver class with driver manager, This is performed by
a static block inside the database driver class and we are not responsible to register explicitily
Within a class we can declare any number of static blocks, but all of them will be executed from top to bottom.
1. Without main method using static block we can print some statements to the console until 1.6 version
Static control flow in Parent to Child Relationship is same as individual, but the main of only child will be executed
when we run child class
Instance Control Flow
When ever we are executing a Java class, Static control flow will be executed. In the static control flow if we create
an object the following sequence of events will be executed as a part of instance control flow
1. Identification of Instance members from top to bottom
2. Execution of instance variable assignments instance blocks from top to bottom
3. Execution of Constructor
Unlike one time activity of Static control flow, Instance control flow will happen every time a new object creation.
Instance control flow from parent to child relationship
1. Identification of instance members from parent to child
2. Execution of instance variable assignments and instance blocks only in parent class
3. Execution of parent constructor
4. Execution of instance variable assignments and instance blocks only in child class
5. Execution of constructor constructor
Consider the following program and its output
class StaticInstance First Static Block
{ Second Static Block
{ First Instance Block
System.out.println("First Instance Block"); } Second Instance Block
static{Constructor
System.out.println("First Static Block"); Main Method
} First Instance Block
StaticInstance(){ Second Instance Block
System.out.println("Constructor"); Constructor
}
public static void main(String[] args) {
StaticInstance si1 = new StaticInstance();
System.out.println("Main Method");
StaticInstance si2 = new StaticInstance();
}
static{
System.out.println("Second Static Block"); }
{
System.out.println("Second Instance Block");}
}
From Static we can't access instance members directly because, while executing static area JVM has not identified
any of the instance members.
class Test{
int x;
public static void main(String[] args){
System.out.println(x);
}
This is an compile time error because x is not identified while main is executed since there is no instance reference
for the x we are trying to print.
Ways to create objects in java
1. new operator eg Test t = new Test();
2. newInstance method eg Test t = (Test) Class.forName("Test").newInstance();
3. Factory method
1. Runtime r = Runtime.getRuntime();
2. DateFormat df = Dateformat.getInstance();
4. By using clone() method
1. Test t1 = new Test();
2. Test T2 = (Test) t1.clone()
5. by using De-serialisation
1. FileInputStream fis = new FileInputStream("Abc.txt");
2. ObjectInputStream ois = new ObjectInputStream(fis);
3. Dog d = (Dog) ois.readObject();
Constructor vs Instance Block
Constructor is to do initialization of the object, but other than initialization if we want to perform any activity for
every object creation then we should use instance block (like counter increase for every object creation)
Constructor Rules
1. Name of the class and constructor should be matched
2. Return type is not applicable for constructor (not even void), if we declare a return type for the
constructor then we wont get any compile time error because compiler treats it as a method
3. The applicable modifiers are public, private, protected and default
Default Constructor
1. Compiler is responsible for generating default constructor
2. Compiler will provide default constructor only if programmer provides no constructor at all
3. It is no arg constructor
4. The access modifier is exactly same as access modifier of the class (This rule is applicable only for public
and default)
5. It contains a call to super with no argument super();
6. The Compiler checks if the programmer provided constructor for the first line to be either super() or
this(), if not present the compiler will place super()
7. Only inside constructor we ca use super() or this()
8. we use super or this only in constructor, only in first line and only one inside a constructor
super(), this() super, this
These are constructor calls to super class and current class These are keywords to refer super class
and current class instance members
We can use only in constructor and only in first line we can use anywhere except static area
we can use only once in constructor we can use any number of time
Overloaded constructors
1. Overloading is possible for constructors
2. Inheritance and overriding concept is not applicable for constructors
3. Including Abstract class every class in java can contain constructor
4. interface can't have constructor because all attributes in interface is static, since constructor is initialize
an instance, there is no chance of instance in interface, hence it is illegal and Compile error
5. If there is a chance of recursive constructor invocation then it is a compile time error
Constructor Loopholes
class P{
P(int i)
{
}
}
class Test extends P{
}
The above is a compile time error.
1. If parent class contain any argument constructor, while writing child classes we have to take special care
with respect to constructors
2. When ever we write any argument constructor, it is highly recommended to write no-arg constructor
also
import java.io.IOException;
class P{
P() throws IOException
{
}
}
class Test extends P{
}
The above is compile time error, because of called constructor throws an exception, it should be handled or the
caller should throw the same or its parent exception
The parent constructor is throwing exception, the default constructor is going to place super() call which will call
the constructor of Parent which is actually throwing IOException but our default generated constructor doesn't. It
can be handles with adding throws IOException or its parent in programmer specified constructor with throws
addition.
Singleton Class
For any java class if we are allowed to create only one object then it is called as singleton class, some examples are
1. Runtime
2. BusinessDeligate
3. ServiceLocator
If several people have same requirement, then it is not recommended to create a separate object for every
requirement, instead we can reuse one object for every requirement, so that performance and memory utilization
will be improved. This is the central Idea of singleton classes.
How to create our own Singleton classes
We can create our own singleton classes, by using private constructor and private static variable and a public
factory method.
Approach 1
class Test{
private static Test t = new Test();
private Test(){}
public static Test getTest(){ return t; }
}
Runtime class is internally implemented using this approach.
Approach 2
class Test{
private static Test t = null;
private Test(){}
public static Test getTest(){
if (t == null)
t = new Test();
return t; }
}
At any point of time, for Test class we can create only one object, hence Test class is singleton Class
Class is not final, but we should not allow to create a child class,
If all constructors are declared private then we cant create a child class for the class
Exception Handling
1. Introduction
An unexpected unwanted event that disturbs normal flow of the program is caleed exception
Activation records / stack frame is the stack that is created with main thread by JVM for main thread, which starts
the first entry of main method. Once all the method calls are completed then the empty stack will be destroyed by
JVM.
Each and every method call performed by that thread will be stored in corresponding stack. Each entry in the stack
is called stake frame or activation record. After completing every method call the corresponding entry from stack
will be removed, after completing all method calls the stack will become empty and the empty stack will be
destroyed by JVM just before terminating the thread.
Default Exception handling in JAVA
1. Inside a method if an exception occurs the method in which it is raised is responsible to create exception
object by including the following information
1. name of exception
2. Description of exception
3. Location at which the exception occurs
2. After creating exception object methods handovers that object to JVM
3. JVM will check whether the method contains any exception handling code or not, if the method does't
contain exception handling code then JVM terminates that method abnormally and removes corresponding entry
from the stack.
4. JVM Identifies the caller method and checks for the error handling code and if doesn't contain it, then
JVM terminated the caller method too abnormally and removes the corresponding entry from the stack
5. The above process will be continued till main method, and if main method too doesn't contain JVM code,
then JVM terminates main method abnormally and removes corresponding entry from the stack
6. Then JVM handovers the responsibility of exception handling to default exception handler which is the
part of JVM
1. Default Exception thread "xxx" name of the exception : Description followed by Stack trace
Exception Hierarchy
Throwable class is the root for exception hierarchy, it contains two child classes Exception and Error
Exception: Mostly exception are caused by our program and these are recoverable for example, if our programming
requirement is to read data from a remote file, but at run time if remote file is missing, then we get run time
exception "file not found" exception, in this case we can read local file and continue the program execution.
Try{
Read remote file
}
Catch(FileNotFoundException e){
use local file
}
rest of the program
Error: Mostly errors are not caused by our program, it is generally due to lack of system resources (eg
OutOfMemory Error)
Exception Hierarchy
1. Run time Exception
1. Arithmetic Exception
2. Null Pointer Exception
3. Class cast exception
4. Index Out of bound Exception
1. Array Index out of bound exception
2. String Index out of bound exception
5. Illegal Argument exception
1. Number format Exception
6. ....
2. IOExpection
1. EOF Exception
2. File not found Exception
3. Interrupted IO Exception
3. Servelet Exception
4. Remote Exception
5. Interrupted Exception
6. ......
Checked exception & Unchecked Exception
The exceptions that are checked by compiler to ensure smooth execution is called as checked exception. In our
program if there is a chance of any exception then we need to handle the exception by either try catch or throws.
There are some exception which are not checked by compiler whether programmer is handling or not. Those
exceptions are called uncheked exceptions such as ArithmeticException
Error and Runtime and its child classes are unchecked Exception
Fully vs Partially checked Exception
A checked exception is fully checked if and only if all its child classes also checked, eg IOException,
InterruptedException.
A checked exception is partially checked if some of its child classes are unchecked, eg Exception, Throwable
Describe the behaviour of following exceptions
IOException -> Fully checked
RuntimeException ->Uncheked
InterruptedException ->Fully checked
Error ->Unchecked
Throwable ->Partially checked
ArithmeticException ->Unchecked
NullpointerException ->Unchecked
Exception ->Partially checked
FileNotFoundException ->Fully checked
Customized exceptional handling with try-catch
We need to take only the risky code in try block and length of try block should be as less as possible.
We have 3 methods to print the error
1. printStackTrace() --->>> Name of Exception: Description and stack trace
2. toString() --->>> Name of Exception : Description
3. getMessage() --->>> Description
Order of Catch is more important, child and then parent, else we get a compile error saying exception already
caught
Try - Risky Code
Catch - Handling Code
Finally - Cleanup code
The specialty of finally block is it will be executed always irrespective whether exception is raised or not raised and
weather handled or not.
Finally is used to maintain cleanup code at try block level
Finalize()
This method always invoked before destroying an object to perform cleanup activities related to object, once
finalize method completes immediately garbage collector destroys the object.
Various possible combination of try catch finally
1. Order is important
2. Try without catch or finally is invalid, Compile error, Try without catch or finally is invallid
3. For Catch and Finally Try block is mandatory
4. Nesting of try catch finally is allowed
5. If a Exception is not having a chance to raise in try block then we cant write catch for the same, this rule
is applicable for Fully checked exception
Throw class
1. Programmer throws Exception and JVM catches the thrown exception, Throw keyword handover the
created Exception Object to JVM manually.
2. It is generally used to throw custom defined exception
3. We can use throw keyword only for throw-able types, if we try to use for normal Java objects, we will get
compile time error : Incompatible type found <type> required Java.lang.throwable.
Throws Keyword
1. Throws keyword is used to delegate the responsibility of Exception handling to the caller method.
2. Throws keyword is required only for checked exception, on unchecked exception the keyword is
meaningless.
3. Throws keyword doesn't guarantee normal termination of the program, if main method also throws then
the JVM is responsible to handle exception, in this case it is abnormal termination.
4. Throws Keyword is just to convince Compiler, better approach is try catch
class Test{
public statiic void main(String[] args) throws InteruptedException
{
Thread.sleep(1000);
}
Defining Custom Exception
Class MissingPersonException extends RuntimeException
{
MissingPersonException(String s)
{
super(s);
}
}
Class LocatePerson
{
PSVM(String[] args)
{
if (Person not in DB)
{
throw new MissingPersonException("Person data is not available");
}
}
}
It is highly recommended to define customized exceptions as unchecked, ie we have to extend Run-Time exception
but not exception
The super call is needed to make the description available to Default Exception Handler
Type of Exception
Based on the source of exception throwing the Exception are are two types
1. JVM Exception : When ever an even occurs which is faulty nature then JVM raises the JVM excepion (Null
pointer, Arithmetic etc)
2. Programmatic Exception : These are raised explicitly either by programmer or API developer to indicate
that something goes wrong, IllegalArgumentException
10 Commonly used exception
1. ArrayIndexOutOfBoundException is child of IndexOutOfBoundException unchecked
2. NullPointerException is Child of RuntimeException Unchecked
3. ClassCastException: If we try to cast parent to child then we get this exception
4. StackOverFlowError: Raised automatically by JVM on recursive call
5. NoClassDefFoundError: Raised automatically by JVM whenever JVM is unable to find .class file
6. ExceptionInInitilizerError: Raised by JVM while static variable assignments and static blocks eg static int x
= 10/0 Caused by ArithemeticEception Division by Zero; class Test{ static{ String s=null; SOPL(s.length()); }} Caused
by Null pointer Exception
7. IllegalArgumentException: Programmed in Thread class, while setting priority out of range of 1 to 10. Its
Programmatic Exception
8. NumberFormatException: Child of IllegalArgumentException which is child class of Runtime Exception,
Raised by Programmer
9. IllegalThreadStateException: If we call start method second time when it is already running then this
Exception will trigger
10. AssertionError: unchecked, child of Error, Raised explicitily by programmer to indicate that assert
statement fails eg assert x > 10, if X is not greater than 10, if X is not greater than 10 then we get RunTimeException
AssertionError
1.7 version enhancement with respect to Enhancement handling
1. Try with Resources
2. Multi_catch Block
Try with
Till 1.6 version, it was recommended to write finally block to close the resources that are opened in try block
BR br = null;
try(
br = new BR();
user br
}
catch (Exception e){}
Finally{
if br !== null)
br.close();
}
since it is necessary to write final block it is necessary to write finally block which increases the code length, so from
1.7 version the new concept of try with resources was introduced
try (BR br= new BR(new FR("a.txt")))
{
}
catch{}
1. in the above example, the resources created in try block will be closed at end of Try so finally is not
needed
2. We can define any number of resources in try, and should be separated by Semi-Colon, and they should
be auto-close-able resources, where they implement java.io.Autoclosable introduced in 1.7 version which contain
only close() method.
3. All resources reference variables with try is FINAL by default
Multi-Catch Block
Till 1.6 version though many catch blocks contains exact same code, we need to write separate catch block for each
exception, but from 1.7 version we can combine multiple catch blocks in a single catch block, where every
exception is separated by '|' symbol
eg
try{}
catch(ArithmeticException|IOException e)
In a multi-catch block there should not be any relation between Exception types (parent=>child , Child => Parent, or
same type)
If the called method is not handling the Exception then it is propaganded to caller, this is called Exception
propaganda
Re-throwing Exception
We can use this approach to convert one exception to another exception type
try{
SOP(10/0);
}
catch(ArithemeticException e)
{
throw new NullPointerException();
}
Multi-Threading
1. Introduction
2. Ways to define a Thread
1. By Extending Thread class
2. By implementing Runnable Interface
3. Getting and Setting name of the Thread
4. Thread Priorities
5. The methods to prevent Thread Execution
1. Yield
2. Join
3. Sleep
6. Synchronization
7. Inter-thread communication
1. Wait
2. Notify
3. NotifyAll
8. Deadlock
9. Daemon Threads
10. Multi-Threading Enhancement
Introduction
Executing several tasks simultaneous is the concept of multitasking, there are two types multitasking
1. Process based => Different application, Eg : Listen to music, coding in IDE, Download a file at same time
2. Thread based = > Execute several tasks simultaneously where each task is a separate independent part of
the same program and each independent part is called as thread
To develop web/application servers we use Threads, Developing muti-threaded application in java is easy since java
provides support for multi-threading with rich API (Thread, Runnable, ThreadGroup ...)
Ways to Define a Thread
By Extending Thread Class
class my-thread extends Thread
Thread Scheduler is part of JVM, it is responsible to schedule Threads, Ie if multiple threads are waiting to get a
chance of Execution then in which order the threads will be executed is decided by Thread scheduler. We can't
expect exact algorithm followed by thread scheduler, it varied from JVM to JVM so we can't expect thread
execution order. When ever multi-threading situation there is no guarantee for exact output
Difference between t.start() and t.run()
t.start() a new thread will be created and that is responsible for running our run method in the newly created
thread, but if use t.run() then it is not run in a different thread but the main thread, here no thread is not created
but executed as a normal method of object "t"
Importance of Thread.start()
This method is responsible to register the thread with thread scheduler and all other mandatory activities, hence
without executing start method there is no chance of starting new thread in JAVA, because of this the method is
considered as heart of multi-threading. The following are performed
1. Register the thread with thread scheduler
2. Perform all other mandatory activities for starting the thread
3. Invoke run method
Overloading of run method is always possible but the Thread.start method will invoke only the run method with no
arg, the other overloaded method is to be called as a normal method call.
If we are not overriding run method then Thread.run method will be executed, which has empty implementation,
hence we won't get any output
The State of threads
1. MyThread t = new MyThread(); ===> New / Born
2. t.start() ===> Ready / Runnable
3. Once Thread scheduler allocates processor ===> Running
4. After completing run method ===> Dead
By implementing Runnable Interface
Runnable Interface present in Java.lang package and it contains only run method
The Runnable approach is recommended to use in thread concept because we can use since we can use inheritance
if we implement runnable.
Thread class Constructors
1. Thread t = new Thread();
2. Thread t = new Thread(Runnable r);
3. Thread t = new Thread(String name);
4. Thread t = new Thread(Runnable r, String name);
5. Thread t = new Thread(Threadgroup g, String name);
6. Thread t = new Thread(Threadgroup g, Runnable r);
7. Thread t = new Thread(Threadgroup g, Runnable r, String name);
8. Thread t = new Thread(Threadgroup g, Runnable r, String name, long stacksize);
Another way to define a Thread Not recommended to use
class NewThread extends Thread{
public void run(){ System.out.println("Child Thread"); System.out.println(Thread.currentThread().getName()); ;}
}
class ThreadNew{
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
NewThread nt = new NewThread();
Thread t = new Thread(nt);
t.start();
t.setName("Senthil's Thread");
t.setPriority(10);
System.out.println("Main Thread");}}
Second is the Thread constructor target reference used is Class Thread's child reference instead of Runnable's type.
This is valid Because the class Thread already implemented Runnable
Thread Priorities
The Java thread priority varies from 1 to 10, where 1 is the lowest and 10 is the maximum. It will default assigned
by JVM if programmer does't set one for the thread.
The Thread scheduler used the priority execute the threads based on the priority, if two threads has same priority
then we can't specify the order of execution, its based on thread scheduler.
Default priority of the main thread is 5, for all remaining threads the default priority is inherited from the parent to
child.
Preventing Thread Execution
We can prevent a thread execution using
1. yield()
2. join()
3. sleeep()
Yield Method
This method pause the current executing thread to give chance for waiting threads of same priority, if there is no
waiting thread or waiting thread is of low priority then the thread can continue its execution, if there are multiple
thread waits its execution, the thread which will execute next is depends on thread scheduler.
The syntax of the method definition is
public static native void yield()
Some platforms won't provide proper support for yield method
Join Method
If a thread wants to wait untill other method completes then it should call join method. If thread T1 wants to wait
untill T2 completes, then T1 has to call T2.join(). If T1 executes T2.join() then immediately T1 will enter to wait state
untill T2 completes.
Once T2 completes then T1 can continue its execution.
public final void join();
public final void join(long milliseconds);
public final void join(long milliseconds, int nanoseconds);
All Join method throws Interrupted Exception, so we need to handle the Interrupted Exception wither by throws or
catch
If the thread executed Join then the thread goes to Waiting state (Blocked for joining) and once the wait over for
following reason
1. if the process it is waiting for completes
2. if the time of wait in join call is run out
3. if waiting thread gets interrupted
then the thread will move to ready/runnable state
Waiting of main thread for child thread for 100 milliseconds
class MyThread extends Thread{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("Child Thread");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
//TODO: handle exception
}
}
}
}

class JoinThread{
public static void main(String[] args) throws InterruptedException{
Thread t = new MyThread();
t.start();
t.join(100);
for(int i=0;i<10;i++)
{
System.out.println("MainThread");
}
}
}
Waiting of child thread untill completing main thread, below example child thread waits by joining the parent
thread's reference
class MyThread extends Thread{
public static Thread pt;
public void run()
{
try {
pt.join(1500);
} catch (InterruptedException e) {}
for(int i=0;i<10;i++)
{
System.out.println("Child Thread");
}
}
}
class ChildWait{
public static void main(String[] args) throws InterruptedException{
MyThread.pt = Thread.currentThread();
Thread t = new MyThread();
t.start();
for(int i=0;i<10;i++)
{
System.out.println("MainThread");
Thread.sleep(500);
}
}
}
If main methods calls joins on child thread object and child thread calls joins on main thread object, then the
program will enter Dead-lock on wait state
If a thread calls join on itself then the program will enter Dead-lock on wait state.
Sleep
If a thread enters in sleep method, it is done by possible one of the below format
1. sleep()
2. sleep(long milliseconds, int nanoseconds)
If the thread encounters sleep method execution then it enters sleep state and it can go back to Ready state on the
following occasions
1. Time lapsed the specified sleep time
2. The thread is interrupted
A thread can interrupt a sleeping or waiting thread by using Interrupt method of Thread class
public void interrupt()
If a Interrupt is triggered when thread is not in sleep state then the interrupt will wait till the thread foes into sleep
and interrupts, (as simple as waking a sleeping patient to give sleeping pill)
Property Yield() Join() sleep()
Purpose Thread wants to pause its execution If thread wants to wait for some method to complete If
a thread wants to hold its execution for a period of time
Overlaoded No Yes Yes
Is it final No Yes No
Interrupted Exception throwing No Yes Yes
Is it native Yes No sleep(long) is Native
Sleep(long, int) is non-native
Synchronization
Synchronize is keyword applicable only for methods
Internally Synchronization concept is implemented using lock, every object in java has a unique lock, when ever we
use synchronized keyword only then lock concept will be in picture. If a thread executes a synchronized method
then the thread has to acquire the lock of the object. once the Thread has the lock it is allowed to execute any
synchronized method on the object. Once the method execution completes automatically Thread releases the lock.
Acquiring and releasing the lock is taken care by the JVM and programmer need to do nothing about it.
Lock concept is implemented based on object and not method, So when an object's synchronized method is held by
a thread then no other synchronized method call will be allowed on the object (Object not class)
Class level Lock
Every class in JAVA has a unique lock which is called as class level lock. If a Thread is needs to execute a static
Synchronized method then it will need an exclusive lock on the class, Once it has the class level lock then it have
the access to lock any class level locks. Once method execution completes Thread releases the lock, While a thread
executing static sync method, then remaining threads are not allowed to execute any static sync method of the
class, but they are allowed to execute the following methods simultaneously
1. Normal static method
2. Synchronized methods
3. Normal methods
Synchronizes Block
If very few lines of the code needs synchronization then it is not recommended to define the method as
Synchronized, we have to enclose those few lines of the code b using Synchronized block, the main advantage is
reduces waiting time and improves performance
To get lock of current object
synchronized(this)
{
.......Code block needs locking..............
}
To get lock of particular object
Synchronized(b)
{
.......Code block needs locking..............
}
To get lock at Class level
synchronized(<Class_Name>.class)
{
.......Code block needs locking..............
}
If multiple threads are operation on same object, then there may be a chance of data inconsistency problem, this is
called RACE Condition, we can overcome this by synchronized keyword
While a thread Executing synchronized method on the given object, if the remaining threads are allowed to execute
no other synchronized methods simultaneous on the the same object.
The advantage of synchronize block over synchronized method is performance and reduction of wait time
A thread can acquire multiple locks simultaneously
What is Synchronized statement The statements present in synchronized block (not a JAVA concept)
Inter-thread Communication
Two threads can communicate with each other with wait(), notify(), notifyall() methods. The thread which is
expecting updation is responsible to call wait() method, then the thread will enter into waiting state.
The thread which is responsible to perform updation, after performing updation it is responsible to call notify
method. Then Waiting thread will get that notification and continue its execution, with those updated items.
wait, notify and notifyall methods are present in object class but not in thread class, because the Thread will call
the wait and notify method of a class which is actually doing business logic.
To call a wait method on an object then that thread should be the owner of the object, The thread is called owner
of the object when it has the lock on the object, that is the thread should be in synchronized area, So if we try to
execute Wait, notify, notifyall outside the synchronized area then it will throw an error
IllegalMonitorStateException
If a Thread calls wait method on any object then it releases the lock of the particular object and enter into Wait
state. If the notify and notifyall the lock is released but may not be immediately
Except wait, notify and notifyall methods nowhere the thread releases the lock of the object.
Variations of Wait
public final void wait() throws InterruptedException
public final native void wait(long ms) InterruptedException
public final void wait(long ms, int ns) InterruptedException
Variations of Notify
public final native void notify()
public final native void nofifyall()
Every Wait method throws interrupted exception, which is checked exception, so we should handle these
interrupted exception
When the Waiting thread gets notification to continue, from waiting state it will go to another state of waiting to
acquire the lock back, and once it gets the lock then it will go to Ready state
Producer Consumer Problem
Producer thread is responsible to produce items to the thread and consumer thread is responsible to consume
items from the queue, if the Queue is empty then consumer thread will call wait() and enter into waiting state,
after producing item to the queue producer thread is responsible to call notify thread, then waiting consumer will
get the notification and continue its execution with the updated items
Difference between notify and notifyall
1. we can use notify method to give notification to only one thread, if multiple threads are waiting only one
thread will be notify and the remaining threads have to wait for further notifications, which thread will be notified
cant be expected JVM does randomly.
2. we can use notify all to give notification for all waiting threads of an Object, even though multiple thread
is notified, execution will be performed one by one because thread required lock on the object where it contains
only one exam.
Deadlock
No Resolution available for deadlock but prevention techniques are available.
class A{
public synchronized void d1(B b){
System.out.println("Thread 1 starts D1 method of Class A");
try {
Thread.sleep(6000);
} catch (InterruptedException e) {}
System.out.println("Thread1 trying to call B Class's last method");
b.last();
}
public synchronized void last(){
System.out.println("Inside A's last method");
}
}
class B{
public synchronized void d2(A a){
System.out.println("Thread 2 starts D2 method of Class B");
try {
Thread.sleep(6000);
} catch (InterruptedException e) {}
System.out.println("Thread2 trying to call A Class's last method");
a.last();
}
public synchronized void last(){
System.out.println("Inside B's last method");
}
}
class Deadlock extends Thread{
A a = new A();
B b = new B();
public void m1(){
this.start();
a.d1(b);
}
public void run() {
b.d2(a);
}
public static void main(String[] args) {
Deadlock d = new Deadlock();
d.m1();
}
}
While using Synchronized situation should be carefully
Deadlock vs Starvation
Long waiting of a thread where waiting never ends is deadlock
Long waiting of a thread where waiting ends at some specific point is called starvation (Eg low priority thread
should wait till all the high priority threads completed execution)
Daemon Threads
The threads which execute in the background is called daemon threads, eg Garbage collector, signal dispatcher,
attach listener etc
The main objective of Daemon threads is to provide support for non daemon threads(Main thread), for eg if main
thread runs with low mwmory then JVM runs garbage collector to destroy useless objects, so the amount of free
memory increases and main thread can run easily
Daemon threads will initially run with low priority. but if it needs to work, then JVM will increase the priority to 10,
so the daemon thread runs and cleans up memory then JVM will reduces the priority to 1 so other threads can
resume their jobs.
There are two methods
public boolean isDaemon()
public void setDaemon(boolean)
the changing the daemon nature is allowed before starting of a thread. If we try to do it after then we get error
IllegaThreadStateException
Default Nature of Thread
Main thread is normally is non-Daemon, Other threads inherit the nature from parent.
When all the Non-Daemon thread completes then all Daemon threads will be terminated
Green Thread
Java multi threading concept is implemented by using two models
1. Green thread model
2. Native OS model
In Green thread model the Thread life cycle is completely managed by JVM without underlying OS support. Very
few OS like Sun Solaris provide support for Green thread model ad it is deprecated
In Native OS model the thread is managed by JVM with the help of underlying OS. Windows based OS support only
this model.
How to stop a thread
We can stop a thread Execution by using stop method of thread clause,
public void stop()
if we call stop method then immediately the thread will enter into dead state, this method is deprecated and not
recommended to use.
How to suspend and resume a thread
Suspend and Resume operations on a thread is deprecated and not recommended to use.
https://www.youtube.com/watch?v=21KT--VtawI&index=91&list=PLd3UqWTnYXOmx_J1774ukG_rvrpyWczm0
time 31:00
Advanced Multi-threading
Thread Group
Based on Functionality we can group threads into a single unit called thread group. Like thread thread group also
contain sub-thread group
The main advantage of thread group is we can perform common operations easily. Every thread in java belongs to
some group, Main thread belongs to System Group. Every thread group in java is child group of System either
directly or indirectly, so system group acts as root for all thread groups in java
Systems group contains several system level threads like
1. Finalizer (Garbage collector)
2. reference handler
3. signal dispatcher
4. attach listener etc
ThreadGroup g = new ThreadGroup(String groupname)
Creates a new group with the specified name, the parent of the new thread group is the thread group of currently
executing thread
ThreadGroup g = new ThreadGroup(Threadgroup pg, String Group Name)
The parent of the new ThreadGroup is the pg
Important Methods of ThreadGroup Class
1. String getName()
2. int getMaxPriority()
3. void setMaxPriority(int p) => sets max priority for the group and the maximum value that could be set is
10. If max-priority is reduced, the existing priority value of the threads will not reduce but the newly added will
reduced to match this maximum allotted value
4. ThreadGroup getParent()
5. void list() => it prints information about the ThreadGroup to console
6. int activeCount() = > active threads in the Thread group
7. int activeGrouupCount() => active thread groups in the Thread group
8. int enumerate(Thread[] t) => copy all threads of this active thread group into the provided Thread Array,
in this sub-thread group threads are also considered
9. int enumerate(ThreadGroup[] t) => copy all active subthread groups of this active thread group into the
provided Thread Array
10. boolean isDaemon()
11. void setDaemon(boolean b)
12. void interrupt() = > to interrupt all waiting or sleeping threads in the thread group
13. void destroy() => to destroy thread group and its sub thread groups
Java.util.concurrent package
The problem with traditional synchronized keyword,
1. We are not having any flexibility to try for a lock without any waiting.
2. There is no way to specify maximum waiting time for a thread to get lock, so that Thread will wait until
getting the lock which may create performance problems and deadlock.
3. If a thread releases the lock we don't have any control on which thread will get the control of the lock
4. there is not API to list out all waiting threads for a lock
5. In synchronized key word we can achieve locking either at method level or within a method, and it not
possible to use multiple methods, ie acquire while executing method m1() and calls m2(), and releases at half
execution of m2()
To over come these issues SUN introduced java.util.concurrent package from version 1.5 where multiple
enhancement option to have more control over concurrency
Lock Interface
1. It is similar implicit lock acquired by a thread to execute synchronized method or block.
2. Lock implementations provides more extensive operations than traditional implicit locks
Important methods of Lock Interface
void lock() we can use this method to acquire a lock, if a lock is available then current thread will get the lock. If the
lock is not available then it will wait until getting the lock, it is exactly same behavior of synchronized keyword
boolean trylock() This method will try to acquire the lock, if the lock is available then the thread acquires the lock
and returns the lock, if the lock is not available then this method returns false then this method can continue its
execution without waiting, in this case thread never enters into waiting state
if(l.trylock())
perform lock based opertions
else
Perform alternative operations
boolean trylock(long time, TimeUnit unit) if the lock is available then it acquire the lock and continue execution, if
the lock is not available then the thread will wait till the specified amount of time. Still if the lock is not available
then thread can continue its execution
TimeUnit is an ENUM in java.util.concurrent package
enum TimeUnit{
NANAOSECONDS,
MICROSECONDS,
MILLISECONDS,
SECONDS,
MINUTES,
HOURS,
DAYS,
}
void lockInterruptibly() acquires the lock if available and returns immediately if the lock is not available then it will
wait, while waiting if the thread is interrupted then thread wont get the lock
void unlock() To release the lock, to call this method, the current should be owner of the lock, if not it raise
RunTime Exception : IllegalMonitorStateException
The implementation class for the locks is Reentrantlock(c):
It is the implementation class of lock interface and it is the direct child class of Object. Re-entrant means a thread
can acquire same lock multiple times without any issue. Internally Re-entrant lock increments threads personal
count when ever we call lock method and decrements count value when ever thread calls unlock method, and lock
will be released when ever the count releases 0
Constructors
Reentrantlock l = new Reentrantlock();
Reentrantlock l = new Reentrantlock(boolean fairness); The longest waiting thread will get chance if the fairness is
true, the default value is false
and the following methods are available in addition to the Lock interface methods
int getHoldCount() => gets number of holds it has
boolean isHeldByCurrentThread()
int getQueueLength() =>
collection getQueuedThreads()
boolean hasQueuedThreads()
boolean isLocked()
boolean isFair()
Thread getOwner()
Thread pool
Creating a new thread for every job creates performance and memory problems, to overcome this we should go for
thread pool.
Thread pool is a pool of created threads ready to do our job, Thread pool framework was introduced in Java 1.5
version to implement thread pools
Thread pool framework is also known as executor framework
ExecutorService es = ExecutorService.newFixedThreadpool(3);
the above statement will create a thread-pool with 3 threads
we can submit a runnable job by using submit method.
es.submit(job)
we can shutdown executor service by using shutdown method
es.shutdown()
While Developing web-servers and application servers we use thread pool concept
Callable and Future
1. In the case of runnable job Thread wont return anything after completing a job, if wwe need the thread
to return something after executing the job then we should go to Callable. The interface of Callable contains one
method call(). The definition is public Object call() throws Exception
2. If we submit a callable object to a thread, after completing the job the Thread returns an Object of the
type Future, ie Future object can be used to retrieve the result from callable job using get method
Runnable vs Callable
Runnable Callable
Thread wont return nothing Thread Return something
Interface contains only one method. Run method Interface contains only one method. Call Method
Return Type is Void Return type is Object
For Exception we need to do it using Try_Catch because the parent not throwing any exception For Exception we
can use Throws Exception
Java 1.01.5
Present in Java.Lang Package Present in Java.Util.Concurrent Package
Thread Local
Thread Local class provides Local variables for thread. ThreadLocal Class maintains values per Thread basis. Each
ThreadLocal object maintains a separate value like UserId Transaction ID etc. For Each Thread that access that TL-
object, Thread can access its local value and it can manipulate and even remove its value.
In every part of the code which is executed by the thread we can access its local variable. Eg: Consider a servlet
which invokes some business methods, we have a requirement to generate a unique transaction ID for each and
every request and we have to pass this transaction ID to the business methods. For this requirement we can use
Thread Local to maintain a separate transaction ID for every request ie for every thread.
Note:
1. Introduced in 1.2 version and enhanced in 1.5
2. Can be associated with Thread Scope
3. Total code which is executed by the thread has access to corresponding Thread Local variables
4. An thread can access its own local variables and can't access other threads local variables
5. Once Thread entered into thread state all its local variables are by default eligible for Garbage collection
How to Create Thread Local
ThreadLocal TL = new ThreadLocal();
possible methods
1. Object get() Returns the value of Thread Local variable associated with current thread
2. Object initialValue() returns initial value of Thread Local variable associated with current thread
3. The default implementation of this method returns null
4. To customize our own initial value we have to override this method
5. void set(Object newValue) to set a new value or change the value
6. void remove() to remove the value of Thread Local associated with current thread (Introduced in 1.5
version)
7. After removal if we try to access, it will re-initialized again by invoking its initial value method.
Overriding of Initial value method
class ThreadLocalDemo
{
public static void main(String[] args)
{
ThreadLocal tl = new ThreadLocal()
{
public Object initialValue()
{
return "abc";
}
}
System.out.println(tl.get()); ///abc
tl.set("Sen");
System.out.println(tl.get()); ///abc
tl.remove();
System.out.println(tl.get()); ///abc
}
Thread Local vs Inheritance
1. Parent Thread's Thread Local variable by default not available to the child thread, if we want to make it
available to child we need to use InheritableThreadLocal class
2. By Default Child thread's value is exactly same as parent thread value, but we can change the value by
overriding childValue Method
3. Constructor InheritableThreadLocal t = new InheritableThreadLocal ()
4. InheritableThreadLocal is the ThreadLocal, so all the methods of parent there is another method names
public Object childValue( Object parentValue)
class ParentThread extends Thread{
// static ThreadLocal tl = new ThreadLocal();
static InheritableThreadLocal tl = new InheritableThreadLocal()
{
public Object childValue(Object p){
return "CC";
}
};
public void run(){
tl.set(" PT ");
System.out.println("Value of " + Thread.currentThread().getName() + ParentThread.tl.get());
ChildThread ct = new ChildThread();
ct.setName("Child Thread");
ct.start();
}
}
class ChildThread extends Thread{
public void run(){
// ParentThread.tl.set("CT");
System.out.println("Value of " + Thread.currentThread().getName() + ParentThread.tl.get());
}
}
class ThreadLocalDemo1{
public static void main(String[] args) {
ParentThread pt = new ParentThread();
pt.setName("Parent Thread");
pt.start();
System.out.println("Value of " + Thread.currentThread().getName() + " Thread " + ParentThread.tl.get());
}
}
In the above program if we are not overriding childValue method then the childValue method value will also be
"PP"
Inner Class
Sometimes we need to declare a class inside another class, those classes are inner class. Introduced in 1.1
If there is a tight dependability like an type can't exists without other type then we should use Inner Classes
eg:
University consists of several departments, without University there is no chance of existing of departments, so we
have to declare department class inside university class.
class University{
class Department{
}
}
The relation between outer and inner class is Has a Relationship (composition pr aggregation)
Bases in position and Declaration the inner classes are of 4 types
1. Normal or Regular => An inner class which was defined directly inside a class with name and non static
2. Method Local => An inner class that is defined inside
3. Anonymous
4. Static Nested
class Outer{
class Inner{
}
}
If we compile this code, we get two class files, Outer.class and Outer$Inner.class
Inside Inner class we can't declare any static members hence we can't declare main method and we can't run inner
class directly from command prompt. It is compile time error as Inner class can't have Static declarations
class Outer{
class Inner{
public static void m1(){
System.out.println("Inner class m1 method");
}
public static void main(String[] args){
Outer o = new Outer();
Inner i = o.new Inner();
i.m1(); //new Outer().new Inner().m1(); Alternative way to call the above
}
Within the inner class this always refer current inner class object, if we want to refer current outer class object, we
have to use then we have to use <Outer class name>.this
The applicable modifiers for outer class are
1. default
2. public
3. final
4. strictfp
5. absttract
The applicable modifiers for Inner class in addition to all the outer class are
1. private
2. protected
3. static
Nesting of Inner classes
We can declare another inner class inside inner class, this is called nesting
Method Local Inner classes
This option is best suited for situation that demands nested method, The scope of method local inner class is very
rarely used.
We can declare Method local inner class inside both instance and static methods, if we declare inner class inside
instance method, from that inner class we can access both static and non static members of outer class directly.
If we declare inner class inside static method, then we cannot access instance members of outer class from that
method local inner class
From method local inner class we can't access local variables of the method in which we declare inner class. if the
local variable declared as final then we can access.
class test
{
public void m1()
{
final x = 10;
class inner{
public void m2(){
System.out.println(x);
}
Inner i = new Inner();
i.m2();
}
public static void main(String[] args)
{
Test t = new Test();
t.m1();
}
The above example works fine, if the variable X is not declared as final then we get compile time error. The reason
for this behavior is as below.
If the method is completed and if there is some thread is still holding the reference of the inner class object which
is present in heap memory and once the method is over the other thread is accessing the method of inner class
which is refering the stack variable X, but the variable is destroyed from stack since the method execution is already
completed.
If the variable is final, then the compiler will replace all the final variable references with the constant value during
compilation, so there will be no issues in referencing the same.
Anonymous inner class
If we declare an inner class without name then it is called as anonymous inner class. There are following types of
anonymous inner classes
1. Anonymous inner class that extends a class
2. Anonymous inner class that implements an interface
3. Anonymous inner class that defined inside arguments
eg : Person Student = new Person(){ }
In the above example the Student object is created with reference to Parent object, also in this method we can
implement interface too
The .class file generated as implemetation class$1
Anonymous vs normal class
1. Normal class can extend a class and implements any number of Interfaces, but Anonymous can either
implement a interface or extend a class
2. Constructor cant be implemented in Anonymous classes, because the name of the class is not there
Anonymous Inner classes are useful in the following scenario's
1. GUI based application to implement even based listeners to perform some Action events
Static Nested Classes
Sometimes we can declare inner class with static modifiers, they are static nested classes
Various combinations of nested classes and interfaces
Class inside a class
Interface Inside a class :
Java.Lang
Introduction its impossible to write any java program without java.lang package. There is no need to import
java.lang package explicitly because all classes and interfaces of lang package is available to every java program by
default
Java.lang.object Every class in java is Object.This class defines 11 common methods for any class
1. public String toStrint()
2. public native int hashCode()
3. public boolean equals (Object o)
4. protected native Object clone() throws clone not supported exception
5. protected void finalise() throws rhrowable
6. public final Class getClass()
7. public final void wait() throws InterruptedExceptoin
8. public final void wait(long ms) throws InterruptedExceptoin
9. public final void wait(long ms, int ns) throws InterruptedExceptoin
10. public native final void notify()
11. public native final void notifyAll()
12. private static native void registerNatives() is a method needed for Object class, but not for the derived
classes
toString() if our class doesn't has its own toString() implementation it will execute from Object class, which actually
prints the Classname followed by @symbol and some value.
equals() This method checks the reference of the objects are same or not, ie both the object variable should point
to the same instance of the object to be true. The method is overridden for content comparison only in String Class,
not even in StringBuffer
getClass() This method returns class definition of the run-time object. This concept is called Reflection.
Java.lang.reflect.* is to be imported
import java.lang.reflect.*;
class GetClass1{
public static void main(String[] args) {
int count = 0;
Object o = new String("Senthil");
Class c = o.getClass();
System.out.println("Fullly qualified class name is " + c.getName());
Method[] m = c.getMethods();
for(Method m1: m)
{
count++;
System.out.println(m1.getName());
}
System.out.println("Number of methods in class "+c.getName() + " is " + count);
}
}
after loading every .class file, JVM will create an object of the type java.lang.class in the heap area. Programmer can
use this class object to get class level information
We can use getClass() very frequently in reflections
Finalize() is equal to Destructor in C++, it is generally used to perform cleanup activity, the garbage collector calls
finalize method and then destroy it
wait(), notify(), notifyall() are used for inter thread communication. The thread expecting updation will call wait
method so thread enters waiting state immediately, the thread which performs updation call notify(), the waiting
thread gets notificatin and continue its execution with those updates.
String
java.lang.string
1. String Objects are Immutable and String buffers are mutable String objects once created cannot be
modified, if in case we are trying to make any changes then a new object will be created with the changes.
2. String Class equals() method is over-ridden for content (Value) comaprison (if two String objects contain
same value then the result is true), but in StringBuffer it is not overridden so the objects will be compared.
Example 1:
String s = new String("Senthil") vs String s = "Senthil"
in the case of String s = new String("Senthil") two objects are created one in Heap area and other in SCP (String
constant pool) and s is always pointing to Heap object
in the case of String s = "Senthil" only one object will be crated in SCP (String constant pool) and s is always
pointing to that object
Note : Object creation in SCP is optional, first it will check is there any object already present in SCP with required
content, if Object exists then it will be re-used else a new object will be created. This rule is applicable only for SCP
and not heap
Garbage collector is not allowed to access SCP Area, hence even though object doesn't reference variable it is not
eligible for Garbage collection if it is present in SCP Area. SCP memory objects are destroyed at the time of JVM
shutdown, in web application at the time of web serve shutdown
String s1 = new String("Senthil") -> Creates in Heap and SCP
String s2 = new String("Senthil") -> Creates in Heap
String s3 = "Senthil" -> Refers the object in SCP created while creating s1
String s4 = "Senthil" -> Refers the object in SCP created while creating s1
Heap SCP
s1 ->Senthil s3, s4 -> Senthil
s2->senthil
Example 2:
String s1 = new String("Durga"); => Creates two objects "Durga" in heap and
s1.concat("Software"); => Creates a string "DurgaSoftware" in heap area since it is created in runtime, Also the
object is not stored in and reference variable its immediately availabe for garbage colector, SCP added with
“Solutions“
String s2 = s1.concat("Solutions"); => Created a String object “DurgSolutions” in heap and assign it to
s1 = s1.concat("soft"); => Created “soft” in SCP, and ”Durga soft” in Heap and s1 starts points to this after the
execution
SOPL(s1); => Prints Durga soft
SOPL(s2) => Prints durga solutions
For every constant an object will be placed in SCP Area
because of some runtime operation if an object is created then that object is placed only in the heap area but not in
SCP Area

String Constructors

String s = new String();


Creates an empty string object

String s = new String(String literal)


Creates a string object for the given String literal

String s = new String(SringBuffer sb)


Creates an equivalent string object for the given string buffer

String s = new String(char[] c)


Creates a string with the characters of the char array, char[] ch = {“a”,”B”,”c”,”d”}; String s = new Sring(ch); => s =
“aBcd”;

Important Methods of String Class


public char charAt(int index)
public String concat(String s), The overloaded + and += is also meant for concatenation purpose only.
public boolean equals(Object o)
public boolean equalsIgnoreCase(String s)
public String substring(int begin) => returns substring from begin index to end of string
public String substring(int begin, int end) => returns substring from begin index to end -1 index of string

Note*** Due to runtime operation, if there is change in the content, then with those changes a new object will be
created in the heap, if there is no change in the content then existing object will be re-used and a new object wont
be created.

String s1 = new String("durga"); New Object created in heap and SCP


String s2 = s1.toUpperCase(); New Object created in upper case in heap
String s3 = s1.toLowerCase(); No New object created because lower case string already available in the heap as s1
and s3 points to same
System.out.println(s1 == s2); false
System.out.println(s1 == s3); true
String s4 = s2.toLowerCase(); A new object created in heap since Caps to lower needs conversion of data, wont
bother if the object already exists in heap memory

Example5: String s = new String(byte[] b)


Byte[] b = {100,101,102,103};
String s = new String(b);
SOPL(s); ==>defg

StringBuffer: Advantages of StringBuffer over string is the content changes will happen in the same object, So
changes happen in the content often then the best option is to use StringBuffer.

StringBuffer sb = new SringBuffer(); Creates StringBuffer object with 16 Chars


1. The String buffer initial capacity is 16 character
2. Once the capacity of the StringBuffer is reached then a new StringBuffer is created with (current capacity
+ 1) * 2 size and contents are copied and added the next characters with it. The old Buffer is now eligible for
Garbage Collection
3. Default size is 16 charcters

StringBuffer sb = new Stringbuffer(int initial capacity)


StringBuffer sb = new StringBuffer(String s)
StringBuffer sb = new StringBuffer("Senthil") => creates with string length + 16

StringBuillder
Every method in StringBufffer is Synchronised, Hence only one thread is allwed to operate on StringBuffer Object at
a time, which may create performance problems, to handle this in 1.5 version StringBuilder was introduced.

StringBuilder and StringBuffer are mostly same as StringBuilder with making it non Synchronised methods.

StringBuffer is Thread Safe, and builder is non thread safe


Since only one thread allowed to perform on StringBuffer is lower performer and StringBuilder can operate on
multiple thread increasing performance

Wrapper Class
The Main Objective of wrapper class is to Wrap primitive into object form to handle them like Objects
Secondly to create utility methods for various purposes.

Constructors
All Primitive contains one wrapper classes

Most Wrapper constructor has its own wrapping type and String, except following
1. Float contains => float, String, and double
2. Character contains only char type
Boolean string behaves differently, if the case insensitive value is true then it is true, else it is false.
Utility Methods
1. valueOf()

2. xxxValue()

3. parseXxx()

4. toString()

valueOf()

We can use this methods to create Wrapper object for the given Primitive or String, the forms of code is

Integer I = Integer.valueOf(“10”)

Every Wrapper class except character class contains a static valueOf() method to create wrapper object for the
given string

Every Integral (byte, short, integer, long) can use the method with Radix String option (Base Value). The allowed
range of Radix is 2 to 36. Because for base 36 the allowed values are 0-9,a-z

xxxValue() in total 38 (6 integral for 6 Intergral Objects, boolean and character)

Int to Double vaues will be got in primitive

Public char charValue()

Char ch = new Character(‘A’);

Char c = ch.charValue();

System.out.println(c); ==> A

parseXxx() Every wrapper class except the character class, contains the following parseXxx method to find primitive
for the string object.

Public static primitive parseXxx(String s,int Radix);

Int I = Integer.parseInt(“10”);
toString
String

parseXxx()
ValuOf()
toString()

Wrapper ValuOf() Primitive


Object Value

xxxValue()
Partial Hierarchy of java.lang Package
Conclusions

1. The wrapper classes which are not child class of number are Boolean and Character

2. The wrapper classes which are not direct child class of object are remaining Numeric type

3. String, StringBuffer, StringBuilder and all wrapper classes are final classes

4. In addition to String objects all wrapper class objects are also immutable

Void class

Sometimes it is considered as wrapper class. It is a final class and direct child class of object. It doesn’t contain any
methods and it contains only one variable, void.TYPE

It is the class representation of void keyword in Object

Autoboxing

Automatic conversion of primitive to wrapper object by compiler is called auto boxing

Eg Integer I = 10;

In the above example the primitive value of 10 is wrapped in Integer object automatically

Auto Unboxing is automatic conversion of wrapper to Primitive by compiler is called auto unboxing

Eg : Interger I = new Integer(10);

Int I = I; //Compiler converts Integer to Int by auto unboxing, the compiler changes this line to int I =
I.intValue()

Interget X = 10;

Integer Y = X;

X++;

SOPL(X);

SOPL(Y);

SOPL(X==Y);

Result is

11

10

False

The reason is the Wrapper class objects are immutable and if performing then a new object will be created and
referred to the object.
Internally to Provide support for autoboxing, a buffer of wrapper objects is created at the time of wrapper class
loading, by autoboxing if an object is needed to be created then JVM checks for this objects present in the buffer, if
it is present in the buffer then existing buffer object will be used, if it is not available then JVM will create a new
object

The same applicable to Valueof() method too

Because of widening is long introduced model the following applies

1. Widening dominates autoboxing

2. Widening dominates Vararg Method

3. Autoboxing dominate vararg because vararg gets lowest priority

AutoBoxing followed by Widening allowed

class Test{

public static void m1(Object o){

System.out.println("Object");

public static void main(String[] args) {

int x = 10;

m1(x);

Int ==(AutoBoxing)==> Integer ===(Widening)==> Object

The following are legal

int I = 10; nornal Valod

Integer I = 10; AutoBoxing Valid

int I = 10L; Possible loss of pression found long req int

Long l = 10L auto boxing

Long l = 10; Invalid in compatible type

long l = 10; widening

Object o = 10; Valid (autoboxing and widening)

double d = 10; valid Widening

Double D = 10; Invalid Incompatible types found int req double

Number n = 10 Valid Autoboxing Widening


Hashing related data structures follow the fundamental rule:
1. Two equivalent objects should be placed in same bucket but all objects present in the same bucket need not be
equal

Contract between .equals() and hashCode()

If two objects are equal in .equals() method then their hashcoded must be equal. Whenever override .equals()
method we should hascode method to satisfy above contract.

That is two equivalent objects should have same hashcode

Clone() method

The syntax is

Protected native object clone() throws cloneNotSupportedException

We need to implements cloneable, else it throws runtime exception clone no possible exception, The cloneable is
marker interface, means it has no methods

Shallow Cloning vs Deep cloning

Shallow cloning is also called as bitwise copy, it if there is an primitive variable then it will create a new instance
primitive variable for the cloned object, but if there is a reference then a new instance of reference variable is
created by pointing to the original reference object referencing object.(ie Objects of object are not created but
refereed)

File IO
File
File f = new File(“abc.txt”);

SOPL(f.exists()); false

f.createNewFile();

SOPL(f.exixts()); true

New File() If the file exists it will point to the file, if not exists then it creates a JAVA file Object to represent the file
as named.

The physical file will be created while f.createNewFile();

f.mkdir() is used to create a directory in the file system


FileWriter
FileWriter fw = new FileWriter(String fname)

FileWriter fw = new FileWriter(File f)

The above constructors are ment for overeriting the data, if in case we need to append using filewriter then

FileWriter fw = new FileWriter(String fname, boolean append)

FileWriter fw = new FileWriter(File f, boolean append)

The methods to write data to file is as below

1. write(int ch)

2. write(char[] ch)

3. write(String s)

FileReader
It is used to read the contents of the file from

BufferedWriter and BufferedReader


BufferedWritter bw = new BufferedWritter(Writer w);

PrintWriter
PrintWriter pw = new PrintWriter(String fileName)

PrintWriter pw = new PrintWriter(File f)

PrintWriter pw = new PrintWriter(Writer w)

It performs like system.out.print* methods

Methods available are

Write(int ch)

Write(char[] ch)

Write(String s)

Flush()

Close()

Print()

Println()
In general we can use readers and writers to handle character data (text), where as we can use streams to handle
binary data (like images, videos, audio etc)

We can use output stream and input stream to write and read binary data to and from file respectively

Serialization ver 1.1


Its the process of converting an object from JAVA supported form to network or file supported form and reverse is
DE-serialization

By using FileOutputStream and ObjectOutputStream classes we can implement serialization.

Object => ObjectOutputStream => FileOutputStream ===> serialization

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Dog implements Serializable{


String i = "Dog";
transient String j = "Class";
}

class Cat implements Serializable{


String i = "Cat";
String j = "Class";
}

class Bat implements Serializable{


String i = "Bat";
String j = "Class";
}

class Serial{
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException{
Dog d1 = new Dog();
Dog d2;
Cat c1 = new Cat();
Cat c2;
Bat b1 = new Bat();
Bat b2;
//Serialization starts
FileOutputStream fos = new FileOutputStream("D:\\DogSerial.demo");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(d1);
oos.writeObject(c1);
oos.writeObject(b1);
oos.close();
fos.close();
//Serialization Ends

//DE-Serialization starts
FileInputStream fis = new FileInputStream("D:\\DogSerial.demo");
ObjectInputStream ois = new ObjectInputStream(fis);
d2 = (Dog) ois.readObject();
c2 = (Cat) ois.readObject();
b2 = (Bat) ois.readObject();
ois.close();
//DE-Serialization ends
System.out.println(d2.i + " .... " + d2.j);
System.out.println(c2.i + " .... " + c2.j);
System.out.println(b2.i + " .... " + b2.j);
}
}
Its important to typecast the object while read since the return object from readObject method is Object.

Transient modifier applicable only for variables and not for method and classes, So the object is stored then the
variable is stored with default/initial value.

The order of serialization is important, the DE-serialization process extracts in the same order as serialized and if in
case it is done in other order then we get class cast exception

If we don’t know the order of serialization then we get desrialized to Object class and check for the instanceOf
method of the class and decide what object it is and then typecast to the right form to perform the action

Transient means not to serialize

Transient vs Static Static variable doesn’t participate in serialization because static variables are not part of
object

Serialization of Object Graph


When a class has reference of other class objects and if the object is serialized then the deep structure of
dependant classes are also serialized and DE-Serialized automatically The dependent structure is Object Graph.
Each object in the graph should implements serializeable in-order to perform serialization, else we get not
serializable exception occurs in run time.

Customized Serialization
During default serialization there may be a chance of loss of information due to transient keyword, to recover the
lost information in this process we need to do customized serialization
We can iimplement customized serialization by using the following methods

private void WriteObject(ObjectOutputStream os) Throws Exception

This method will be executed automatically during serialization, hence any activity that need to be performed
should be coded in this method.

private void ReadObject(ObjectInputStream is) Throws Exception

This method will be executed automatically at the time of DE-Serialization, hence we can code the activities to be
performed during DE-Serialization.

The above methods are callback methods, because these are executed automatically by the JVM.

The above methods are to be placed in the class of the objects that are to be serialized.

If in case we have transient primitive serialization then follow the below example for the same.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Account implements Serializable{
private static final long serialVersionUID = 1L;
String name;
transient String pass;
transient int pin;
Account(String Name, String Pass, int Pin){
name = Name;
pass = Pass;
pin = Pin;
}
private void readObject(ObjectInputStream is) throws Exception{
is.defaultReadObject();
pass = (String) is.readObject();
pass = epass.substring(3);
pin = is.readInt() - 4444;
}
private void writeObject(ObjectOutputStream oos) throws Exception{
oos.defaultWriteObject();
String epass = "123"+pass;
oos.writeObject(epass);
oos.writeInt(pin);
}
}
class CustomSerial{
public static void main(String[] args) throws Exception{
Account a = new Account("Senthil", "password");
FileOutputStream fos = new FileOutputStream("D:\\CUSSER.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(a);
oos.close();

FileInputStream fis = new FileInputStream("D:\\CUSSER.dat");


ObjectInputStream ois = new ObjectInputStream(fis);
Account a1;
a1 = (Account) ois.readObject();
System.out.println(a1.name + " ... " + a1.pass + " ... " + a1.pin);
ois.close();
}
}
1. If parent or child any one is implementing serializable interface then we can serialize the object

2. At the time of DE-serialization JVM will searches for variable inherited from non serializable parent, if found then
JVM ignore the original value and sets the default value for the variable to serialize by executing object instance
control flow

3. For instance control flow of non serializable parent JVM calls No-Arg constructor, it could be programmer
defined or compiler defined.

Externalization version 1.1


In serialization everything taken care by JVM and programmer have no control. In serialization it always save the
whole object and not possible to save a part of it, which could result in performance problems. To overcome this
problem we should go for externalization

The main advantages are based on requirement we can save part of object which improves performance.

To achieve externalization the class should implements Externalizable interface, which contain two methods

1. writeExternal()

2. readExternal()

Externalizable is child of Serializable


Externalizable class should have public no-arg constructor not default constructor
import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

class ExternalDemo implements Externalizable{


String s; int i; int j;
public ExternalDemo(){
System.out.println("No Arg Constructor");
}
ExternalDemo(String S, int I, int J){
s = S; i = I; j = J;}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(s);
out.writeInt(i);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
s = (String) in.readObject();
i = in.readInt();
}
}
class Externalize{
public static void main(String[] args) throws Exception{
ExternalDemo e1 = new ExternalDemo("Senthil",10,20);
FileOutputStream fos = new FileOutputStream("D:\\External.dat");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(e1);
os.close();
fos.close();

FileInputStream fis = new FileInputStream("D:\\External.dat");


ObjectInputStream is = new ObjectInputStream(fis);
System.out.println("Deserialization Starts");
ExternalDemo e2 = (ExternalDemo)is.readObject();
is.close();
System.out.println(e2.s + " ... " + e2.i + " ... " + e2.j);
}
}
Transient key wont play any role in Externalization

SerialVerionUID
In Serialization both sender and receiver need not to be the same.
At the time of serialization the JVM will generate the UID based on the Serailizable class and creates the file. On the
DE-Serialize end the the object ID is generated based on the de0seriallize object and if both the UID matches then
the action happens.
1. The UID generation is depend on machine, OS and version, so if sender and receiver have different configuration
then the UID generated would be different and de-serializaiton may fail
2. If the .class file is different from sender and receiver end then it will fail
3. JVM generated UID involves overhead which could create performance issue

Regular Expression
import java.util.regex.*;
class Patter{
public static void main(String[] args) {
Pattern p = Pattern.compile("ab");
Matcher m = p.matcher("abbabbba");
while(m.find())
{
System.out.println(m.start() + " ... " + m.end() + " ... " + m.group());
}
}
}
A pattern object is a compiled version of regular expression. It is a java equivalent object of pattern.
We create a pattern object by using compile method of pattern class, and search for the match using matcher
method of pattern class returns Matcher Object.
Pattern and Matcher classes present in java.util.regex package from 1.4 version
Character classes
[a-z] small characters
[^a-z] non small characters
Predefined character classes
\s Space
\S except Space
\d digit [0-9]
\D Except Digit [^0-9]
\w any word [a-zA-Z0-9]
\w except word [^a-zA-Z0-9]
. Any character
Quantifiers
Quantifiers are used to specify number of occurrences to match
a => Exacctly 1 a
A+ => Atleast one A
A* => any number of A atleast 1 number
A? => Atmost one A either 1 or zero

Split method
Split method splits the string based on the character given.
Pattern p = Pattern.Compile(“\\.”);
String [] s = p.Split(“www.gmail.com”);
For( each s1:s)
SOPL(s1);
Gives output as
www
gmail
com

String Tokenizer
Present in java.util.package
The Default Regular expression for StringTokenizer is space
import java.util.StringTokenizer;
public class StringTokenize {
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("15-04-2019");
while(st.hasMoreTokens())
System.out.println(st.nextToken("-"));
}
}

Write regular expression to represent all valid 10 digit mobile numbers


Every number should contain exactly 10 digits
First digit should be 7 or 8 or 9
[789][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]
[7-9][0-9]{9} is the short representation of the above expression
0?[7-9][0-9]{9} is the short representation of the above expression with optional zero at the beginning
(0/91)?[7-9][0-9]{9} is the short representation of the above expression with optional 0 or 91 at the beginning

Write a regular expression to represent all valid mail ids


[a-zA-Z0-9][a-zA-Z0-9_.]*@[a-zA-Z0-9]+ ([.][1-zA-Z]+)+
[a-zA-Z0-9][a-zA-Z0-9_.]*@gmail[.]com =? any mail id with gmail.com

Yava Language Identifiers


Allowed characters are
1. A-Z a-z 0-9 # $
2. Length of each identifier should be atleast 2
3. The first character should be lower case alphabet symbol from a-k
4. Second character should be a digit divisible by 3
The reg ex for the above rule is
[a-z][0369][a-zA-Z0-9#$]*

Program to check Mobile number for India


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

public class StringTokenize {


public static void main(String[] args) {
String s = "91919191919191";
Pattern p = Pattern.compile("(0/91)?[789][0-9]{9}");
Matcher m = p.matcher(s);
if(m.find() && m.group().equals(s))
{
System.out.println(m.group());
System.out.println("Valid");
}
else
System.out.println("Invalid");
}
}

Write a program to read all mobile numbers present in the given input file where mobile number is mixed with
normal text data.

Collections
Collection is a entity which represents a group of objects as a single entity
Collection Framework is the interfaces and classes which enables the collections concept possible. (Collections API)

An array is an indexed collection of fixed number of homogeneous data elements (except Tree set and Tree Map).
The main advantage of arrays is to represent multiple values by a single variable, so that readability of the code will
be improved
Limitations of Arrays
1. Fixed in size , run time manipulation of number of objects is not possible
2. It stores only homogeneous object
3. It is not implemented based on some standard data structure, hence ready made support is not available, for
every requirement we have to code explicitly increases the programming complexity.

To overcome these shortcoming we can use collections


Arrays vs Collections
1. Arrays are fixed in size Collections are growable
2. With respective to memory arrays are not recommended
3. Arrays performance is better than Collections
4. Arrays hold only homogeneous but collections holds both homogeneous and heterogeneous
5. Arrays has no underlying data structures, so no methods are available
6. Arrays can hold primitive objects and objects where collections can hold only objects

9 key interfaces of collection framework


1. Collction
2. List
3. Set
4. SortedSet
5. NavigableSet
6. Que
7. Map
8. Sorted Map
9. Navigable map
Collection
To Represent a group of individual objects as single entity we need some most common method for any collection
object. In general it is considered as root interface of collection framework
There is no concrete class that implements collection interface directly

Collection is an interface where collections is a class with utility methods for collection like sort, search etc.
Collection(I) 1.2
==> Lists(I) 1.2 Insertion Order maintained and Duplicates allowed
==>ArrayList 1.2 Java
==>LinkedList 1.2 Java
==>Vector 1.0 Java Legacy
==>Stack 1.0 Java Legacy
==> Set(I) Insertion order is not maintained but duplicates not allowed, Objects are single entity 1.2
==>HashSet 1.2
==>LinkedHashSet 1.4
==>SortedSet(I) 1.2Has some sorting order, Child of Set
==>NavigableSet(I) 1.6 V Has navigation methods like previous, next etc, TreeSet 1.2 is the
Implementation class
==>Queue(I) 1.5 Java
==>PriorityQueue 1.5
==>Blocking Queue 1.5
==>PriorityBlockingQueue 1.5
==>LinkedBlockingQueue 1.5

Map Objects Key-Value Pairs 1.2


Map is not child interface of Collection. If we need to represent group of objects as key-value pairs then Map is use.
Both Key and value are objects, Duplicate keys are not allowed but values can be duplicated.
Implementation classes for MAP
==> HashMap 1.2
==>LinkedHashMap 1.4
==>WeakHashMap 1.2
==>IdentityHashMap 1.4
==>Hashtable ==>Parent class is Dictionary(Abstract) 1.0 Legacy Classes
==>Properties 1.0 Legacy Classes

==>Sortedmap(I) 1.2 is a child interface of Map. If we represent a group of Key-Value pairs according to some
sorting order of Keys then we should go for sorted map. In Sortedmap the sorting should be based on key only not
value

==>Navigablemap(I) 1.6 is child interface of sorted map, it defines several methods for navigation purpose.
==>The implementation class is Treemap 1.2

The following Legacy characters present in collection framework,


1. Enumeration
2. Dictionary
3. Vector
4. Stack
5. Hashtable
6. Properties
For sorting we use two classes
1. Comparable(I) => default sorting order
2. Comperator(I) => custom sorting

To process the collection one by one we use


1. Enumeration(I) 1.0 Legacy
2. Iterator(I)
3. List Iterator (I)

Utility Classes
1. Collections
2. Arrays

Collection
To represent a group of individual objects as a single entity, Collection interface defines the most common methods
that are applicable for any collection object, Such as
1. boolean add(Object o)
2. boolean addAll(Collection c)
3. boolean remove(Object o)
4. boolean removeAll(Collection c)
5. void clear()
6. boolean retainAll(Collection c), Except the objects in collection c remaining are removed
7. boolean contains(Object o)
8. boolean containsAll(Collection c)
9. boolean isEmpty()
10. Int size()
11. Object [] toArray()
12. Iterator iterator()
List Interface
The insertion order preserved with respective to index, Duplicates are allowed and we differentiate them via Index.
The method present in addition to collection interface are
Void add()
void add(int index, Object o)
boolean add(int index, Collection c)
boolean remove(“A”)
boolean remove(int index)
Object get(int index) =>Replacement of the object with the specified object
boolean set(int index, Object o)
int indexOf(Object o)
int lastIndexOf(Object o)
ListIterator listIterator()
Array List
The underlying data structure for array list is Re-sizable Array or Grow-able Array, where it allows duplicate and
preserve order of insertion with heterogeneous object allowed (except Tree set/map) and null insertion is possible.
Constructor
ArrayList l = new ArrayList()
The above statement create an AL object created with default capacity (10 objects) is created, and if 11 th element is
added then a new AL is created with new capacity using formula (current capacity * 3 /2) + 1, and the division is
integral, The old object contents are copied to the new one and the AL reference moved to the new AL object and
the old will will be eligible for garbage collection.

ArrayList l = new ArrayList(int initial capacity)


AL created with specified capacity

ArrayList l = new ArrayList(Collection c)


If we need to create a collection for another type of collection then the above constructor is used.

import java.util.ArrayList;
import javafx.scene.effect.Light.Spot;
class Collect{
public static void main(String[] args) {
ArrayList L = new ArrayList<>(4);
L.add("A");
L.add(10);
L.add("B");
L.add(null);
System.out.println(L);
L.remove("A");
System.out.println(L);
}
}

Usually we use collections to hold and transfer objects from one location to another, to support for this
requirement Every Collection classes by default implements serializable and and clonable interfaces.
The ArrayList and vector classes implement RandomAccess interface, so that any random element can be
accessed with the same speed. This ability is only for Array and Vector

RandomAccess interface is is java.util package, it contains no methods, it is a marker interface, the required
ability is provided by JVM

Array list is the best choice if our frequent operation is read (Because it Implements Random Access Interface), it is
the worst choice if our frequent operation is insertion or deletion in the middle (since it need to re-align the objects
index)

Difference between ArrayLit and Vector


Aray List Vector
Every method is present is Non Synchronized Every method is present Is Synchronized
Non-Thread safe Only one thread is allowed to operate- So Thread safe
High Performance Lower performance
1.2 version 1.0 version Legacy object

How to get Synchronized version of ArrayList Object


By Default ArrayLit is non synchronized but we can get a synchronized version of AL object by using Synchronized
list (method) of Collections class.
Public static List synchronizedList(List l)
ArrayList l = new ArralyList();
List l1 = Collections.synchronizedList(l);
L is non synchronized and l1 is synchronized

Similarly we can get Synchronized version of set and map object from the Collections class
public static Set synchronizedSet(Set s)
public static Map synchronizedSet(Map p)

Linked List
The concept of C double linked list.
LinkedList l = new LinkedList() => creates an empty linked list object
LinkedList l = new LinkedList(Collection c) => creates an equivalent linked list object for the collection

Linked list Class specific methods


Usually we use linked list to develop stack and queues, to provide support for this requirement linked list class
defies the following specific methods
1. Void addFirst()
2. Void addLast()
3. Object getFirst()
4. Object getLast()
5. Object removeFirst()
6. Object removeLast()

Vector
The underlying data structure is Re-Sizable array or growable arraw with following properties
1. Insertion Order
2. Duplicates allowed
3. Heterogeneous
4. Null insertion allowed
5. Serializable, Cloneable, and RandomAccess Interfaces implemented
6. Thread safe operation
Constructors
Vector v = new Vector() creates an empty vector object with initial capacity 10, ,once reaches the max capacity a
new object will be created with new capacity = current capacity * 2
Add(Object o) => collection interface method
add(int index, Object o), List
addElement(Object o) Vector

Remove(Object o) - C
removeElement(Object o) V
remove(int index) L
removeElementAt(int Index) V
Clear() C
removeAllElements() V

Stack Class
There are 5 stack specific operations
Object push(Object o)
Object pop()
Object peek()
Boolean empty()
Int search(Object O), returns the offset of the item in stack from top as 1 and bottom as size, if not found -1

The 3 cursors of java


If we need to process objects sequentially from the collection then we should use cursor, the types of them are
1. Enumeration
2. Iterator
3. List Iterator

We can use Enumeration to get get objects sequentially from legacy collection object. We can create enumeration
objects by using elements method of vector class.
Public enumeration elements() => Enumeration e = VectorObject.Elements()
Public boolean hasMoreElements() => checks does this enumeration has more elements
public Object nextElement() =>Gets the next element in the vector’s cursor

Limitations
1. It is applicable only for legacy classes
2. Only read operation is possible

Iterator
It is universal cursor, In addition of Enumeration we can perform both read and remove operation.
Iterator itr = c.Iterator()
Methods
public boolean hasNext()
public Objectg Next()
public void remove()
Limitations
1. We can move only in forward direction, because these are single directional cursor
2. We can’t add or replace using the cursor

To overcome these shortcoming we should use List Iterator


LisIterator
1. This is a bi-directional cursor capable of navigating forward and backward direction
2. We can do addition and replace operations too.
There are 9 methods of its
public boolean hasNext()
public Object next()
public int nextIndex()
public boolean hasPrevious()
public Object previous()
public int previousIndex()
public void remove()
public void add(Objec o)
public void set(Object o)

The most powerful cursor is ListIterator, but its limitation is its applicable only for List Objects

Property Enumerator Iterator List Iterator


Applicable Area Legacy classes only For any Collection Object Only for List Objects
Is Legacy Object Yes 1.0 No 1.2 No 1.2
Direction Forward Forward Bi-Directional
Allowed Operation Read Read Remove Read Remove Replace Add
How to Instance Vector.Elements() Collection.iterator() ListInterface.ListIterator()
Methods hasMoreElementa() hasNext()
nextElement() next() 9 methods
Remove()

Sets
Collections (I) 1.2
==>Set (I) 1.2
==> HashSet 1.2
==> LinkedHashSet 1.4
==> SortedSet 1.2
==> NavigableSet(I) 1.6
==> TreeSet 1.2

In Set Duplicates are not allowed and order is not preserved, it has no methods implemented for them, so only the
methods available to collection is available

HashSet
1. The underlying data structure is hash table
2. Duplicate objects are not allowed
3. Insertion order is not preserved
4. It is based on hash code of the objects
5. Null insertion is possible
6. Heterogeneous objects are allowed
7. Implements serializable clonnable and random access interfaces
8. Best choice if our frequent operation is search operation

HashSet hs = new HashSet()


Default Initial capacity is 16 and default fill ratio is 0.75 (the bigger hash set object is created after the capacity
reaches 75% instead of waiting for the last element + 1 is getting filled)
HashSet hs = new HashSet(int initialCapacity)
Everything remains same as above constructor only with initial capacity

HashSet hs = new HashSet(int initialCapacity, float fillratio)

HashSet hs = new HashSet(Collection c)

Linked Hash set (1.4) is the child class of hash set, it is exactly same as has set(Including constructors and
methods) except it preserve the insertion order and its internal underlying object is Hash Table + Linked set
(Hybrid)
In general we use Linked Hash set to develop Cache based applications where duplicates are not allowed and
insertion order is preserved

Sorted Set
It is the child interface of set, if we want to represent some set of objects according to some sorting order without
duplicates, then sorted set is the right option. The methods specific to sorted set are
1. Object first(), returns the first object
2. Object last(), returns last element
3. SortedSet headSet(Object obj)
4. Sorted tailSet(Object obj)
5. SortedSet subSet(Object obj1, Object obj2)
6. comparator comparator()

TreeSet
Same properties as like normal set except no heterogeneous objects not allowed and not implementing
RandomAccess
TreeSet t = new TreeSet() with default natural sorting order
TreeSet t = new TreeSet( Comparator c) Creates an empty TreeSet object where the elements eill be inserted
according to customized sorting order specified by comperater object
TreeSet t = new TreeSet(Collection c) Default natural sorting order
TreeSet t = new TreeSet(SortedSet s) based on SortedSet’s sorting order

1. If we are trying to insert null to non empty Tree Set then we get null pointer exception
2. null is allowed as the first element to an Empty TreeSet but after null if we insert any other then we get Null
pointer exception
3. null insertion as a first element to the empty TreeSet, from 1.7 version null is not allowed at all for TreeSet

Considering the following example with homogeneous objects


import java.util.TreeSet;
class TreeSetDemo{
public static void main(String[] args) {
TreeSet t = new TreeSet();
t.add(new StringBuffer("A"));
t.add(new StringBuffer("C"));
System.out.println(t);
}
}
If we are depending on default natural sorting order then compulsory the objects should be homogeneous and
comparable else we get run time exception as cast cast exception.
If the class implements comparable interface only then they are comparable objects

Comparable Interface
It is present in java.lang package and it contains only one method and it contains only one method compareTo
public int compareTo(Obj o)

Eg Obj1.compareTo(obj2)
If return is negative then Obj is less than obj2
If return is positive then Obj is greater than obj2
If return is zero then Obj is equal to obj2

Comparator Interface
This is meant for customized sorting order

When ever we implement comparator interface it is compulsory to provide implementation only for compare
method because equals method implementation is implemented in Object Class.

Program to sort in reverse alphabetic order


import java.util.Comparator;
import java.util.TreeSet;

class StringReverse{
public static void main(String[] args) {
TreeSet t = new TreeSet(new DesendingString());
t.add(new String("Senthil"));
t.add(new String("Sappy"));
t.add(new String("Vaishu"));
t.add(new String("Swetha"));
t.add(new String("Adithi"));
t.add(new String("SriP"));
t.add(new String("Tomato"));
t.add(new String("Pranav"));
t.add(new String("Nethra"));
System.out.println(t);
}
}

class DesendingString implements Comparator


{
public int compare(Object obj1, Object obj2)
{
String s1 = (String) obj1;
String s2 = (String) obj2;
return s2.compareTo(s1);
}
}

Comparable Vs Comparator
1. For predefined comparable classes default natural sorting order already available available, if we are not satisfied
with the that default natural sorting order then we can define our own sorting by using Comparator
2. For pre-defines non comparable classes(like StringBuffer) default natural sorting order is not available, we can
define our own sorting logic by using comparator
3. For custom classes like Employee, the class creator is responsible for defining natural default sorting order by
implementing the comparable interface
4. The person using the custom class can either use the comparable interface, then he can define custom sorting
using comparator
Comparable Comparator
Default Natural sorting order Customized sorting order
Java.lang Java.util
compareTo() Compare() and equal()
String and all wrapper classes implements Only implemented in Collator and RuleBasedCollator

Comparison table Set Implemented classes


Property HashSet LinkedHashSet TreeSet
Underlying Dataset Hash Table Linked List + Hash Table Balanced tree
Duplicates Objects No No Not Allowed
Insertion order Not preserved Yes No
Sorting order Not applicable Not applicable Applicable
Heterogeneous objects Allowed Allowed Not allowed by default
Null acceptance Yes Yes Only null can be present in
set

Map
Maps are not a part of collection, its equivalence to dictionary object in python, it represents as key value pairs. It
is also knows as collection of entry objects
Map interface methods
Object put(Object key, Object Value)
If the object successfully added then it returns null, if the key is existing already then it the new value overwrite the
value for the key and the object with old value is returned.
void putAll(Map m)
Object m.get()
Object m.remove()
m.containsKey(Object key)
boolean m.containsValue(Object Value)
boolean m.isEmpty()
int m.size()
void m.clear()
Set keySet() Returns only the key values since they don’t contain duplicates
Collection values()
Set entrySet()
The Above methods are collection views of map

Entry Interface
A map is a group of key value pairs and each pair is called as an entry, hence maps is considered as collection of
entry objects. Hence entry interface is defined inside map interface
Interface map{
interface entry{
Object getKey()
Object getValue()
Object setValue()
}
}

Hash Map
1. The underlying data structure is hash table
2. Nsertion order is not prerserved and it is based on hash code of keys
3. Duplicate keys are not allowed but values can be duplicated
4. Heterogeneous objects are allowed for both key and value, null is allowed for key (only once) for values no limit
5. It implements clonnable and serializable but not random access
6. It is best choice is search operation

HashMap m = new HashMap() inital capacity 16 and fill ratio 0.75


HashMap m = new HashMap(int initial capacity)
HashMap m = new HashMap(int initial capacity, int float fill ratio)
HashMap m = new HashMap(HashMap m)

Example of map entry program


import java.util.Set;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
class maps{
public static void main(String[] args) {
HashMap m = new HashMap();
m.put(1,"Senthil");
m.put(2,"Sappy");
m.put(3,"Swetha");
m.put(4,"Adithi");
m.put(5,"Vaishu");
System.out.println(m);
System.out.println(m.put(5,"Vaishnavi"));
System.out.println(m);
Set s = m.keySet();
System.out.println(s);
Collection valc = m.values();
System.out.println(valc);
Set s1 = m.entrySet();
System.out.println("Sen" + s1);

Iterator i = s1.iterator();
while(i.hasNext()){
Map.Entry m1 = (Map.Entry) i.next();
System.out.println(m1.getKey() + "..." + m1.getKey());
if(m1.getValue() == "Sappy")
m1.setValue("Sapna");
}
System.out.println(m);
}
}

Hash map Hash table


Not thread safe / Non Synchronized Thread safe / Synchronized
Performance is better Performance is lower
Null is allowed for key and value Null is not allowed
1.2 version non legacy cllass Its legacy class

How to get synchronized version Hash map object


By default Hashmap is non synchronized but we can get Synchronized map by using Synchronized method of
Collections class
Hashmap m = new Hashmap();
Map m1 = Collections.synchrronizedmap(m);
LinkedHashMap
It is exactly same as HashMap including constructors and methods except the following differences
1. Underlying data structure is Linked list and Hash table (Hybrid data Structure)
2. Insertion order is preserved
3. Introduced in 1.2
Difference between == operator and .equals() method
Ingeneral == operator meant for reference address comparison where as .equals() method for content comparison

IdentityHashMap
It is exactly same as HashMap including constructors and methods except the following differences
JVM uses == operator to compare content comparison

WeakHashMap
It is exactly same as HashMap the following difference
In case of HashMapeven though the object have no reference it is not eligible for Garbage Collector if it is
associated with HashMap, IE HashMap dominates Garbage collector, but in case of weak hash map if the object
doesn’t contain any reference the object is associated with weak hash map

SortedMaps
It is similar to sorted sets for maps and has the same functions as like sorted sets

TreeMap
1. Underlying data structure is RED-BLACK tree
2. Insertion order not preserved, insertion happens based on the sorting order of the key
3. Duplicate keys not allowed but values allowed
4. If depending on default natural sorting order then keys should be comparable and homogeneous but if we have
comparator for our own sorting order
TreeMap t = new Treemap() Default natural sorting order
TreeMap t = new Treemap(Comparator c)
TreeMap t = new Treemap(Sortedmap m)
TreeMap t = new Treemap(Map m)

HashTable
The default initial capacity is 11 and fill ration is 0.75

Java Properties
1. It holds properties that are maintained in properties file
2. Both key and value pair should be String

Properties p = new Properties()

String getProperty(String pname)


String setProperty(String pname, String pvalue), => if key is present already the value is replaced and returns old
value
Enumeration prropertyNmes()
load(inputStrean is) => to load properties into properties object that come from properties file
Store(outputStrean os, String comment) => to save properties into properties object that come from properties file
Queues 1.5v
It is a child interface of collection
Methods of Queue
1. Offer (Object o) => Add an object to the queue
2. Poll() Remove and returns head element, if Queue is empty it returns null
3. Remove() Remove and returns head element, if Queue is empty then triggers NoSuchElementException
4. Peek() Returns head element, if Queue is empty it returns null, and wont remove the element
5. Element() Remove and returns head element, if Queue is empty it returns null, and wont remove the element

Priority Queue
1. If we need to hold data before processing then Queue
2. Default Natural sorting order or Customized sorting order using compartor
3. Insertion order is not preserved
4. Duplicates not allowed
5. Heterogeneous is possible with Customized sorting order else homogeneous is needed
6. Null is not allowed

Constructors
1. PriorityQueue q = new PriorityQueue()
2. PriorityQueue q = new PriorityQueue(int Initial capacity)
3. PriorityQueue q = new PriorityQueue(int Initial capacity, Comparator c)
4. PriorityQueue q = new PriorityQueue(SortedSet s) =>Default sorting order
5. PriorityQueue q = new PriorityQueue(Collections c)

1.6 Version Enhancements in Collection frame work


As a part of 1.6 version the following two concepts introduced in collection framework.
1. Navigable Set
2. Navigable Map

NavigableSet
It is the child interface of sorted set and it defines several methods for navigation purposes.
Collections class defines the following binary search methods
Public static int binarySearch(List l, Object target), if the list is sorted to Default sorting
Public static int binarySearch(List, Object target, Comporator c) if the list is sorted to Customized sorting

Binary search
The binary search is a method of collections object and it takes a array list as an argument and object to find, the
return type is integer where on successful find it returns the object index starting from zero and on an unsuccessful
find it gets the insertion point starting from -1.

In order to perform the Binary search operation the array list should be sorted in ascending order
If a custom sorting order is performed then in search too we need to
Reverse vs Reverse Order
We can use reverse method to reverse method to reverse order of list, Where as the reverse order method to get
reversed comparator.

Comparator c1 = Collections.reverseOrder(Comparator c)

Array Class
This is an utility class that define utility methods for Array objects
Sorting Elements of array
public static void sort(primitive[] p)
public static void sort(Object[] p)
public static void sort(Object[] p, Comparator c

We can sort the primitive arrays only on Default Natural Sorting Order, but Object array on both DNSO or custom
sorting order

Searching Elements of array


The following binary search methods
public static int binarySearch(primitive[] p, primitive primitive_target)
public static void binarySearch(Object[] p)
public static void binarySearch(Object[] p, Comparator c)

All rules of binary Search methods of Array class is same as Collections class

Conversion of array to list


public static List asList(Object[] a)
For the existing array we get list view by the above method, a new List object is not created by the method. Since
both the object refers to the same object if we perform any change using either of the object that change will be
reflected automatically to the other reference form.
By using list reference we cannot perform operation which modifies the size of an Array, such as remove or add. If
we try such operation then we get run time exception UnSupportedOperationException
Also we cannot modify with heterogeneous objects

Concurrent collection
Concurrent map interface contains following methods in addition to map interface
putIfAbsent(101,”Shiva”) => this entry will be added only if 101 key is not present, if it exists it will not replace the
old value with Shiva as like in maps.put() method

remove(101,”Shiva”) this method will remove entry only if key and value in the parameters matched

replace(key, value, new value)

1. The underlying data structure is Hashtable


2. It is possible to perform multiple read operations and thread safe update operation
3. To perform read no lock is needed, for writing we need bucket or segment lock
4. Concurrency level is number of locks available

You might also like