Upload
suresh-kuma
View
226
Download
0
Embed Size (px)
Citation preview
8/12/2019 JDK Training
1/14
Java Training
What is a JDK? JDK = Java Development Kit
Developement
Writing Code
Any text editor
Compiling
JAVC
Running
JRE
Linking
LibrariesVerier
Class le should be genuineInterger being used to gain access to memory
Loader
Loads class, Initializes class data Execution
JIT
Byte code -> M/C Language
GC
No delete in Java!
Thread Manager
Help!
DOCS
Others: Javad (debugger), rmi (for distributed objects). All of these -> found in jdk/bin
8/12/2019 JDK Training
2/14
Java Training
Code Quantum:Class
Class
default Not visible outside package
public visible outside package
abstract Can not be instantiated
nal Can not be inherited
strictfp Equivalent oating point resultsMembers
Fields
Access Modiers
private, default, protected, public
staticClass Fields
nalNamed constants
volatileNo optimisation please!
transientDo not serialize
Method
Method Modiers
Access Modiers
private, default, protected, public
staticClass Methods
Synchronize
One thread at a time
nal
Implementation xed
abstract
No Implementation native
So what, if code is not in JAVA! strictfp
strictfp:till scope of method
Nested Classes
Access Modiers
private, default, protected
static
abstract
nal
strictfp
8/12/2019 JDK Training
3/14
Java Training
Access Modiers
Keep classes and its members in lowest possible scope for greater cohesion and lesser coupling.
Base A
Derived A UnrelatedA
PUBLIC DerivedB
UnrelatedB
Base A
Derived A UnrelatedA
PROTECTED DerivedB
UnrelatedB
Base A
Derived A UnrelatedA
DEFAULT DerivedB
UnrelatedB
Base A
Derived A UnrelatedA
PRIVATE DerivedB
UnrelatedB
8/12/2019 JDK Training
4/14
Java Training
What is strictfp?strictfp method:
All operations done on oating point numbers inside the method would not be optimised as perbase architecture
Results would therefore be equivalent across platforms.
strictfp class:
All oating point arithemetic inside the class (in methods, in initialisation expression, etc.)would be evaluated strictly
strictfp interface:
All oating point arithemetic inside the interface (in initialisation expression) would be evalu-
ated strictly. No method implementations here.
What is volatile?volatile eld:
No optimisations would be done by the compiler for this eld.
Consider the following code:counter = 5;
for(;;){System.out.println(counter);Thread.sleep(1000);}Compiler might get tempted to replace counter with 5 as the value is not changing. But otherthreads may change it and thus need not be 5 all the time. Making the counter eld volatilewould not let the compiler do this.
What is Static?Static eld:
Class properties: like number of instances created.
Can be referenced (whereever visible) by the object reference or class name. However classname should be used.
Initialised when class gets loaded.
8/12/2019 JDK Training
5/14
Java Training
Static method:
Class Method: like for creating and mantaining single instance of a class in Singleton DesignPattern.
Can be referenced (whereever visible) by the object reference or class name. However classname should be used.
Can access only static elds or class elds. A static method trying to access non-static eld islike an Apple factory trying to see the song begin played in some Ipod. In short it doesnt makesense.
However non-static can access static elds: like an ipod might be interested in its Serial number.Fair enough.
Static class:
Top level classes can only be: public, abstract, nal, strictfp. However nested classes can bestatic.
We nest classes when they are related. When the class being nested is related to the top levelclass and not instances of the top level class it is declared static.
Static interface:
Top level interfaces can only be: public, strictfp.(they are abstract by default).
Nested interfaces are static be default.
Static initialization block:
Initialization blocks are used for complex initialization common to all constructors.
Initialization blocks execute as if they are duplicated in the beginning of every constructor.
static initialisation blocks take care of static elds.
What is Abstract?Abstract method:
Method that has no implementaion. As soon as a method is declared abstract the corresponding class must also be declared abstract.
All methods of an interface are public and abstract by default.
Abstract class:
Can not be instantiated.
8/12/2019 JDK Training
6/14
Java Training
Needed when class can not be fully described until it is specifed a bit.
E.g. List, SinglyLinkedList, DoublyLinkedList, CircularlyLinkedList. List is the base classand rest three extend this base class. Now List has the location of the Header say, thus List can
implement the function isempty(). If header is null implies the list in empty, but methods likeadd and remove can be implemented only when we know the type of list we have. Thus Listcannot be desribed completely till we know what kind of list it is. Thus all such methods wouldbe abstract and List class would be abstract as well.
Used in Template Method Design Pattern, Implement whatever you can, DELEGATE the specicsto sub classes.
What is Final?Final eld:
Once initialized cannot be modied.
can be initialized after creation also. Till rst value is dummped it is called a blank nal eld.
C++ used to have initialiser list for initialising references and constant variables. No such toolneeded here
Final method:
Method that can not be overriden.
Overloading and overriding Overloading: same name,different(by order,number or type of arguments) argument list.
nal modier is a implementation detail and is not included in the argument list. Overriding: same name, same argument list AND same return type (return type is part
of the contract.Code that has reference of base class should not crip if gets object of subclass).
All functions are virtual(C++ VTABLE etc) by default. Therefore "reference.method"would always point to the method of the class whose object is being refered to by thereference. [different for elds, reference.eld woudl point to the eld of the class of ref-erence. Reason lies in the constructor chaining super constructor gets this reference of
subclass.] Constructors should not call public non nal methods (these might get overloaded)
nal and abstract are mutually exclusive modifers.
Final class:
Can not be extended, Maths class is nal.
8/12/2019 JDK Training
7/14
Java Training
What is transient?
transient eld: Will not be included during object serialisation
What is native?native methods:
Can be invoked from Java code but the implementation exists in some native language ususallyC,C++.
8/12/2019 JDK Training
8/14
Java Training
ExceptionsThrowable
Exception
IOException
RuntimeException
ClassNotFoundException
Error
AssertionFailed
Checked Exceptions:
Must be handled. Should either be caught and handled or the enclosing method should throw them explicitly Can be attributed to factors like: le not opening etc.
Unchecked Exceptions:
Need not (rather should not be handled) Represent logical erros in the code. Therefore it is likely that program might be in irrecov-
erable state.
Catching and throwing exceptions:
Throwing an unchecked exception should be avoided as these can easily be overlooked bythe users of ur method
You should catch only what you are supposed to. Catching more than required can lead tomisinterpretations. For example see the code below:try{sum=getTotalSumFromDb();average=sum/totalCount;}catch( Exception ){System.out.println("Record could not be fetched from DB");}As we caught more general exception rather than spcic exception, thus even division byzero might be interpreted as DB problem.
8/12/2019 JDK Training
9/14
Java Training
Thumb rule: Be specic!! (in throwing and catching exceptions)
Finally:
Is always exceuted. Best place to do clearing work, closing stream, le handles etc. If catch throws exception still this code is exceuted. If it has a return statement: then that statement would override any other return. Return
after nallys return is unreachable. If catch and nally both throw exceptions, nally exception obejct would trickel down.
8/12/2019 JDK Training
10/14
Java Training
Inheritance Downcasting:
From top down. E.g. assigning a object reference to a string reference. This requires an explicit typcasting like this stringRef= (String) objecRef; Also the object reference should actually be refering to some string object. Otherwise class
cast.
Upcasting
However string is always an object. Therefore a string reference can always be assgined toobject reference
No explicit typcasting needed
Visbility Constrains
Since a code having reference of a super class be handed a reference from the sub class(upcasting) the sub class is bound to adhere to the contract of the super class.
Thus if the super class says a function is public sub class can not I would make it myprivate.
Visibility can either be kept same or only increased.
Exception declaration
Again because of the above reason, exception list can only shrink or kept same As otherwise the contract would be broken Again the throws clause should have specic exceptions rather than having a super class of
these exceptions
Constructor Chaining
calling super classes constructor can be done like this super(); this()and super can be only the rst statements Explainantion of
Why should not we call public non-nal functions in constructors why reference.eld refers to the eld of class of the reference rather than the class of
the object being pointed to by the reference. Annonymous classes
you would encounter code like the following at various places.
viewer.getControl().getDisplay().syncExec( new Runnable() {public void run(){
viewer.refresh();
8/12/2019 JDK Training
11/14
Java Training
}});
Runnable is an interface therefore how are we able to do a new on that? Actually we are doing new on an annonymus class. The base class of this annonymous
class is Runnable (language takes care of the fact whether it should be "extends" or"implements"n).
as is evident u cannot have more than one such base classes or interfaces. Advantage: u need not name them!
Interfaces and multiple inheritance
Java doesnot allow multiple inheritance You can extend one class and can implement multiple interfaces You have one identity(class extension) but can have multiple abilities (interfaces) That is why interface name ends with "able" Like throwable
Consturction of Objects
When an object is created, memory if allocated for all its elds including those inheritedfrom superclasses and those elds are set to their default values: Numeric types: 0 Boolead : false Character: 0000 Object References : null
After this (donot worry about the nal elds they can blank nals) Invoke superclasss constructor Initialize the elds using their initializers and any initialization blocks Then for the current class
8/12/2019 JDK Training
12/14
Java Training
Polymorphism Poly = many, morph = form, sounds cool! but who is taking various forms here?!
An object... as these can come as Object,or Exception or as RuntimeException each time it"identies" itself with different identities.
This according to me is the most powerful feature of OOP. This allows us to
Program to an interface Good design = references are always of Interfaces. The moment you create an object = you tie your code forever Somewhere down the line you will have to tie the knot but ... before that we should have
layers of interfaces as that gives us as many layers of data independence. We can changewhatever lies below the layer of interface without affecting what lies above it.
It makes it possible to change implementation even without changing the new clause. Aswhat to create is delegated to spring which it gets from some xml and hence has been madea conguration.
As the interfaces donot have any implementation the problems associated with Diamondinheritance is not here.
8/12/2019 JDK Training
13/14
Java Training
Threads Answer to why threads? is same as answer to why concurrency? ..apparent!
Creating threads objects and spawing threads are different tasks. Thread represents a unit of work This unit of work can be created in two ways
In the form of thread Create a runnable and assign it to some thread. Work is what is written in the run method.
Important functions and the state transitions of the thread.
Ready to Run
Running
scheduling
yield()
Terminated or Completed
Dead
Not Runnable
Sleepingsleep()
Blocked for I/O Blocked for Join
join()
Waiting for notication
wait()
Blocked for lock acquisition
on notication
Synchronization
Once we have multiple lines of execution, They can get interleaved. Thus it has to bemanaged.That essentially means synchronizing access to resources.
Synchronization: Take locks on something (object, this, class) release only when you aredone or you cannot proceed any further(Exceptions)
Instance Method Synchronization: When a thread start execution of a sync. method it acquires the thread on "this". Lock is held per thread and not per method, so if a sync method calls another sync
method on the same object.. No problem!
8/12/2019 JDK Training
14/14
Java Training
Only the resource knows who all are waiting for it thus functions like wait, notify andnotify all are ll in Object class.
Block Synchronisation
Lock on a particular object (not this). Therefore instance and static sync methods canstill be called.
Good way as you can limit the locking period to core Critical Section(always a goodidea)
Class Method Synchronization Lock on Class object of the class. (Tangled Hierarchies!!) Once a class method is being executed by a thread, no other thread can execute a sync
class (static) method. However can very well execute an instance method (synced , ornot)
Scheduling : All above points take care of resource access but not scheduling. Schedulingis taken care by the Thread Manager of JVM. There some hooks using which we canmanipulate (to some extent) this scheduling. Sleep
From Running state to sleep state Locks are not released Would sleep for at least the mentioned time, then it would be scheduled from, Ready
Queue Yield
From Running to Ready to Run locks are released CPU intensive job to work in work quantums
Join Calling thread would not proceed till the run method of the thread on which join
was called gets nished I would join xyz.
Wait From running to wait set of the object Once notied (when in wait set) goes to stage of Waiting for lock aquisition Once lock aquired goes to ready to run state, ready to get scheduled.