Presentation - Core Java

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

Java

Tutorials for
Beginners
what will learn today ???
• What do you mean by program ?
• Types of programming languages
• Differences between Procedural and Object oriented paradigms
• Modules of JAVA (J2SE,J2EE,J2ME)
• Differences between C,C++,JAVA
Introduction
• Program : Set of coded software instructions to control the
operation of a computer .

• Programming: It is a process of designing computer program.

• Paradigm: it is a way to classify programming languages based


on their features.

• Programming Language: it is a formal language which follows


different programming paradigm that produce various output.
Ex. C , C++, java , python etc
• a program, also called an application or software, is a set of
instructions that process input, manipulate data, and output a result.
• Examples : Microsoft word , Games , Goggle Chrome etc

• Paradigm : imperative , structured, procedure ,function ,object


oriented , event- driven .
Put simply, programming is giving a set of instructions to a computer
to execute. If you’ve ever cooked using a recipe before, you can think
of yourself as the computer and the recipe’s author as a programmer.
The recipe author provides you with a set of instructions which you
read and then follow. The more complex the instructions, the more
complex the result!”
Differences
Procedural Object Oriented
• In Procedural programming the • Object oriented programming
program is written as a based on objects which
collection of actions contains data and code :data in
(procedures)that are carried out the form of fields and code in
in a sequence , one after the the form of procedures.
other.
• Procedures also called as • Ex : Java, Python
functions.
• Ex: C language
C java
Introduction
Author : James Gosling

Vendor : Sun Microsystems(Oracle corporation]

Project Name : Green Project

Type : open source and free software

Initial name : Oak language

Extensions : .java & .class

Present Version : 15 version

Operating systems : Multi operating systems


Importance of java
• Java is used to develop:
J2SE
• Standalone Applications
• Desktop applications
J2EE
• Two tier Applications
• Web Applications
• Enterprise Applications
J2ME
• Mobile Application
• Smart Cards
• Games
• Robotics
Standalone appln:
The appln that doesnt depend on other appln .
The appln which has main method
The ouput can be seen on console.

desktop appln:The application that consists of menus, buttons, tool bars,


text fields, and other graphical features. The GUI is mainly for user
input, whether the user clicks a button or types in information,In
addition, GUI components often display information back to the user.

To create the GUI, you use the Java Foundation Classes/Swing


(JFC/Swing) and Abstract Window Toolkit (AWT) API. The many classes
and interfaces in those packages allow you to easily create buttons,
check-box objects, text fields, and other components, as well as
components to organize them.
• The two-tier architecture is based on
the Client-Server model.It consists of
Client-Application tier and Database
tier. The Client-Application server
communicates directly with the
Database server.
• The Client-Application sends the
request to the server and it processes
the request and sends back with data.
• The client-Application layer can be
build using languages such as C, C++,
Java, Python, PHP, .NET.

• Examples :
• Web Application :
• It is a type of computer program that usually
runs with the help of a web browser and also
uses many web technologies to perform
various tasks on the internet.

• A web application can be developed for


several uses, which can be used by anyone
like it can be used as an individual or as a
whole organization for several reasons.

• Examples: gmail,facebook etc


Simple : Because it has eliminated all the difficult and confusing
concepts like pointers .
Object oriented :Because the whole data is represented in the
form of object
Class Test
{
Features of java Data;
Data

}
Test T= new Test(); T
By using object reference we are calling all the methods , variables ..
Platform Independent : compiling the java program in one
OS(windows) and that compiled file (.class file) is executed in other
OS(linux) is called platform independent nature.

window
Source file compilation bytecode jvm s

linux
Test .java javac Test.class
macos
Distributed: By using java technology we are preparing standalone
applications and distributed apps.

Standalone App: It doesn’t need client server architecture.


Features of java Web App : It needs Client server architecture.
Distributed App: The project code is distributed in multiple number of
jvm’’s.
Architectural Neutral: java applications
compiled in one architecture and that compiled
program runs on any hardware architecture is Multithreaded: if any technology allows to create and execute more
called architectural neutral.
than one thread called as multithreaded.

Robust : Any technology if it is good at two


main areas it is said to be ROBUST Compiled and Interpreted: By using compiler we are converting
1.Exception Handling source code into bytecode and by interpreter we are converting bytecode
into executable code and interpreter is a part of jvm.
2.Memory Allocation

Secure : To provide implicit security java High Performance:


provide one component inside JVM called Security
Manager.
Identifiers RULE 4: It is recommended to take 15
characters as an identifier name .
Any name in java is nothing but identifier.
Int abcdefghijklmnopqrstuvwwxjcj=10
Classnames , Methodnames , Variable names (not correct)
RULE 1:An identifier will accept following characters RULE 5: We can’t take reserved words
0-9,A-Z,a-z,_,$ as identifiers names
class Test_App int switch=40; (wrong declaration)
{
}

RULE 2 : If we take other characters as identifier names


then we get compile time error called Illegal start of
expression.
int emp_id=101; ( declaration)
RULE 3: An identifier name must and should start with
alphabet but not with number.
Int 12a=30; (wrong declaration)
Int a12=30; (correct)
Keywords
--Keyword is a reserved word which has predefined meaning in the language.
--We have around 51 reserved
words in java
--Programmers cannot use keywords as names for variables ,methods ,classes
,or as any other identifier
--Ex: byte ,int ,float ,char, if, for ,while , switch ,new
--Keywords are always written in lower case.
Naming Coventions
ClassNames : It should always begin with a Packages: It is always written in lower case.
capital letter .If it has more than one word then
every second word should start with capital Ex. java.lang , java.io
letter.
Ex. class First_Session
{ InterfaceNames : they have same convention as
} class name.
Predefined classes : String , System , Thread ,
ArithmeticException , FileReader etc Ex. Runnable , Serializable,PreparedStatement

Method Names : It should begin with lower


case and if it has any multiple words every
second word should start with capital letter.
Ex public void firstOne()
{
}
Predefined methods : setName() , getPriority(),
run()
Sample code
class Hello
{
Structure of class
public static void main(String
class className args[])
{ {
Data;
Code;
System.out.println(“Hello World”);
} }

}
Class and object

Class •Class is a logical entity which is


used for writing logics of the
{
application.
Variables
Class is a userdefined blueprint
Methods from which objects are created .
Constructors •Object is a physical entity which
Instance blocks is used for allocating memory for
Static blocks logics of the application.
} •class is a group of objects that
share comon properties and
behaviours
Variables •Based on the position and declaration
these primitive variables are again
It is used to store some classified as
value •Local
--Based on the value •Instance
represented by the
variable, these variables •Static
are classified as two types •Local variables are accessible inside the
--Variables are the method , block constructor that declared
properties an object it.
knows about itself.
•Instance variables are defined inside the
--Primitive variable class for which each instantiated object of
Int x=10; the class has a separate copy
--Reference variable •Static variable is common to all objects of
Student s=new Student(); the class
Java areas

Instance area Static area


void methodOne() static void methodOne()
{ {
Instance area Static area
} }
Access Permissions
• Instance variables : they cannot be • Static variables can be
directly accessed from the static accessed directly from
area both the areas.
• If we want to access them from
static area we need to create
object
• Syntax:
Classname reference variable=new
Constructor();
• Ex Student s=new Student();
• They can be accessed directly
from instance area
Local Variable • Declaration: variables declared
inside the methods ,constructors ,
blocks
• Scope : The scope will always be
within the method or constructor
in which it is declared.
• Memory allocation : It is
allocated when method starts.
• Stored Location: Stack Memory
Instance Variables Static Variables
• Declaration: Inside the class but not
• Declaration: same as instance but
inside the methods , constructors.
are preceded with static keyword
• Scope : Inside the class all methods
• Scope : Throughout the class
and constructors are able to access
them. • Memory : It is allocated when .class
file is loaded and deallocated when
• Memory : It is allocated when object is
.class file is unloaded
created and deallocated when object is
destroyed. • Stored Location: Method area
• Stored location : Heap memory
Methods
Method syntax:
--A method is a block of code Modifier returntype methodname(parameter-list )
which only runs when u
{
call it.
Logics
--They are used to write logic of
the application. }
Ex: public void methodOne(int a)
Class Test {
{ //logics;
Int a=10; }
Int b=20; (Not Correct)
s.o.p(a+b);
Method signature: methodname along with parameters
} is called method signature
{ Directly writing business logic Ex: methodOne(int a) is method signature
is not allowed}
Every method contains three parts:
Class Test
{
🡪method declaration :
public void m1(int a)
ex: void methodOne(int a)
{
🡪method Implementation
Sysout(a);//logics
ex: logics
}psvm{
🡪method calling:
Test t=new Test();
ex: t.methodOne();
t.m1(56);
}
Topics to be covered in
methods Instance and static method

Methods with and without parameters

Two methods with same signature is not allowed in same class

Is return type mandatory or optional for methods

Does java supports inner method concept

method calling

If a method has instance and local variables with same name then priority goes to local variable.

Importance of this keyword

Inside static method ,this keyword is not allowed.

Method returntype maybe a primitive type,class type or array type.

Method returning variables

Template method

Method returning same class objects

Taking method arguments dynamically.


instance methods
• Although it is perfectly fine to define a class with only data members, it rarely happens.
Most of the time, we use methods to access the instance variables of the class.

• The instance method belongs to instances of a class, not to the class itself.

• Whenever a new object is created a new copy of instance method is created for that
individual object. So if 10 objects are created for a class then 10 copies of instance
methods will be created. Which uses more memory at run time.

• Instance method can access static variables and static methods directly
static methods
• Usually, the methods of a class are dependent on the object of the class. But, there will be
times when we want to define a method inside a class that can work independently. That is they
are independent of the objects of the class.

• In Java, it is possible to create a method inside a class that can be used by itself, without
reference to an instance of the class. This type of method is known as the static method. To
create such a method, we’ve to precede its declaration with the keyword static.

• we make a method static when the same resource is going to be use by many objects. So
instead of making it as instance we declare it as static method so that only one copy of that
method is created for all the object. This is how we can save the memory.

Restrictions
• They can only call other static methods inside them.
• They must only access static data.
• They cannot refer to this or super in any way.
This keyword
🡪this keyword refers the current class object in a method or constructor.
🡪The most common use of this keyword is to eliminate the confusion between
class attributes(instance variables) and parameters(local variable)with the same
name.
🡪It can be used with
1)Variables
Syntax : this.variablename
2)Methods
Syntax: this.methodname
3)Constructors
Syntax : this()
Constructors •Rules and regulations for
declaring constructor
They are used for writing logics
and these logics are executed at •Constructor name and classname
the object creation must be same.
They are used to initialize some •Constructor takes parameters
value to instance variables during
object creation •Constructor doesn’t allow return
type
•Constructor cannot be abstract ,
final, static and synchronized
•Constructors accepts all modifiers
public, private ,protected
Types of constructors
Predefined Userdefined
Default constructor : If a user explicitly defines a
Inside the class if we are constructor then it is known as
not defining any userdefined constructor
constructor then 1)Zero argument :if a
compiler generates zero constructor doesn’t accepts any
argument constructor.
parameter then it is known as
zero argument.
JVM doesn’t generates 2)Parameterized : if a
constructor instead constructor accepts parameter
compiler generates it.
then it is known as
parameterized.
To call constructor
from another
constructor we use
this keyword.
Constructor
calling

