Presentation - Core Java
Presentation - Core Java
Presentation - Core 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 .
• 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.
}
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.
}
Class and object
method calling
If a method has instance and local variables with same name then priority goes to local variable.
Template method
• 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();
new Test();
.
🡪we can have multiple instance blocks but the order will be
from top to bottom.
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.
🡪order of modifier is not important instead of public and static we can write static and
public
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 ? :
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
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
--inside switch it is possible to declare any number of cases but is possible to declare only one default.
--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:
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.
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
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 )
Polymorphism
ex : method 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.
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
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.
• 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.
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.
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.
--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
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
1)throw keyword is used to create the exception object explicitly by the developer for predefined exceptions.
2)throw keyword is used to create the exception object explicitly by the developer for userdefined exceptions.
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;
syntax:
datatype a[]=new datatype[size];
or
int[] a={10,20,30,40,50};
--Every array in java is an object hence we will use new operator to create an array.
--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.
--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.
--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)
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
SCP
s1
String s1=“ABC”;
heap
--if we create by new keyword 2 objects will be created
SCP
--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
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
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;
--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:
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.
--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
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();
}
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.
--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.
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??
For example:
--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
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
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
--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
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.
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
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.
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