this();
Formats of Named object approach
object
creation Test t=new Test();

Nameless object approach

new Test();
.

Instance blocks Syntax:


They are used to write {
the logics and those //logics
logics are executed at }
object creation.
🡪constructor and instance block , both are executed at object
creation but always instance block is completed first and then
They are used for constructor will be executed.
initializing instance
variables 🡪constructor logics are specific to one object but instance
block is common to all objects.

🡪we can have multiple instance blocks but the order will be
from top to bottom.

🡪instance blocks execution depends on object creation but not


on constructor execution.
Static blocks
🡪Static blocks are used to write the logics and those logics are executed
during .class file is loaded.
Syntax:
static
{
//logics
}
🡪Static blocks are executed only once as class is loaded only once.
🡪Inside class multiple static blocks are allowed and order is from top to
bottom
🡪Static blocks are used to initialize static variables.
Class vs objects
Class object
• The class contains • Object is a physical entity which is
variables,methods,constructors,instance creating memory for the logics of the
blocks,static blocks. application.
• The class is a logical entity which contains • We create object by using new keyword.
logic of the application
• Class is a blueprint which decides object
creation without class we cannot create
objects.
• Test t = new Test();
• Test t1=new Test();
• Based on single blueprint we can design
multiple objects.
• We create class by using class keyword
Main method:
Jvm always checks for main method with the following definition
public static void main(String args[])

public: Jvm has to call this method from anywhere that’s why we
are declaring main method as public

static :without using object reference also jvm has to call the
method,that’s why we are declaring main method as static.

void :main method doesn’t return anything to jvm that’s why the
return type is void.

main: Sunmicrosystems has given one name to main method that’s


nothing but main.
We can perform changes in main method with following acceptable formats

🡪order of modifier is not important instead of public and static we can write static and
public

🡪we can write String[] in following acceptable formats.


psvm(String args[])
psvm(String[] args)
psvm(String []args)

🡪we can replace args with valid java identifier


psvm(String[] Nazia)

🡪we can replace String[] with var-arg parameter


psvm(String … Nazia)

🡪main method will accept following modifiers synchronized , final , strictfp


Data types
The data type defines the operations that can be done on the data , the meaning of
the data and the way values of that type can be stored.

Operators
operator is a symbol that acts upon operands and response back user with a result.
Arithmetic operators(+,-,*,/,%)
Assignment operator(=,+=,-=,*=)
Relational operator(<,>,<=,>=,==)
Bitwise operator
Logical operator(&&,||,!)
Inc/dec(++,--)
Miscellaneous operator (conditional operator , instance of)
Conditional operator
--it
is also known as ternary operator .
--This operator consists of three operands and is used to evaluate
Boolean expressions.
--The goal of this operator is to decide which value should be
assigned to the variable.
--symbol is ? :

Variable x=(expression1)?value if true : value if false

Instanceof operator
--this operator is used only for reference variables
--the operator checks whether the object is of a particular classtype
or
interface type
syntax :
(object reference variable) instanceof(class/interface type)
Data types
Primitive Non primitive

Boolean Numeric
Type Type

String Array
Character Integer
value value

boolean integer Floating


char

byte lon
short int float double
byte: size: 1 byte
range: -128 to 127
short: size: 2 bytes
range: -32768 to 32767
or
2^15 to 2^15 -1
int : size: 4 bytes
range: -2147483648 to 2147483647
or
2^31 to 2^31 -1
long: size: 8 bytes
range:2^63 to 2^63 -1
float: size: 4 bytes
range: -3.4e^38 to 3.4e^38
double: size: 8 bytes
range: -1.7e^308 to 1.7e^308

char size:2 bytes


range:0 to 65535
boolean doesnt have size
true or false
Switch statement:
it is used to declare multiple selections.

--inside switch it is possible to declare any number of cases but is possible to declare only one default.

--the allowed argument for switch block are


byte , short ,int , char , String

-- float , double ,boolean and long is not allowed

--Based on the provided argument the matched case will be executed if the cases are not matched default will be executed

syntax:
switch(argument)
{
case label1:
sop(“ ”);
break;
case label2:
sop(“ ” );
break;
default:
sop(“ ”);
}
Case studies

--inside switch the case labels must be unique , If we are declaring duplicate case labels the compiler will raise
compilation error “duplicate case label”.
--Inside the switch for the case labels it is possible to provide expressions(10+10+20, 10*4 ,10/2)
--inside the switch the case label must be constant values
--inside the switch the default is optional
--inside the switch cases are optional
--inside the switch independent statements are not allowed
--internal conversion of char to integer
--internal conversion of integer to character
--inside the switch statement break is optional
--inside the switch we are able to declare the default statement starting or middle or end of the switch
Iteration statements
While loop Do while loop
• A while loop statement in java • In do while loop first the statements inside
programming language repeatedly the loop gets executed then condition is
executes a target statement as long as evaluated.
a given condition is true
• Syntax: • Syntax
initialization
initialization do
while(Boolean expression) {
{ //Statements
//statements inc/dec
Inc/dec }
}
While(condition);
It is also known as entry controlled loop
• It is also known as exit controlled loop
For loop

we use java for loop to execute a set of statements for a repeated number of times based on certain condition.

Using for loop we know how many times we need to execute the same set of code.

Syntax:

for(initialization ; condition ; increment/decrement)


{
Body;
}
Case studies

--Inside the for loop initialization part is optional


--Instead of initialization it is possible to take any number of s.o.p(“lll) statements and each and every
statement is separated by comas(,)
--more than one initialization is not possible
--inside for loop conditional part is optional if we are not providing condition at that time of compilation
compiler will provide true value.
--inside for loop increment /decrement part is optional
--instead of increment/decrement operator it is possible to take any number of SOP() that each
and every statement separated by comas
Transfer statements
break: when the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes
at the next statement following the loop.

It can be used to terminate a case in the switch statement.

Syntax:

break;

continue: It causes the loop to immediately jump to the next iteration of the loop.

Syntax:

continue;

return : a return statement causes the program control to transfer back to the caller of a method. Every method in java is declared
with a return type and it is mandatory for all java methods. A return type may be primitive type int,float,double,a reference type or void
type
Java Class loader
Virtual
Machine
Class PC Native
Heap Stack Method
area Register
Stack

Memory Areas

Execution Native
Engine Method Java
Interface native
libraries
Jvm : A java virtual machine is a virtual machine that enables a computer to run java programs.
It has primary functions :
--loads code
--verifies code
--Executes code
--provides runtime environment
--allows java programs to run on any device or operating systems.
-- manages and optimize program memory

Classloader: It is a subsystem of JVM which is used to load the class files . whenever we run java programs ,it is loaded first by the classloader.

Class(Method )Area: It contains per class elements like fields , method local data , method code , constructor codes etc which are used in class and
initialization of objects/interfaces.

Heap:It is the runtime area in which objects are allocated.

Stack:It holds local variables and partial results , and plays a part in method invocation and return.

Program counter Register: It contains address of the java virtual machine instruction currently being executed.

Native Method Stack: It contains all the native method used in the application. It is also called C stack .
Native methods are not written in java language.
Execution Engine:

It contains :
--a virtual processor.
--Interpreter: Read bytecode stream and then executes the instructions.
--JIT(Just-In-Time )compiler:It is used to improve the performance.JIT compiles parts of the bytecode that
have similar functionality at the same time and hence reduces the amount of time needed for compilation.

Java Native Interface: It is a framework which provides an interface to communicate with another
application written in another language like c,c++,Assembly,etc.
Java uses JNI framework to send output to the console or interact with OS libraries.
OOPS
oops are the methodologies by using which we are attaining project requirements.
--Inheritance
--polymorphism
--Abstraction
--Encapsulation

INHERITANCE
--parent and child relationship is called inheritance.
--The process of acquiring some properties and behaviours from parent class to child class is called inheritance.
--the class who provides the properties is called parent class or super class or base class.
--the class who acquires the properties is called child class or derived class or subclass.
---Inheritance is also known as Extensibility
---In UML terminology inheritance is also known as IS-A relationship
---we achieve inheritance by using extends keyword which is used to establish relationship between two classes.
---If you create object for parent class you are able to access only parent class properties.
---At project level it is always recommended to create objects for child class.
---In entire java the root class is Object class which is present in default package java.lang
The principle behind this kind of division is that each subclass (child-class) shares common characteristics with the class from which it is derived.

Advantages:

Reduces Redundancy .
Reduces length of the code.
Types of Inheritance:
Parent
Single :The child class is derived from a single parent.

Child

parent
Multilevel: The derived class becomes parent for the next class.
Child/pare
nt

Child parent

Hierarchical: parent class can have more than one child.


child1 child2
Preventing inheritance
you can prevent subclass creation by using final keyword in the parent class declaration.

Relationships :

Association: ()
--Class A uses Class B
--when one object wants another object to perform services for it.
--example : relationship between teacher and student ,number of students associated with one teacher or one
student can associate with number of teachers. But there is no ownership and both the objects have their own
lifecycle.

Aggregation:(has-a )

--Class B has instance of class A


--Class A can exists without presence of Class B
--Take a relationship between teacher and department.A teacher belongs to multiple departments hence teacher is
a part of multiple departments but if we delete department object teacher object will not destroy.
Composition(has-a)
--Class A owns Class B,it is a strong type of aggregation . There is no meaning of child without parent.
--example: Bank account consists of transaction history without bank account no meaning of transaction history.
--eg: house contains multiple rooms, if we delete house object no meaning of room object hence the room object
cannot exists without house object.
--Relationship between student and marks ,there is no meaning of marks object without student object.

Super : super keyword is holding super class object .And it is representing

1.super class variables : super.variablename;


2.super class methods : super.methodname();
3.super class constructors : super()

parent instance blocks


child instance blocks
parent static blocks
child static blocks
Polymorphism :
one thing can exhibits more than one form is called polymorphism.
--Polymorphism shows some functionality(method name same) with different logics execution.
--The ability to appear in more than one forms is called polymorphism.
--Polymorphism is a Greek word poly means many and morphism means forms.

Polymorphism

Compile time Runtime


Compile time polymorphism/static binding /early binding:
--method execution is decided at compilation time.
--If java class allows two or more methods with same name but different number of arguments such
type of methods are called overloaded methods.
--we can overload the methods in two ways

ex : method overloading

a)By passing different number of arguments to same methods


b)By providing the same number of arguments with different data types.
--To achieve overloading concept one class is enough.
--It is possible to overload any number of methods in single java class.
Types of overloading:

a)Method Overloading
b)Constructor Overloading
c)Operator Overloading
Operator overloading:
one operator can perform more than one operation is called operator overloading.
Java is not supporting operator overloading but only one operator is overloaded in java i.e
‘’+’’
--if both the operands are integer + performs addition.
--if atleast one operand is String then + perform concatenation.

Runtime Polymorhism/dynamic binding/late binding


--method execution is decided at runtime
--The parent class method contains some implementation (logics)
a)if child class is satisfied use parent class method
b)If child class is not satisfied and wants to go with their own implementation then override the method in class
--A subclass has the same method as declared in the super class it is known as method overriding.
--If we want to achieve method overriding we need two classes with parent and child relationship.
--Parent methods are called overridden methods.
--Child class methods are called overriding methods.
Rules to be followed while overriding
--while overriding child class and parent class method signature must be same.
-- the return types of overridden method and overriding method must be same.
--final methods can’t be overridden
--static methods can’t be overridden because they are bounded with class.
--It is possible to change return type at class level(COVARIANT RETURN TYPES)
--The Parent class reference variable is able to hold Child class object but child class reference variable is unable to
hold Parent object.
--while overriding check the modifiers permission , the subclass method modifiers should have same permission or
increasing level of parent class method but not decreasing order.
Access modifiers
private:

--The private access modifier is accessible only within class.


-- The private access modifier is specified using the keyword private.
--The methods or data members declared as private are accessible only within the class in which they
are declared.
--Any other class of same package will not be able to access these members.
Classes or interface can not be declared as private.
Default:

--If you don’t use any modifier, it is treated as default by default.


----The default modifier is accessible only within package.
--The data members, class or methods which are not declared using any
access modifiers i.e. having default access modifier are accessible only
within the same package.
protected
-The protected access modifier is specified using the keyword protected.
-The protected access modifier is accessible within package and outside the package but
through inheritance only.
-The protected access modifier can be applied on the data member, method and constructor.
.
-It can’t be applied on the class
public:
-The public access modifier is specified using the keyword public.
-The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
-Classes, methods or data members which are declared as public are accessible from every
where in the program. There is no restriction on the scope of a public data members.
Access within class within outside outside
Modifier package package by package
subclass
only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y
Abstraction
-- the process of highlighting the set of services and hiding implementation in child classes is called abstraction
Example: Bank Atm screens ,Hiding the internal implementation and highlighting set of services like money transfer , mobile
registration.
--In java we can achieve abstraction in two ways
a] abstract class
b]Interfaces

--There are two types of methods in java


a)Normal methods
b)Abstract methods

Normal methods: They are the method which contain method declaration as well as method implementation .Also called as
concrete method or component method.

Abstract methods: The method which is having only method declaration but not method implementation such type of methods are
called abstract method.
Ex: abstract void m1();
Based on above representation of methods the classes are divided into two types
1]Normal classes 2]Abstract classes
Normal class: it is a ordinary java class which contains only normal methods

class Test
{
void m1()
{
body
}
}
Abstract class: it may or may not contain abstract methods but we cannot create objects for abstract class
absract class Test
{
void m1()
{
}
abstract void m2();
}
Topics to be covered for abstract class

1]abstract classes are partially implemented classes hence object creation is not possible.
2] Is it possible to declare main method inside abstract class
3]Inside abstract class constructor declaration is possible
4]Inside abstract class is it possible to declare instance block and static block
5]abstract class reference variable is able to hold child class objects.
6]for the abstract methods is it possible to provide any return type(int,float…)
7]is it possible to override non abstract as abstract method in child class.
Interfaces
--Interface is also one of the type of class and it contains only abstract methods.
--It is not an alternative for an abstract class but it is an extension for abstract class
--For the interfaces also the compiler generates .class file
--Interfaces gives information about the functionalities but doesn’t give info about internal implementation.
--Inside the source file it is possible to declare any number of interfaces.
--we declare interface by using interface keyword.
--By default all the methods declared inside interfaces are public and abstract
--implements means you are using the elements of a java interface in your class and extends means that you are
creating a subclass of the base class
--when we have extends and implements then always use extends keyword as first keyword.
syntax: interface IT
{

}
• Applications will be enhanced and optimized as well as simplified as its internal
implementation is not the concern of the end-user.

• The most important of all is that the application becomes secured as the
implementation after making abstract is hidden from the outside world, thus
maintaining the security aspects as well.

• The functionality of the multiple inheritances also becomes supportable.

• The client-side perspective of expecting a set of services to be delivered to the end-


user is known as interface, and from the perspective of service providers, the set of
services being offered is known as the interface.

• Therefore, as mentioned earlier with a real-life example, an interface in java is nothing but a
contract between the client-side and service providers. It maintains IS-A-Relationship, which
also helps make the inheritance and extend between classes possible, thus providing visibility.
• An abstract class is also good if we want to declare non-public
members. In an interface, all methods must be public.

• If we want to add new methods in the future, then an abstract class


is a better choice. Because if we add new methods to an interface,
then all of the classes that already implemented that interface will
have to be changed to implement the new methods.

• If we want to provide common, implemented functionality among all


implementations of our component, use an abstract class.
Topics to be covered for interfaces

-- is it possible to declare interface inside another interface


--is it possible to declare interface inside another class
--is it possible to declare variables inside interface
----If the implementation class fails to provide implementation of all abstract methods then declare
implementation class as abstract and take the child class of implementation class and then complete the
implementation of remaining abstract methods.
--interface versus inheritance
--Multiple Inheritance
--Hybrid Inheritance
--Adapter class
--Marker interface
--functional interface
Multiple inheritance

A B

A
c

hybrid inheritance
B C

Diamond problem

D
Valid and invalid conclusions
--class A extends B (valid)
--class A extends B,C (invalid)
--class A implements IT3 (valid)
--class A implements IT1,IT2,IT3 (valid)
--class A extends A (invalid) java doesn’t support cyclic inheritance
--interface IT1 extends IT2 (valid)
--interface IT1 extends IT2,IT3 (valid)
--interface IT1 extends A (invalid)
--interface IT1 extends IT1 (invalid)
--class A extends B implements IT1,IT2 (valid)
--class A implements IT1,IT2 extends B (invalid)
The whole idea behind encapsulation is to hide the implementation details from users. If a data
member is private it means it can only be accessed within the same class. No outside class can
access private data member (variable) of other class. ... That's why encapsulation is known as
data hiding.

--Abstraction is the method of hiding the unwanted information. Whereas encapsulation is a


method to hide the data in a single entity or unit along with a method to protect information from
outside. ... Whereas encapsulation can be implemented using by access modifier i.e. private,
protected and public.

Encapsulation helps in isolating implementation details from the behavior exposed to clients of a
class (other classes/functions that are using this class), and gives you more control over coupling in
your code.
Encapsulation
In Java , encapsulation is a mechanism of wrapping the data (variables) and code acting on
the data (methods) together as a single unit. In encapsulation, the variables of a class will
be hidden from other classes, and can be accessed only through the methods of their current
class .
--To bind the data tightly we use modifier private .
--The class containing private properties that class is said to be tightly encapsulated.
--At project level we consider java bean class ,it contains private properties and public setter a
and getter methods .It is used to transfer the data between the layers.
--setter is used to set the data for properties
--getter is used to get the data from the properties.
When you log into your email accounts such as Gmail, Yahoo Mail, or
Rediff mail, there is a lot of internal processes taking place in the
backend and you have no control over it.

When you enter the password for logging, they are retrieved in an
encrypted form and verified, and then you are given access to your
account.

You do not have control over it that how the password has been
verified. Thus, it keeps our account safe from being misused.
Exception
Handling
Exception : It is a problem for which we can provide solution programmatically.
-- it will rise due syntax error.

Error : It is a problem for which we cannot provide solutions programmatically.


--It will rise due to lack of system resources

--Java technology supports two types of termination:


1]smooth termination
2]abnormal termination
--During the application execution if there is no interruption in the middle of a program such
type of termination is called smooth termination.
--During the application execution if there is interruption in the middle of the program such
type of termination is called abnormal termination.
Information regarding Exception:

1)Dicitionary meaning of the Exception is abnormal termination.


2)Exception is unwanted unexpected event which disturbs normal flow of our program.
3)Every Exception is a predefined class present in some packages.
ArithmeticException -------java.lang
SQLException-------------java.sql
ServletException----------javax.servlet
IOException-----------------java.io
4)The exception are occurred due to two reasons
a)Developer mistakes
b)End-user mistakes
5)Exception occurs due to reasons like:
----while providing wrong inputs to the application
---- A file that needs to be opened can’t found then exception occurs.
Types of Exception:
--Predefined exception
--Userdefined exception
--An exception which is given by jdk software is called predefined exception and it is divided into two types
--checked exception
--unchecked exception
Unchecked Exception:

--The exception which are not checked by the compiler at the time of compilation are called Unchecked Exception
--ArithmeticException , NullPointerException
--whenever we are getting unchecked exception the code is compiled but at the runtime program terminated
abnormally hence handle the exception by using try –catch blocks or throws keyword to get normal termination.

Checked Exception:

--The Exception which are checked by the compiler at the compilation time is called checked exception.
--IOException , SQLException, InterruptedException
--In our application whenever we are getting checked exception the compiler is able to give intimation to developer
regarding handle the exception.
--if application contains checked exception the code wont compile so must handle the exception in two ways
a)try-catch
b)throws
--The checked exception caused due to predefined methods it means whenever we are using predefined methods (not
all predefined only for exceptional methods) we are getting checked exception.
a)Exceptional methods:
--public static void sleep(long)throws java.lang.InterruptedException
--public abstract Statement createStatement()throws SQLException

Exception handling keywords: try,catch,throws,finally,throw

try block:
--It is a block which contains risky code.
--try block is associated with catch and finally blocks
--it is always recommended to write very little code inside try block because if exception raises
try block won’t be executed.
--if any exception raises in the middle of the program try block rest of the code wont be executed.
Syntax:
try
{
exceptional code;
}
Catch block:
--it is a block which contains error handling code.
--catch block is used to define an exception.
--catch block will take exception class name as parameter and this should match with exception name.
--catch block is associated with try block only.
--catch block is used to catch the exception thrown by try block.
--if there is no exception in try block catch block won’t get executed.
Syntax:
catch(ExceptionName referencevariable)
{
code to run if an exception is raised;
}
finally block
--it is always executed irrespective of try and catch.
--it is used to provide clean up code(Database connection closing,stream closing …etc)
--it is associated with try and catch.
--its not possible to write finally alone.
Syntax:
finally
{
clean up code
}
Valid and invalid
try –catch-finally ------------valid
try –catch--------------------valid
catch-finally------------------invalid
try-catch-catch-finally-------valid
try-finally---------------------valid
catch-catch-finally------------invalid
try----------------------------invalid

Various methods to display exception details:


printStackTrace() : It will display name of the exception : description of the exception : line of the exception.

toString() : displays name of the exception : description of the exception

getMessage():displays description of the exception


Case Studies :
1) whenever the exception is raised in the try block JVM won’t terminate the program immediately it will search corresponding
catch block.
2)if there is no exception in try block the catch blocks are not executed.
3)In exception handling independent try blocks are not allowed.
4)In between try-catch independent statements are not allowed .
5)if the exception is raised in other than try block it is always a abnormal termination.
6)if the exception raised in try block remaining code of try wont get executed.
7)the way of handling exception varies from exception to exception hence it is recommended to provide try with multiple
number of catch blocks.
8)By using Exceptional catch block we are able to hold any type of exception.
9)If we are declaring multiple catch blocks order should be from child to parent but not parent to child.
Throws :
In the exception handling we must handle the exception in two ways.
A)by using try-catch blocks
b)by using throws keyword.
--Try catch block is used to handle the exception but throws keyword is used to delegate the responsibilities of the exception handling to the caller method.
--The main purpose of the throws keyword is bypassing the generated exception from present method to caller method.
--use throws keyword at method declaration level.
--it is possible to use throws any number of time based on the programmer requirements.
--If main method throws exception then JVM is responsible to handle the exception.
Throw:
1)The main purpose of the throw keyword is creation of exception object explicitly either for predefined or userdefined.
2)throw keyword works like a try block .The difference is try block will automatically find the situation and creates exception object implicitly. Whereas throw
keyword creates a object explicitly.
3)Throws keyword is used to delegate the responsibilities whereas throw is used to create exception object explicitly.
4)if the exception object created by the user then userdefined information is printed.
5)we use throws keyword at method declaration level whereas we throw at method implementation level.
Throw keyword has two objectives
--Handover the user created exception object to jvm for predefined Exception.
--Handover the user created exception object to jvm for userdefined Exception.

1)throw keyword is used to create the exception object explicitly by the developer for predefined exceptions.

Step -1: create the exception object explicitly.


new ArithmeticException(“Arun is not eligible”);
Step-2:handover user created Exception object to JVM by using throw keyword.
throw new ArithmeticException(“Arun is not eligible”);

2)throw keyword is used to create the exception object explicitly by the developer for userdefined exceptions.

Step 1: create userdefined Exception


class InvalidAgeException extends RuntimeException
{
}
Step-2:create the object of userdefined Exception
new InvalidAgeException();
Step-3:handover userdefined exception object to jvm by using throw keyword
throw new InvalidAgeException();
Parameterized approach
step1:create userdefined exception class

Ex:class InvalidAgeException extends Exception


{
InvalidAgeException(String str)
{
super(str);
}
}
step2: use user created exception object in our project

There are two approaches to create userdefined unchecked exception

A)Default constructor approach


B)parameterized constructor approach.
Default constructor approach

step-1:create userdefined exception


class InvalidAgeException extends RuntimeException
{
default constructor;
}
Creation of userdefined exceptions
There are two types of userdefined exceptions.
1)userdefined checked exceptions(these exceptions extends Exception class)
2)userdefined unchecked exceptions(extends RuntimeException class)
--The naming conventions are every exception suffix must be the word Exception.
--There are two approaches to create userdefined checked exceptions.
A)default constructor approach.
B)Parameterized constructor approach.
Default constructor approach

step1: create the userdefined exception.


Normal java class will become exception class whenever we extends predefined Exception class.
Ex: class InvalidAgeException extends Exception
{
default constructor
}
step2: use created exception object in our project.
Step-2:
use user created exception in our project
parameterized approach:

step 1: create usedefined exception class


ex:public class InvalidAgeException extends RuntimeException
{
InvalidAgeException(String str)
{
super(str)
}
}
step -2: use user created exception object in our project
Exception Handling with Method Overriding in Java
There are many rules if we talk about method overriding with exception handling.

Some of the rules are listed below:

If the superclass method does not declare an exception


If the superclass method does not declare an exception, subclass overridden method cannot declare
the checked exception but it can declare unchecked exception.
If the superclass method declares an exception
If the superclass method declares an exception, subclass overridden method can declare same,
subclass exception or no exception but cannot declare parent exception.
Different types of exception:
--ArrayIndexOutOfBoundsException
--NumberFormatException
--NullPointerException
--ArithmeticException
--IllegalArgumentException
--IllegalThreadStateException
--StringIndexOutOfBoundsException
--NegativeArraySizeException
--InputMismatchException
Different Types of errors
--StackOverflowError
--OutOfMemoryError
Var-arg method
it allows method to take any number of arguments
syntax: only three dots
void m1(int… a)
the above m1()is allowed to take any number of parameters.

Method Recursion:
a method is calling itself during execution is called recursion
syntax:
returntype methodname()
{
//code to be executed
methodname(); //calling same method
}
Array
An Array is used to store group of elements as a single entity and these elements must be homogeneous and fixed.
--The main advantage of an array is we can represent multiple elements using single variable name.
--performance point of view array is recommended
--The main disadvantage of an array ,there is no chance of increasing and decreasing the size of an array.
--to use array concept in advance we should know the size of an array which is always not possible.

Int[]
String[]
float[]
double[]

10 , 20 , 30 , 40 ,50
a[0] a[1] a[2] a[3] a[4]
--arrays is always index based
--if size is 5 ,last index is 4 i.e n-1
--To define an array we have three approaches
Declaration:
int[] a
Instantiation
a=new int[5]

initialization
a[0]=10;
a[1]=20;

--three steps can be written as :

syntax:
datatype a[]=new datatype[size];
or
int[] a={10,20,30,40,50};

Arrays are divided into three types


1)single dimensional array
2)Two dimensional array
3)multi dimensional array
--At the time of array declarations we should not specify array size otherwise we will get compile
time error.

--Every array in java is an object hence we will use new operator to create an array.

int a[]=new int [3];


internally
a

--At the time of array creation compulsory we should specify array size otherwise we will get
compile time error called array dimension missing
int a[] =new int[3]; (valid)
int a[]=new int[];CTE
--It is legal to have array size with zero
int a[]=new int[0];(valid)

--If we take negative int value as an array size then we will get C.T.E as
NegativeArraySizeException.
Int a[]=new int[-3];(invalid)

--The allowed data type for array size are byte,short,int ,char .
By mistake if we take other datatype .then will get c.t.e called possible loss of precision.

Int a[]=new int[10.5f]; (invalid)


--The maximum length we can assign for an array size is the length of int.(2147483647) .thats why it doesn’t
support float ,long , double etc.
--Once we create an array every element will be initialized with default values .
--if we are not satisfied with those default values then we can replace it with our own customized values.

--Example: int[] prime;


array is not created at declaration and memory is not allocated .

--Example:
int primes[]=new int[10];
in the above example ,memory for 10 integers i.e 40 bytes is allocated.

--An array is normally initialized (values assigned to elements in the array) as follows
int[] variable_name= {val1 ,val2 ,val3…………….}

int [] primes={2,3,5,7,11,13,17,19,23,29}
--we can also initialize an array with an existing array.
int [] even={2,4,6,8,10};
int[] notOdd=even;
--one array but two array variables ; both array variables refer to the same array;
Array can be accessed through either variable name.
--we can refer to array length by using attribute of array object i. e array_name.length
for example:
for(int i=0;i<primes.length;i++)
{…….}
-- if number of elements in the array are changed ,java will automatically change the length attribute.

Command line arguments.


An argument which passes through a command prompt such type of argument are called command line arguments.
--A command line is an information that directly follows the program name on the command line when it is executed.
--the main objective of command line is to change the behaviour of main method.
Javac test.java
java test 10 20 30
args[0] args[1] args[2]
--they are stored as String array passed to main().
--The arg passed from the console can be received in the java program and it can be used as an input.
--Arrays doesn’t support any predefined methods so while working with array operations
like updations ,deletions becomes complex.

--length vs length()

--a method return type can be an array and argument can also be array.

--array are used to store both primitive data and object data

--Array is able to hold homogeneous data but object array is able to hold any type of
data(heterogeneous)

-- the parent array is able to hold all subclass data.


Two dimensional array:
2-d array is an array where every element of the array is an array .
--its like array within the array.
Int [][] numbergrid=new int [3][4]

BinarySearchAlgorithm:

binary search is the process of searching an element from sorted array by repeatedly
dividing the search interval in half.
Binary search is faster than linear search.
Before performing binary search array should be sorted ..
For each loop
--For-each is another array traversing technique like for loop, while loop, do-while loop
introduced in Java5.
--It starts with the keyword for like a normal for-loop.
--Instead of declaring and initializing a loop counter variable, you declare a variable
that is the same type as the base type of the array, followed by a colon, which is then
followed by the array name.
--In the loop body, you can use the loop variable you created rather than using an
indexed array element.
--It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)

Syntax:
for (type var : array)
{
statements using var;
}
Limitations of for each loop
--for –each loops are not appropriate when you want to modify the array.
--for-each loops do not keep track of index.so we do not obtain array index using for –each loop.
--for-each iterates only forwards over the array in single steps.
selection sort
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning. The
algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order)
from the unsorted subarray is picked and moved to the sorted subarray.
arr[] = 64 25 12 22 11

// Find the minimum element in arr[0...4]


// and place it at beginning
11 25 12 22 64

// Find the minimum element in arr[1...4]


// and place it at beginning of arr[1...4]
11 12 25 22 64

// Find the minimum element in arr[2...4]


// and place it at beginning of arr[2...4]
11 12 22 25 64

// Find the minimum element in arr[3...4]


// and place it at beginning of arr[3...4]
11 12 22 25 64
• Bubble sort is a sorting algorithm that compares two adjacent
elements and swaps them until they are not in the intended
order.
String Manipulations
String
StringBuffer
StringBuilder
StringTokenizer
--String is a final class present in java.lang
--it is a group of characters enclosed within the double quotes.
--if the content is not frequently changing then we should go for String,for every change a separate object will be created internally.
--it is not a datatype ,it is a universal class in java
--String is a immutable object
--StringBuffer is a final class present in java.lang
--if the content is frequently changing then we should go for String Buffer
--The main advantage of StringBuffer over String is all required changes will be performed in the existing object .
Constructors of String Buffer
a)StringBuffer sb=new StringBuffer();
creates an empty SB object with default capacity 16.once reaches its maximum capacity the existing object will be given new
capacity=(currentcapacity+1)*2
b)StringBuffer sb=new StringBuffer(int initialcapacity)
:creates SB object with specified capacity.
c)StringBuffer sb=new StringBuffer(String s)
creates an equivalent SB object for the given String with capacity=s.length()+16
--we can create String in two ways
--By using literal
--By new Keyword
--String objects are stored in special memory area called as string constant pool(SCP) which is located inside heap memory
--if we create by using literal only one object is created inside SCP.

SCP

s1
String s1=“ABC”;
heap
--if we create by new keyword 2 objects will be created

SCP

String s2=new String(“ABC”)


HEAP
s2
--if we are having same content we want to create object JVM will check whether the content is already present or not .if present then it is not
created ,but it is just referenced with string literal.

--with new keyword it will create object for new string even though the content is same.
--SCP doesn’t allow duplicates
--Heap allows duplicates.
--String Methods : there are about 86-90 methods for String class

--toString() :
In java if we print the reference variable ,internally it is calling toString() method .
--it belongs to object class and it gives the address of the memory location where the object is located.
--it gives some hexadecimal number that is called as hashcode.
--Object class is the superclass of all the classes ,including predefined and userdefined.
--during compilation it will add “extends object” .
--if we are not overriding the toString () of object class it will display address of the object reference
--if we are overriding the toString() of object class it will display the content of present class or
String class.
Internal implementation of toString():
class Object
{
public String toString()
{
return classname@hashcode
}
--------------------------------------------------------------------------------------------------------------------
class String extends Object
{
/*overriding toString*/
public String toString()
{
return “content of string object”
}
--------------------------------------------------------------------------------------------------------------------
class StringBuffer extends Object
{
public String toString()
{
return “content of stringbuffer object”
}
equals() and == (reference comparison)
--String class equals ()will check the content whereas == check the reference address

internal implementation of equals method


class Object
{
public Boolean equals()
{
return reference comparison
}
---------------------------------------------------------------------------------------------------
-----
class String extends Object
{
overriding equals method
public boolean equals()
{
return “content comparision”
}
Class StringBuffer extends Object
{
public Boolean equals()
{
return referencecomparison
}
}
--it is possible to convert String object to StringBuffer .

--String Buffer and String Builder


--In StringBuffer every method is synchronized . At a time only one thread is allowed to act on SB
object.
--In StringBuilder no method is synchronized ,any no of thread can act simultaneously on Sbuilder
object.
--SB performance wise is not recommended.
--Sbuilder grows dynamically.
--its initial size is 16.
--There is no direct way to convert StringBuffer to StringBuilder
--StringBuilder performance is speed when you compare to both String and StringBuffer.

StringTokenizer
--By using StringTokenizer we can spilt the given string into words based on the delimiters.
--StringTokenizer sb=new StringTokenizer(“this is my”,” ”);
--
Wrapper classes
--in java everything is treated as objects.so if we want to represent primitive data types as objects then we need classes called wrapper classes.
Datatype Wrapper class Constructors
byte Byte byte,String
short Short short,String
int Integer int,String
long Long long,String
float Float float,String,double
double Double double,String
char Character char
boolean Boolean Boolean,String

--All wrapper classes are immutable classes and are present in java.lang
--All wrapper classes consists of four methods.

--valueOf()
--toString()
--parseXxx()
--xxxValue()
toString()
--it prints String representation of object.
-- In all 8 wrapper classes toString() is overridden to return the content of the corresponding object.
Internal Implementation

class Object
{
public String toString()
{
return “classname@hashcode” ;
}
}
class Integer extends Object
{
public String toString()
{
return “content of the IntegerObject ”;
}
}
valueOf()
it is also used to create wrapper object .
--there are two approaches to create wrapper object 1)constructor approach and 2)valueof()

Primitiv Wrapper
e object
String

xxxValue()
--By using xxxValue() method we are coverting wrapper objects into corresponding primitive values.

Primitiv
Wrappe e
r object value
parseXxx():
--By using parseXxx() method we are converting String into the corresponding primitive.

Correspondin
String g
value primitive

Autoboxing and Autounboxing


Automatic conversion of the primitive to wrapper and wrapper to primitive

autoboxin
g Wrapper
primitive
object
autounboxing
Type casting or Type conversion
converting one type of data into another type is called type conversion or type casting.
--In java there are four types of type casting
1)primitive-primitive
2)object-object
3)object-primitive
4)String-primitive

primitive-primitive:
--There are two types of primitive-primitive type conversion
a)Implicit casting
b)explicit casting
--if we try to store a smaller datatype value in a bigger datatype variable then that is known as implicit casting
--this is done by compiler
--if we are trying to store a bigger datatype value in a smaller variable then that is known as explicit casting.
--this is done by user explicitly.
2)object-object

--this kind of casting is possible only if both objects are having relation.
--There are two types of object-object type casting
a)upcasting
b)downcasting
--if a parent class reference is holding the subclass instance that is known as upcasting
Parent p=new Child();
--holding parent class instance (object) into child class reference is called downcasting
Parent p=new Child();
Child c=new (Child)p;

3)object-primitive and primitive –object


wrapper class is used for object-primitive ,primitive to object type of conversion
--to convert primitive datatype to objects we use wrapper classes.
--from java-5 a new concept was introduced called boxing –coverting primitive type to object
and unboxing-converting object to primitive type.
4)String-primitive and primitive to String
--wrapper classes are used to convert String type to primitive type
--Ex Integer.parseInt(String s);
it is used to convert String type to int type.
--To convert primitive type to string type we use String.valueOf() method.
Ex.String value =String.valueOf(int);

--Another approach to convert primitive type to string type is add string(“ ”) to primitive type

String value=34+” ”
Java.io
java.io package is providing essential classes and interfaces for performing io operation on file ,array,network,string .
--by using these classes and interfaces we are transferring the data between source file to destination file.
--source is the one which sends the data and destination is the one which receives data.
--when we work with stored files we need to follow tasks like:
a)Determine whether the files is there or not.
b)open a file
c)Read the data from the file
d)writing information to file
e)closing file
--Stream is a channel ,and it supports continuous flow of data from one place to another place.
--channel is a communication medium through this channel we can read and write the data.
--Streams are two types:
1)Byte oriented( supports byte formatted data to transfer)
2)Character oriented(supports character formatted data to transfer)
InputStream
it’s a abstract class that contains methods to perform input operations

OutputStream:
its an abstract class that contains methods to perform output operations

Reader:
its an abstract class that contains methods to perform input operations

Writer:

its an abstract class that contains methods to perform output operations


--to read the data ,file is mandatory otherwise FileNotFoundException
--to write the data,fileis optional,if file is not there it will create new file
steps:
a)create the channel
b)first read the data,it will return the Unicode values ,store it some integer variable
c)check the stream is ended or not by using -1 constant
d)if the condition is satisfied ,write the data
e)close the channel.
--problem with normal streams:
when we read data we are reading character by character ,if application has 1 lakh characters
in that case we need to perform I lakh read operation and 1 lakh write operations.so performance is
degraded .
--to improve the performance we use buffer streams.
Normal Streams Buffer Streams

• Read and write character • Read and write line by line so


by character so performance is increased
performance is degraded. • They are developed on
• They are developed normal streams.
directly • For the first time they get it
• They get the data from from hard disc and from
hard disc second time they get it from
• ex. buffer memory.
• FileInputStream • Ex:
• FileReader • BufferedInputStream
• FileOutputStream • BufferedReader
Serialization

The process of saving object to a file or the process of sending an object across the network is called serialization.
--But strictly speaking the process of converting the object from java supported form to the network supported form which is file supported form is
called serialization
--if you want to perform serialization ,class must implements serializable.
--To do serialization we require following classes
FileOutputStream
ObjectOutputStream

Deserialization
--The process of reading the object from file supported form or network supported form to the java supported form is called deserialization.
--To do deserialization we need two classes
FileInputStream
ObjectInputStream

transient modifier: its applicable for only variables and we cant apply for methods
--At the time of serialization if we don’t want to save the values of a particular variables we make that variable as transient .
--for security constraints we use it.
Multithreading
Thread:
--Thread is nothing but separate path of sequential execution.
--The independent execution technical name is called thread.
--whenever different parts of the program executed simultaneously that each and every part is called thread.
--The thread is light weight process because whenever we are creating thread it is not occupying the separate memory and it
uses the same memory space .
--Executing more than one thread at a time is called multithreading
--The main important areas of the multithreading :
Developing video games
Implementing multimedia graphics
Developing animations
--Thread is a userdefined process
Single threaded model
--if an application contains only one thread Is called a single threaded model.
--if an application consists of only one thread then we can expect exact output.
--when a java program execution starts one thread is running immediately and that is main thread of our program.
--The main thread is important for two reasons
1)it is used to create a new thread( child thread)
2)it is the last thread to finish the execution because it performs various actions.

--There are two different ways to create a thread


**you can extends the java.lang.Thread class
**you can implement the java.lang.Runnable interface
First approach to create thread by extending Thread class
step-1: creates a class that is extend by Thread class and override the run() method

class MyThread extends Thread


{
public void run()
{
sysout(business logic);sysout(body of the thread)
}
}
step-2
create a thread object.
MyThread t=new MyThread();
step-3
starts the execution of a thread.
t.start();

--if no start() method is present in current class then parent class start() method is executed by jvm
--if jvm finds a start() method in the present class then that will be executed.
--whenever the thread class start() method is called it is responsible to call run() method internally.
--whenever we are giving chance to the thread class start() method then only a new thread will be created.

Thread scheduler
--if application contains more than one thread then which thread is executed that is decided by thread scheduler
--thread scheduler is a component of jvm
--thread scheduler internally follows two algorithms to allocate cpu cycles
a)preemptive algorithm
b)time slicing algorithm
--whenever the thread class start() is executed it will perform two actions.
1)That thread class start() method register the current class(MyThread ) to ThreadScheduler.so whenever it is registered to thread scheduler then only thread is
created.
2)The thread class start() method code automatically call run() method.

Topics to be covered
--single threaded
--Multi threaded
--Difference between t.start() and t.run()
--if we are not overriding run() method then parent class run is executed which is having empty implementation.
--what happens if we override start() method
--can we overload run() method
--Multiple threads performing same task
--Multiple threads different tasks unexpected output
--each and every thread contains name
--each and every thread has got its own priority
--lifecycle of a thread
--Daemon threads
--join()
--yield()
--Runnable interface
--synchronization
--deadlock
--Interthread communication
--difference between wait() and sleep()
Life cycle of a thread

New runnin
born ready g

dead

Blocked
state
New :when a thread is instantiated it will enter into new born state.
MyThread t=new MyThread();

ready: when we say t.start() the thread becomes active and enter into ready state but still not performing any task.

Running state: if thread scheduler allocates CPU cycles for particular thread .Thread goes to running state .
And now here in this state it is performing the task. i.e run() is executed.

Blocked state: if the running thread got interrupted or goes to sleep state at that moment it goes to the blocked state.

Dead state: if the business logic of the project is completed means run() is over then thread goes dead state

Daemon threads
--The threads which are executing in the background are called Daemon threads
--These threads are providing support to foreground threads
--the lifecycle of these threads depends upon user threads. It means when user thread dies jvm terminates this thread automatically.
Ex:
garbage collector,finalizer
join()

To stop execution of current thread until the completion of target thread we use join ()

t1 t2 t3

t3.join();
here in the above example t2 has to wait until the completion of t3.

yield()

when we call yield () thread will sleep for sometime ,we are unable to decide that exact time ,that time is decided by thread
Scheduler.

Sleep(): if a thread don’t want to perform a task for a particular amount of time then we should go for sleep()
We are having two approaches to create a thread and which one is better
first approach
important point is that when extending the thread class ,the sub class cannot extend any other base class because java allows
single inheritance.
Second approach
--Implementing the Runnable interface does not give developers any control over the thread itself.as It simply defines the unit of work that will be
executed in a thread.
--By implementing the Runnable interface , the class can still extend other base classes if necessary.
Synchronization

--synchronization is built around an internal entity which is known as lock or monitor.


--When thread wants to access any object it has to acquire the lock associated with it and release it when its done.
--synchronization in java is capability to control the access of multiple threads to any shared resource.
--synchronization is better option if we want to allow only one thread to access the shared resource.
--we use synchronization for two reasons
1)prevent thread interference
2)prevent consistency problems.
--There are two types of thread synchronization
--mutual exclusive
--inter thread communication
Mutual exclusive
it helps to keep thread away from interferring with one another while sharing data,this can be done by three ways.
1)synchronized method
2)synchronized block
3)static synchronization
Synchronized method
if we declare any method as synchronized it is known as synchronized method
--it is used to lock an object for any shared resource.
--when a thread invokes a synchronized method it automatically acquires the lock for that object and releases it when
the thread completes its task.
Synchronized block
it can used to perform synchronization on any specific resource of the method.
--suppose you have 50 lines of code in your method but you want to synchronize only 5 lines then we use
synchronized block.
Static synchronization:
if you make any static method as synchronized the lock will be on class but not on object.
Inter-thread communication
it is all about allowing synchronized threads to communicate with each other.
--it is also known as co-operation
--co–operation is a mechanism in which a thread is paused running its critical section and other thread is allowed to
enter in the same critical section to be executed.
--it is implemented by the following methods of object class
a)wait()
b)notify()
c)notifyAll()
wait(): it causes the current thread to release the lock and wait until either another thread invokes the notify() or
notifyAll() for this object
notify()wakes up a single thread that is waiting on this object monitor .if any threads are waiting for this object ,one of
them is chosen to be awakened .
notifyAll() wakes up all threads that are waiting on this object monitor.
Deadlock
--it occurs in a situation when a thread is waiting for an object lock.
--for example second thread is waiting for an object lock that is acquired by the first thread and vice versa.
--since both the threads are waiting for each other to release the lock ,the condition is called deadlock.

wait() Sleep()
• Wait releases the lock • Sleep doesn’t release the lock
• It’s the method of object class • It’s the method of Thread class
• It is non static method • It’s a static method
• Should be notified by notify()or • After a specified amount of time
notifyAll() sleep is completed.
Inner classes
Declaring a class inside another class is called nested classes.
--The nested classes are divided into two categories
Nested classes

Non-static
nested Static
class nested
class
Normal

Method
local inner
class

anonymou
s
Uses of nested classes:
1.it is a way logically grouping classes that are only used in one place.
If a class is useful to other class only one time then it is logically embedded it into that class .this makes the two classes together.

Class A class A
{ {
} class B
class B {}
{ }
A a=new A();
}

2.it increases encapsulation.


If we are taking two top level classes A and B .Then suppose B class needs the member of A which are declared as private .even then it can access
A properties ..Moreover B is not visible to outside world.

3.it leads more readability and maintainability of the code.


Nesting the classes within the top level classes at that situation placing code is very closer to the top level class.
Member inner classes:
--if we are declaring any data in outer class then it is automatically available to inner class.
Class Outer
{
class Inner
{
}
}
object creation syntax:
syntax-1:
Outerclassname rv=new Outerclassname();
Outerclassname.innerclassname oi=Outerobjectreference.new Innerclassname();

syntax-2:
outerclassname.innerclassname oi=new outerclass().new InnerClass();
Method local inner classes
--Declaring a class inside the method is called method local inner classes
--in the case of method local inner classes the class has the scope upto the respective method.

Static inner classes


--Declaring a class as static and defining it inside another class is called static inner class.
--static inner class can access only static variables and static methods but not instance variables and instance methods.

Anonymous inner class


The nameless class is called anonymous inner class
--it can be used to provide the implementation of normal class or abstract class or interface.
Garbage collector:
it is destroying the useless object and recollect the space for new object in heap and it is a part of the jvm
-- it is started and stopped by jvm when required.
--it’s a deamon thread which provides services to the user threads.
--whenever we are assigning null constants to our objects then objects are eligible for gc.
--whenever we reassign the reference variables the objects are automatically eligible for garabage collector
--gc()
by using gc() we are able to call garbage collector explicitly
gc() present in System class and it is static method
System.gc()
--whenever garbage collector is destroying useless objects just before destroying the objects the GC will call finalize()
method on that object to perform final operation.
--if the garbage collector is calling finalize method at that situation if exception raises it is ignored.
--if the user is calling finalize() explicitly at that situation exception is raised.
Var-arg method
--it was introduced in 1.5 version
-- It allows the method to take any no of parameters.

void m1(int … a) ------------- valid


void m2(int …a,char ch)-----------------invalid

void m3(int …a, boolean …b) -------------invalid

void m4(double d , int … a)--------------valid

void m5(char ch ,double d , int …a)----------valid

void m6(char ch, int …a , boolean …b)--------invalid

--inside the method it is possible to declare only one variable –argument and that must be last argument
otherwise the compiler will generate compilation error.
Collection
--if we want to store one value then we use
int x=10;
--if we want to represent huge amount of data then we use arrays.
Int x[]=new int[1000];
--array is a indexed collection of fixed no of homogeneous data elements.
--The main disadvantage of arrays is
1)they are fixed in size that is if we create an array we can’t increase ör decrease the size based on our requirement.
Due to this ,to use arrays concept we must know the size in advance which is not possible always.
2)They can hold only homogeneous data
3)Array concept is not implemented on some data structure concept and hence readymade method support is not available . For every requirement we have
to write the code explicitly which increases complexity of programming.
To overcome these problems we should go for collection concept
--Collection is growable in nature so based on our requirement we can increase or decrease the size.
--Collection can hold both homogeneous and heterogeneous elements and objects
--Every collection class is based on some standard data structure hence for every requiremet readymade method support is available.
Collection framework: It contains several classes and interfaces which can be used to represent group of individual objects as single
entity.

--In collection framework we have nine key interfaces.


1.Collection
2.List
3.Set
4.SortedSet
5.NavigableSet
6.Queue
7.Map
8.SortedMAp
9.NaviagableMap

Collection:If we want to represent group of individual objects as single entity then we should go for
collection
--collection interface defines the most common methods which are applicable for any collection object
--in general Collection interface is considered as root interface of Collection framework.
--There is no concrete class that implements Collection interface directly.
Why we need collections??

We need collections for efficient storage and better manipulation of data.

For example:

we use array to store integer but what if we want to

--Resize the array


--insert element in array
--delete an element in an array
--perform any modifications to array
List
if we want represent group of objects as single entity where duplicates are allowed and insertion order is preserved then go for List
--It is the child interface of Collection
--whatever methods are there for Collection it automatically comes to List
methods of list
add()
addAll()
remove()
removeAll()
g.et()
set()
lastIndexOf()
--Implementation classes of List
ArrayList ,LinkedList,Vector,Stack
--Every Collection object is implemented by underlined data structure
ArrayList
--Resizable Array or Growable array
--Duplicates are allowed
--insertion order is preserved
--it can hold both homogeneous and heterogeneous objects
--null insertions is possible
--ArrayList is the best choice when our frequent operation is reterival because ArrayList and Vector both implements
RandomAccess(it is a marker interface and its functionality is provided by JVM)
--ArrayList is the worst choice if our frequent operation is inserting or deleting an element in middle
Generics
in order to make collection as type safe we use generics
what is the purpose of collection?
--To hold data and transfer from one location to another location
--for this reason every collection is by default Serializable

whats the difference between ArrayList and Vector


ArrayList is non synchronized whereas Vector is synchronized so performance of ArrayList will be high when compared to Vector.

How to get the synchronized version of ArrayList


ArrayList l=new ArrayList();
List L1=Collections.synchronizedList(l);
Constructors of ArrayList
1)ArrayList L=new ArrayList();

creates an empty arraylist with default capacity of 10;


once arraylist reaches its maximum capacity then a new arraylist object is created with new capacity=(currentcapacity*3/2)+1

2)ArrayList L=new ArrayList(int initialcapacity)

it creates an empty arraylist object with specified initial capacity

3)ArrayList l-new ArrayList(Collection C)

it creates an equivalent arraylist object for the given collection

--In ArrayList elements are stored in consecutive memory locations,so if we do any changes then lot of shift operations
takes place and performance becomes slow.
ArrayList insertion example
ArrayList insertion example
ArrayList deletion example
Vector
--The underlying data structure for vector is resizable array or growable array
--Insertion order is preserved
--Heterogeneous elements allowed
--null insertions is possible
--by default implements Serializable,Colenable,RandomAccess
--Synchronized i.e thread safe
addElement(Object o)
removeElement(Object o)
removeElement(int index)
clear()
size()
capacity()
constructors of vector
1)Vector v=new Vector();
it creates a new empty vector object with default capacity of 10;
once it reaches its maximum capacity then a new vector object will be created with double capacity.
New capacity=current capacity*2
2)Vector V=new Vector(int initialcapacity,int Incrementalcapacity)
this type of constructor is not present in ArrayList i.e incremental capacity constructor.
LinkedList
--The underlying data structure is doubly linked list.
--Insertion order is preserved
--heterogeneous objects allowed
--null insertions possible
--LinkedList implements Serializable but not RandomAccess.
--LinkedList is the best choice if our requirement is insertion and deletion in the middle.
--LinkedList is the worst choice if our frequent operation is retrieval
constructors of linkedlist

LinkedList l=new LinkedList();


creates an empty linkedlist object
--No capacity for linkedlist
LinkedList l=new LinkedList(Collection c)
Linked List is a part of the Collection framework present in java.util package. This class is an
implementation of the LinkedList data structure which is a linear data structure where the elements
are not stored in contiguous locations and every element is a separate object with a data part and
address part.

The elements are linked using pointers and addresses. Each element is known as a node. Due to the
dynamicity and ease of insertions and deletions, they are preferred over the arrays. It also has a few
disadvantages like the nodes cannot be accessed directly instead we need to start from the head
and follow through the link to reach a node we wish to access.
Since a LinkedList acts as a dynamic array and we do not have to specify the size
while creating it, the size of the list automatically increases when we dynamically add
and remove items.

And also, the elements are not stored in a continuous fashion. Therefore, there is no
need to increase the size. Internally, the LinkedList is implemented using the doubly
linked list data structure.

The main difference between a normal linked list and a doubly LinkedList is that a
doubly linked list contains an extra pointer, typically called the previous pointer.
--A DLL can be traversed in both forward and backward direction.
-- The delete operation in DLL is more efficient if pointer to the node to
be deleted is given.
--We can quickly insert a new node before a given node.
--they use more memory than arrays because of the storage used by
their pointers.
Stack:
--it is the child class of vector
--it is specially designed class for LIFO order
Constructor of stack
Stack s=new Stack();
methods
push()
pop()
peek()
empty()
search()
Cursors
if we don’t want all objects at a time instead one by one then we go for cursors
--Enumeration
--Iterator
--ListIterator
Set:
-- It is the child interface of Collection
--If we want to represent group of individual objects as single entity where duplicates are not allowed and insertion order is not preserved then
we should go for Set.
Implementation classes for Set are
HashSet,LinkedHashSet,TreeSet
HashSet:
--The underlined data structure is hashtable
--Duplicates are not allowed
--null insertions are possible but only once
--Heterogeneous elements are allowed.
--HashSet implements Serializable,colenable
--whenever our frequent operation is searching then go for HashSet
constructors of HashSet
HashSet h=new HashSet();
creates an empty hashset object with default capacity of 16 and default ratio as 0.75
HashSet h=new HashSet(int initialcapacity)
HashSet h=new HashSet(Collection c)
creates an equivalent hashset for the given Collection.
Eg: for a given vector create an hashset
its meant for interconversion bw collection objects
Fill ratio or load factor:
fill ratio :0.75 means after filling 75% ratio a new hashset object will be created automatically
LinkedHashSet:
--It is the child interface of HashSet ,it is exactly same as HashSet(including constructors and
methods)except the following differences
HashSet LinkedHashSet
1.Hashtable is the underlined ds 1.LinkedList+hashtable is the underlined ds

2.Insertion order is not preserved 2.Insertion order is preserved

3.released in 1.2v 3.released in 1.4 version


SortedSet
--It is the child interface of Set
--if we want to represent group of individual objects according to some sorting order without duplicates then we should go for SortedSet
--SortedSet contains some methods which are not applicable to Set.
First()
last()
headset(obj):returns sortedset whose elements are less than obj
tailSet(obj):it returns elements greater than and equals to obj
subset(obj1,obj2):returns sortedset whose elements are >=obj1(inclusive) and <obj2 (exclusive)
NavigableSet
--It is the child interface of SortedSet and it defines several methods for navigation purpose
--TreeSet is the implementation class for NavigableSet
floor(e): returns highest element which is <=e
lower(e):returns lowest element which is <e
ceiling(e):returns lowest element which is >=e
higher(e): returns next greater element
pollFirst():remove and return first element
pollLast():remove and return last element
descendingSet():it returns NavigableSet in reverse order
TreeSet:
--underlying datastructure for TreeSet is balanced tree
--Duplicates are not allowed
--Insertion order is not preserved
--Heterogeneous is not allowed
--null is allowed only once
--TreeSet implements Serializable.
--All the objects are inserted based on some sorting order .it may be either default natural sorting order or customized sorting order
Constructors of TreeSet
1)TreeSet t=new TreeSet();
creates an empty TreeSet object where all the elements are inserted by using default natural sorting order

2)TreeSet t=new TreeSet(Comparator c)


creates an empty TreeSet object where all elements are inserted by using customized sorting order specified by
Comparator object

3)TreeSet t=new TreeSet(Collection c)

4)TreeSet t=new TreeSet(SortedSet s);


--if we are depending on default natural sorting order compulsory objects must be homogeneous and comparable
otherwise will get Runtime exception saying ClassCastException.
--If the corresponding class implements Comparable (Interface) then it is said to be comparable
--All the wrapper classes ,String class is comparable .

Comparable
its present in java.lang and contains only one method compareTo()
public int compareTo(Object obj)
--obj1.compareTo(obj 2)
--returns negative if and only if obj1 comes before obj2
--returns positive if and only if obj1 comes after obj2
--returns 0 if obj1 and obj2 are equal
--if we are depending on default natural sorting order then while adding objects into the TreeSet, jvm will call
compareTo() .
Comparator
--whenever we are not satisfied with default natural sorting order then we can go for customized sorting by using
Comparator.
--it is present in java.util package
--Comparator defines two methods :compare () and equals()
public int compare(Object ob1,Object ob2)
--returns negative iff obj1 comes before obj2
--returns positive iff obj1 comes after obj2
--returns 0 iff obj1 and obj2 are equal

public boolean equals(Object obj)

--whenever we are implementing Comparator compulsory we should provide implementation for compare()
and we are not required to provide implementation for equals() because it is already available to our class from Object class through
inheritance

various possibility of compare()


1)return I1.compareTo(I2)
default natural sorting order

2)return –I1.compareTo(I2);
Desecending order

3)return I2.compareTo(I1);
desecending order
4)return –I2.compareTo(I1);
Ascending order

5)return +1;
Insertion order

6)return -1;
reverse of insertion order

7)return 0;
only first element is inserted and rest are treated as duplicates
1)Wap to insert integer objects into the TreeSet where the sorting order is descending order

2)Wap to insert String objects into the TreeSet where all elements should be inserted according
reverse order of alphabetical order

3)Wap to insert string and stringbuffer objects into TreeSet where sorting order is increasing length
order.if two objects having same length then consider there alphabetical order.
Map
--map is not the child interface of collection.
--if you want to represent a group of objects as key –value pair then we should go for Map
--key and value both are objects
--duplicate keys are not allowed but values can be duplicated
--each key-value pair is called entry
--Hence map is considered as a collection of entry objects or group of entries is called Map
--Map is nowhere related to Collection so it will have its own methods.

Collection views of Map

1.Set KeySet() : returns only keys

2.Collection values(): returns only values

3.Set entrySet(): returns the total entrysets


Interface Map
{
interface Entry
{
Object getKey()
Object getValue()
Object setValue(object )
}
}
--without existing Map object there is no chance of existing entry object hence entry interface is defined inside Map interface.
HashMap
--The underlying data structure is hashtable
--Insertion order is not preserved and is based on hashcode of the keys
--duplicate keys are not allowed
--duplicate values are allowed
--Heterogeneous elements are allowed for both key and values
--null values is allowed for key (only once) and null is allowed for values(any no of times) .
--HashMap implements Serializable
--HashMap is the best choice if our frequent operation is searching
How to get synchronized version of HashMap object
HashMap h=new HashMap();
Map m1=Collections.synchroziedMap(h);
LinkedHashMap
--it is the child interface of HashMap
--the underlying datastructure is hashtable+LinkedList
--Insertion order is preserved
--it was introduced in 1.4 version

SortedMap: if we want to represent group of objects as key-value pair according to some order of keys then we should go for SM.
TreeMap
--the underlyimg datastructure is RED-BLACK-TREE
--Insertion order is not preserved and it is based on some sorting order of keys
--Duplicate keys are not allowed but values can be duplicated
--if we depending on default natural sorting order then keys should be homogeneous and comparable otherwise we will get RuntimeException
saying ClassCastException.
Constructors of TreeMap
1)TreeMap t=new TreeMap();
creates an empty treemap object with default natural sorting order of keys
2)TreeMap t=new TreeMap(comparator c)
creates a empty TreeMap object with customized sortig order.
Hashtable
--the underlying ds is hashtable.
--insertion order is not preserved and it is based on hashcode of the keys
--duplicate keys are not allowed but values can be duplicated
--heterogeneous objects are allowed for both keys and values
--null is not allowed
--it implements serializable.
--every method present in hashtable is synchronized
--hashtable is best choice if our frequent operation is searching
Constructors of hashtable
Hashtable t=new Hashtable();
creates an empty hashtable with default capacity of 11 and default fill ratio of 0.75.
same as hashmap …
Properties
--In our program if anything is changing frequently (like username,password,mailid,mobile no etc)then its not recommended to hardcode in java programs because if there is
any change to reflect that change recompilation,rebuild and redoployment of application is required.
--we can overcome this problem by using properties file .such type of variable things we have to configure in the Properties file.
And from that properties file we have to read into java program and we can use those properties.
--the main advantage of this approach is if there is a change in properties file to reflect that change just redoployment is enough.
--here key and value both must be a String.
Constructors
Properties p=new Properties();

Methods
String getProperty()
to get the value associated with the specified property

String setProperty()
to set the new property

void load(InputStream is)


to load properties from properties file into java properties

void store (OutputStream os)


to store properties from java properties into properties file
NavigableMap
--it is the child interface of SortedMap .
--It defines several methods for navigation purposes
methods:
floorKey(e)
lowerKey(e)
ceilingKey(e)
highestKey(e)
pollFirstKey();
pollLastKey();
descendingMap();
PriorityQueue
--If you want to represent group of individual objects prior to processing according to some priority then we should go for priority
queue.
--it can either be default natural sorting order or customized sorting order defined by comparator
--insertion order is not preserved
--duplicate object are not allowed
--if we are depending on default natural sorting order then objects must be homogeneous and comparable.
--null is not allowed
Constructors
PriorityQueue r=new PriorityQueue()
creates an empty PQ with default capacity of 11 and objects are inserted according to default natural sorting order
methods
offer() to add a object into the queue
poll() to remove and return head element of the queue .. Returns nulll
remove() to remove and return the head element---returns NoSuchElementException
peek() return the head element of the queue. ----returns null
element() to return head element of the queue---returns NoSuchMethodException
Utility classes
Collections
Arrays
Collections: it is a utility class for defining several utility methods for collection objects.

Eg: Collections.sort(al);
Collections class defines several utility methods for collection objects like sorting ,searching ,
reversing etc.

Sorting:
Collection class defines the following two sort methods.
1)public static void sort(List l)
by default it will be sorted according to default natural sorting order(homogeneous and comparable)
2)public static void sort(List l , Comparator c)
to sort according to customized sorting order.

--the list should not contain null values otherwise NPE.

Searching:
Collections class defines the following binary search methods
1)public static int binarySearch(List l,Objecttarget)
if the list is sorted according to default natural sorting order then we have to use this method.
2)public static int binarySearch(List l, object target,Comparator c)
we have to use this method if the list is sorted according to customized sorting order.
Conclusions:
--The above search method internally will use binary search algorithm
--Successful search returns index.
--Unsuccessful search returns insertion point
--Insertion point is the location where we can place target element in the sorted list
--Before calling binarySearch method compulsory list should be sorted otherwise we wil get unpredectible results.
--if we are trying to sort the list according comparator we need to pass the comparator object otherwise will get unpredectible
results.
Reversing elements of list
public static void reverse(List l)
Collections defines the following reverse method to reverse elements of the list
Arrays
Arrays class is an utility class to define several utility methods for arrays or array objects.
Sorting
searching
sorting elements of array
public static void sort(Primitive[] p)
--to sort according to default natural sorting order
public static void sort(Object[] o)
--to sort according to default natural sorting order
public static void sort(Object[] o,Comparator)
--to sort according to customized sorting order

You might also like