Wednesday, December 30, 2009

JVM tuning

In any production server using JVM performance can be improved by tuning the JVM parameters particularly those parameters which are related to memory and garbage collections.

We will try to learn about some JVm parameters which should be taken care of while going in production.

Heap size

The heap is the runtime data area from which memory for all class instances and arrays is allocated. The heap may be of a fixed size or may be expanded. The heap is created on virtual machine start-up. If you have complicated algorithms or big caching which might create lot of objects in memory you may need bigger heap size.

YOu can use the following java code to find out the heap size.It is in case of a simple java programme.

public class getHeapSize {
public static void main(String[]args){

//Get the jvm heap size.
long heapSize = Runtime.getRuntime().totalMemory();

//Print the jvm heap size.
System.out.println("Heap Size = " + heapSize);
}
}

The allocation of memory for the JVM is specified using -X options.

for example if you are using sun JVM the parameters are

-Xms initial java heap size

-Xmx maximum java heap size

-Xmn the size of the heap for the young generation.


In my previous posts i have discussed about JVM in learning java,however we need to go much deep in to the jvm in order to undestand the concept of jvm tuning.We will once again look in to the structure of JVM and try to find out what goes inside and how to fine tune it.


JVM as we have seen earlier executes the byte code and generates the output.JVM is a virtual computer that resides in a physical computer as a software process.However to generate any output jvm uses several components.The main components of JVM Are
the stack, the garbage-collected heap, the registers and the method area.we will check each of them one by one.

STACK-Stack in a Java virtual machine stores various method arguements as well as the local variables of any method.IT contains three registers which help in the manipulation of the stacks.Stack also keep track of each and every method invocation.
The three registers are

Vars register-All the local variables that are used during a method invocation are stored in Vars register.

Frame register-It is used to maintain the operation of stack itself.

Optop register-Here the parameters for bytecode instructions are placed, and results of bytecode instructions are found.
==================================

Method area-It is the actual aread where the byte code resides.The JVM has a program counter which always points to the next instruction and keep track of the current execution.

==================================

Garbage collection heap-The java programmes are stored here.when ever we create an object the memory is taken from this heap only.Any local object reference resides on Stack but the actual object resides in Heap only. Arays are also objects so they are also stored in garbage collection heap.


In java you can use the following scrip to find out the
Used Memory:
Free Memory:
Total Memory:
Max Memory:


public class Movie {

public static void main(String [] args) {

int mb = 1024*1024;

//Getting the runtime reference from system
Runtime runtime = Runtime.getRuntime();

System.out.println("##### Heap utilization statistics [MB] #####");

//Print used memory
System.out.println("Used Memory:"
+ (runtime.totalMemory() - runtime.freeMemory()) / mb);

//Print free memory
System.out.println("Free Memory:"
+ runtime.freeMemory() / mb);

//Print total available memory
System.out.println("Total Memory:" + runtime.totalMemory() / mb);

//Print Maximum available memory
System.out.println("Max Memory:" + runtime.maxMemory() / mb);
}
}


Now we have some idea about the jvm we will dicuss about some jvm parameters and then we will check based on what criteria should we give values to them.

So depending upon your RAM size you have to assign values to the different parameters in your JVM.If your application runs on a single jvm or to make it more easy lets suppose your server uses a JVM and you want to assign it some values.If you have a ram og 2gb then you can have an initial heap size of 1gb.Please understand that there is no perfect settings for jvm.You have to do a lot of R &D in order to reach a correct setting.

As per sun recommendation the inital heap size and the maximum heap size must be the same. ie -Xms and -Xmx should be same.

The maximum heap size -Xmx controls how much memory the JVM can use. If your BPEL instance runs on a dedicated machine it can be set as high as the maximum memory space of your Operating System.

We have also talked about Eden space -Xmn.

It is the place where in short term process are stored as most of the process are short lived.So it should be 60-70% of the maximum heap size.

so having all these condition an ideal setting should be

-Xms2048m -Xmx2048m –Xmn1228m

This setting i have considered for a machine with 32 bit operating system linux box

The same settings can be applied in windows as 32 bit operating system in windows have a limitation for 2gb ,so if you don't have any other server or installation in your windows system then you can apply these changes.

If more than 2 cpu are getting used then one can go for aggressive heaping ,it is done by adding the following flag

-XX:+AggressiveHeap

This flag check the available memory and the number of processor associated with the machine automatically sets different properties for optimal performance.It works best in non windows environment.It does not have any effect on the performance of windows operating system.

So with all these setting the full configuration should be looking like


-Xms2048m -Xmx2048m –Xmn1228m -XX:+AggressiveHeap

Creating HL7 document

In this section we will be creating HL7 document.

One will be the request document and other will be the acknowledgement document.

Again go to the Oracle B2b document Editor

In the left column slect new document

and choose HL7 folder



Now in the next window choose the version 2.3.1



Expand the folder and choose Event A01:ADT/ACK-Admi/Visit Notification

and there in select ADT:ADT Message and say next




Now in the next window verify that the insert envelope segment is deslected and say finish.



Now check the document created.



Now once the document is created .go to file menu and say export

In the export wizard select B2B as the export type and say next



Now choose the folder location where you want to store your .ecs file and give it some logical name as HL7_231_A01.ecs




Say save and then the next window will come which will give the location and name for the xsd file.




Say next and let the default seelction be there.Only deselect the last option to launch oracle integration b2b.




SAy next and then finish the wizard now verify the files .ecs and .xsd that are created in the folder structure provided by you.

Once these steps are completed do the same steps for the acknowledge document.REpeat the same step and provide some logical name to the acknowledge document.

Creating RosettaNet PIP3A4 document

In this section we will be creating a purchase order request and a purchase order confirmation for Rosettanet.

Again go to spec builder.In the left column select new document to start the new document wizard,there in select Rosettanet and then choose the pip3A4 and say ok




The following document will be created once you will say ok




Now again go to file menu and select export,there you choose the RosettaNet XSD as the export type





Say next and choose the directory where you want to save the .xsd file.Please provide it a logical name as i have provided it as PIP3A4.xsd




Say next and choose all the default options provided.



SAy next and the document will be created as shown below.Once it is created say finish.



Now verify in the folder location if you have the .xsd file created at that place.

Now again go to the document say export and choose Rosettanet XSD this time save the exported file as PIP3A4.ecs



Say next and choose all the options




The document gets create say finish and exit the wizard.Then check in the folder locatin whether the required file is created or not.You can also escape this second phase of creating the ecs file and directly close the document created which will ask for an option to save it before closing.You can give the file name as PIP3A4.ecs and save it as .ecs file.


This step was done to create purchase order you have to repeat the same process to create the purchase order confirmation document in both the trading and host partner.

Working with Spec Builder-Creating EDI-X12 document

In EDI x12 850 is the code for a purchase order similarly 997 is the functional acknowledge ment in EDI-x12.

We will be creating a document for EDI purchase order(850) and EDI functional acknowledgement.

OPen the B2b document Editor also known as spec builder.

In the left column select the new document tab to create a new document.

YOu will get a window like this.Just select EDI x12 from there and say ok



ONce you will say ok you will get a list of folders.These are the different versions of the EDI - x12 document.We will select here v4010




Expand the folder and select 850 purchase order from there.



Then say next and verify that the insert envelope segment check box is deselected and then say finish.



You will get a screen like this.



Now go to the file menu option and say export.

YOu will get a window like this



Now choose Oracle B2B type to export the document as shown and say next



Now just save the ecs file and the xsd file in some specific location from where you can easily retrieve them.Please provide some logical name to the files.As i have provided it as EDIX12_4010_850.ecs




Also save the xsd file created for the same document




Then say next and let the default option be selected




Say next and then finsih the wizard and verify in the directory structure if both the files have been created succesfully.



In a similar way you can create the document for the 997 that is functional acknowledge ment from the EDI-x12 for 850 purchase order.YOu can again give it some logical name EDIX12_v4010_997 or as per your ease.

We are creating these document because we will be checking the functionality that how b2b 11g works and how it communicates.so the same stpes have to be followed in another machine also.In b2b we generally have one host and one remote trading partner so you have to follow these stpes both the host and the remote trading partner.

Tuesday, December 29, 2009

Oracle Weblogic Server

We will now see how to set up a cluster in weblogic 10.3 but before that we need to have some concepts about the terms and terminology in weblogic.

WEblogic is an Enterprise J2EE Server which provides higher reliability,Availability, Scalability and Performance.

Few important terms in weblogic

A domain in a weblogic server is a group of instances and clusters under one single control.Domains contains a WebLogic Server instance called the Administration Server we also called in short it as admin server.This is the main place from where we control and manage all the resources in a domain. We also create our own weblogic instances called as managed server.We deploy our application in the managed server and from admin server we configure and monitor them.We have a terminology called cluster within a domain which is nothing but group of managed servers to provide increased scalability and reliability to the end users.Also we have node manager which is a process to start/stop and auto restart the managed server.so essentially our domain consist of one admin server, one or more managed server,one node manager and one or more cluster.

Again a server in weblogic can be a standalone server or it can be a part of a cluster.All Managed Servers in a cluster must reside in the same domain i.e. you cannot split a cluster over multiple domains.


If you have created multiple domains in weblogic, then each domain must point to its own database schema. You cannot share a configured resource or subsystem between domains. For example, if you create a JDBC data source in one domain, you cannot use it with a Managed Server or cluster in another domain.You must create a similar data source in the second domain.

When a Managed Server starts, it connects to the Administration Server to check the data maintained by the admin server.so whenever a configuration is changed the admin server sends the changed configuration to the managed servers.

Weblogic scripting tool(WLST)

WLST is a scripting language based in jython.It is a Scripting tool for administering a domain (create, configure, manage, monitor, deploy applications).We have a record feature in admin console of weblogic.This records the data in the form of wlst scripts.There are two modes of WLST script

1>Offline WLST
With offline WLST you can create a domain template,or create a domain based on existing template without connecting to the server.

2>Online WLST
WLST online is a Java Management Extensions (JMX) client.With online WLST you can connect to a running admin server,manage the configuration of a domain and check its performance data.


NOde Manager

Node Manager is a WebLogic Server utility that enables you to start, stop, and restart Administration Server and Managed Server instances from a remote location. It is not associated with a domain but with a machine.

Machine is nothing but a logical name for a computer to associate it with its managed server.

Again one important feature of weblogic is jrockit.It is developed to optimize performance on Windows and Linux only.It is BEA's version of JVM.YOu can also use SUN's JVM.

Now in weblogic for a domain the most important configuration file is config.xml which is the central configuration file for a domain.

How to set up BPEL cluster

In my previous posts i have discussed how to set up an applicaiton server cluster.I have missed the part how to configure the bpel cluster.

I will start from the point that you have SOA Suite installed on two different machines and you have oc4j_soa container on both the hosts.

Both the container or SOA suite should have the same dehydration store.Now just install bpel process manager on both the host on top of the container oc4j_soa.

Once bpel is installed on both the node you need to do the following in order to set up a bpel cluster.

Go to SOA_Home/bpel/system/config/collaxa-config.xml file

Set the "enableCluster" property to "true" for all BPEL nodes in the cluster.


Set Value of the "clusterName" property to "Load-balancer host:port", which needs to be the same for all bpel nodes in a cluster in order for them to find each other

It will be more clear from this diagram




As you can see we have set the "enableCluster" property to "true"

and in the Load balancer host and port number i have define the value myLBR.com:7777

here myLBR.com is my host name for the load balancer and 7777 is the port number in which my load balancer is running.Oracle provide web cache as a load balancer however you can have some other load balancer like pen or you can have hardware load balancer like bigip but hardware load balancer are too costly in comparison to software one.

Once these settings are don save the file and exit now go to the following directory
SOA_Home/bpel/system/config/jgroups-protocol.xml file.

If nodes are on the same subnet, use UDP multicast method. mcast_port and mcast_addr properties must be the same for all nodes in the BPEL cluster.

As you can see in the following diagram



Here mcast port

mcast_port="123445"

value should be same in all the nodes of the cluster i.e. if we have two bpel nodes then in both the nodes we should have the same value for the mcast_port number.
Same applies for the mcast address.

mcast_addr="220.220.220.220"

A multicast group address is an ip address in the range 224.0.0.0 to 239.255.255.255 that identifies the members of an IP multicast group.It broadcast the same message to all members of an IP multicast group,In a cluster we give the same multicast address to all the nodes so all the nodes becomes a member of the multicast group and the messages are trasnmitted to all of them.




It should also be same in both the nodes of the cluster.

If the nodes are on different subnet you should use TCP protocol.I have often experienced that udp protocol gives issues so i would prefer to use TCP protocol even if both the hosts are on same subnet or in different.So in tcp protocol you will configure something like this.



here initial_hosts="myhostA[7777],myhostB[7777]" these are the two host which runs on 7777 port.

Now go to the following path

SOA_Home/bpel/system/config/collaxa-config.xml file.

Set "soapServerUrl" and "soapCallbackUrl" properties to loadbalancer url:port.YOu can also change the same from BPELADmin console also.Once done save the changes and now try to open the BPEL console from the loadbalancer url and port.

Check the functionality of the cluster by deploying a simple bpel process in one node and by default it should get reflceted in both the nodes.

Also try to bring fown one node and check if the console and processes are accessible.

Monday, December 28, 2009

Proxy configuration in BPEL

Before understanding the porxy we must understand what a firewall mean.A firewall is a part of a computer system or network that is designed to block unauthorized access while permitting authorized communications. It is a device or set of devices configured to permit, deny, encrypt, decrypt, or proxy all (in and out) computer traffic between different security domains based upon a set of rules and other criteria.Proxt setting is one of the type of firewall techniques.


For enterprise customers it is important to be able to set up secure computing environments within their companies, and proxy configuration is an essential part of doing that. Proxy configuration acts as a security barrier, it ensures that the proxy server monitors all traffic between the Internet and the intranet. This is normally an integral part of security enforcement in corporate firewalls within intranets.


Lets suppose i have to access a bpel process that is running on a different network.Then i can not enter into any network i have to enter into that network through the proxy server.The proxy server will check if i have the proper authority to access the page,this may be based on some filter criteria also like it may filter by ip address.so once it will allow then only i can access the process.So proxy server is basically used to protect the internal process to be exposed to outside world.

To configure the Ant tasks and the Oracle BPEL Process Manager to use an http proxy
server you need to do the following

set OB_JAVA_PROPERTIES in SOA_HOME\orabpel\bin\obsetenv.bat

By defulat you will get the properties set to

set OB_JAVA_PROPERTIES="-Dhttp.proxySet=true" "-Dhttp.proxyHost=[HTTP_PROXY_HOST]" "-Dhttp.proxyPort=[HTTP_PROXY_PORT]" "-Dhttp.nonProxyHosts=[HTTP_NON_PROXY_HOSTS]"

YOu just need to provide the right details for the host and port

eg-

set OB_JAVA_PROPERTIES="-Dhttp.proxySet=true" "-Dhttp.proxyHost=myproxy.ora.com"
"-Dhttp.proxyPort=8090" "-Dhttp.nonProxyHosts=arahi.ora.com"


By setting http.proxySet to true, you activate the client proxy and redirect all the
outbound traffic through http.proxyHost and http.proxyPort. By setting the http.nonProxyHosts
to the server which hosts the BPEL server you prevent the local request from going
through the proxy. You might want to consider expanding the nonProxyHosts list to
include other servers inside your corporate network or other logical names for the
arahi.ora.com machine by using | as a delimiter.


here is our example we have the prooxy server myproxy.ora.com which runs on port 8090.Lets suppose i have a local network arahi.ora.com and i want to access some web service from a different network then all the request will be routed by this proxy server and port number.Since we have also defined that

-Dhttp.nonProxyHosts=arahi.ora.com

so our local request will not be routed to outside world.

How to set up JMS adapter for Oracle JMS

The J2EE Connector architecture defines a standard architecture for connecting the J2EE platform to heterogeneous Enterprise Information Systems (EISs).A resource adapter is a system-level software driver used by an application server or an application client to connect to an EIS.Here we will be creating a resource provider and try to connect to the underlaying appliactions.


To set up a jms adapter for oracle you first need to configure your resource for the connectivity.YOu need to go the the following directory.

SOA_HOME/j2ee/instance_name/config /application.xml

there you will find a line

data-sources path=”data-sources.xml”

we must take the bakcup for the file before making any changes.

SO now open the file and add follwing lines




Here arpitdemo is just the name of the resource you can name it any thing as per your wish or requirement.

jdbc/AQ points to the datasource configuration which is used for this resource provider.

So now we will make a corresponding entry in our datasource configuration for this resource provider.Go to the following

SOA_HOME/j2ee/instance_name/config /data-sources.xml

Take the backup of data-source.xml file and now try to modify it.

Add the following entry in to the data-sorce.xml



Save the file



In this datasource configuration

the jndi name that we have provided is the same that we have defined for our resource provider.
Replace with your Oracle Database SID. replace "yourUser" and "yourPassword" with your AQ user/password Save and exit.

now we need to make an entry in our oc4j-ra.xml file for the implementation.oc4j-ra.xml is the OC4J specific deployment descriptor for a resource adapter.

Now go to the following location

SOA_HOME/j2ee/OC4J_BPEL/application-deployments/default/JMSAdapter/oc4j-ra.xml

Again make a backup of the file and make an entry in the oc4j-ra.xml as




Here the arpitdemo resource is the one that we created earlier in application.xml. It is represented above as “java:comp/resource/arpitdemo/QueueConnectionFactories/myQCF”. The name myQCF is a user-defined name, and can be anything. We need to provide the username/password correctly.

Then save the change and restart your server to implement the changes.

Friday, December 18, 2009

Task Manager and Task Action handler

The TaskManager or TaskActionHandler processes are the default process which gets deployed in to your bpel server when we install the SOA Suite however in many cases these process in Oracle BPEL Control fail to deploy after installing Oracle Application Server or after upgrading.

YOu can find the following issues along with this like

The domain.log file present in SOA_HOME/bpel/domains/default/logs will give compilation error and xml parser error.


Either the TaskManager or TaskActionHandler or may be both will not appear in the bpel console

Http://localhost:port/BPELConsole.

or a third case is when you will have the .jar files in failed state.

In that case file named bpel_TaskManager_1.0.jar.failed or bpel_TaskActionHandler_1.0.jar.failed will be present in the ORACLE_HOME/bpel/domains/default/deploy directory.

TO overcome this issue

Navigate to

SOA_HOME/bpel/domains/default/deploy folder and there change the

bpel_TaskManager_1.0.jar.failed to bpel_TaskManager_1.0.jar

and bpel_TaskActionHandler_1.0.jar.failed to bpel_TaskActionHandler_1.0.jar

Once done restart your server and these process will be automatically deployed in the server.

Now you will be able to see both the process in the bpel console.

One more thing that we have captured here is if we will copy any jar file in the

SOA_HOME/bpel/domains/default/deploy location it will be automatically deployed to the bpel server when it will start because it is the default location used by bpel process manager to deploy the process while starting.

Monday, December 14, 2009

Learning JAVA

To undestand BPEL/ESB it is recommended to have a good knowledge of java,xml and j2ee server.YOu need not be a bond in all the three but you should have the concept about all the three to get an inner view of the process.

I will try to explain java in my words.

JAva as everyone of us knows is a programming language which is derived from c++.

It is an object oriented programming language.

Object-oriented programming (OOP) is a programming pattern that uses "objects" – data structures consisting of datafields and methods together with their interactions – to design applications and computer programs.




Java is generally referred to as java programming language.The java Virtual machine,java api and java class file work together to make the java phemonenon possible.Java is a robust language and is platform independent.Platform independent mean write once and execute any where.Once you have written the java code you can run it in any where jre is available.

We have discussed that the java architecture consist of four specification.

1>Java programming language.
2>Java class file format.
3>Java application programming interface(java API)
4>Java virtual machine.

Now we will check both the compile-time environment and run-time-environment

Compile time environment

Programme.java -àcompiler àProgramme.class

We have written a simple programme called Programme.java.
The compiler convert it into byte code Programme.class.

This is the only function that took place in compiler.

Now you have the class file so you can execute it in any platform.
It can be on local machine or it can be transferred to another system.


Run-time environment

Run time consist of java api and java virtual machine.The java api and jvm together is also called as java platform.When we write Java programme it access system resources by calling methods in the class which implements java api(example string.class, object.class) .

The class file that we have created “Programme.class” and the class file which implement java api together enters the java virtual machine which acts as an interpreter and execute the byte code to fetch the result.



So finally it comes to JVM.Now we will try to peep inside the JVM what it is and what it does.

Java virtual machine is an abstract computer.Its main job is to load the class files and execute the byte code.JVM contains a classloader and a execution engine.The classloader loads your programme class file and the class file from java api it converts it into byte code and then execution engine execute the byte code.

A simple execution engine acts as an interpreter which executes the byte code one by one,however we have another execution which is much faster than the simple execution engine ,it is just in time compiler or JIT.In this scheme the byte code is converted to native machine code the first time the method is invoked it is then cached so that the next time the code is invoked it can be directly loaded.So it will save time and the execution will be much faster.Now we will check each of the component individually.

Class loader-When a class file run it may need other class files also to perform its execution.These class files are loaded by the class loader in JVM.The class file may be present in the local system or may be in the network.The JVM uses the classpath to point to these class variables.The classpath can be added by using java –cp or java –classpath command.

Example- java –cp c:\jdk_home\jre\lib\tools.jar


One class files are loaded it goes to verification phase where in it check whether the java code fulfills the basic rules of java.This step ensure that no illegal actions are performed.

The jvm act as byte code interpreter that execute the byte code for the loaded class.The JVM keeps track of the memory so once the execution is completed and jvm finds that the object is no longer required.It marked the instace for garbage collection..Thus it manages memory also.Essentially in real application a jvm instance start running by calling the main() method .The main method must be public ,static,return void,and accept once parameter a string array.We will check these details later.This is infact very confusing in java as most of the things are interrealated and we can not have all the concepts at a single time so we will check these in our order.



Java-Object Oriented Programming

An object is a run time representation of a thing.Object oriented programming approach ensures that the programme survives the changes in the changing world and changing business needs.An object is an idividual entity which can be changed without changing the whole application.In shor we can say it is adaptable and reusable.It also defines the term abstraction,encapsulation,inheritance and polymorphism.I will cover it as soon the lesson will proceed.

JDK-Java development kit

The java development kit provides following

1>Compiler that is javac which is used to compile the java code.

If we have a programme movie.java then we will compile it by following command

Javac movie.java

This will create the byte code for the movie code called movie.class.

2>It provides the core class library.The library contains all the class files which are required for the execution of a programme.The jdk provide the library in the form of rt.jar file.

3>Debugger-It provides a debugger which helps in debugging ,finding the real place of error with the exact error messages.In JDK the debugger provided is jdb.

4>Byte code interpreter or jvm-IT interpret the byte code.

5>Documentation generator-Provide opportunity to create the java doc representing the structure of class files in the programme.

6>Java archieve utility-Several class files can be bunched together to form a jar file out of it.


Different edition of java


Java,Micro Edition-Used for small applications like smart cards,pagers,mobile etc.

Java Platfrom Standard Edition-Development environment for internet applications

Java Platform,Enterprise Edition-For implementation in application server.




Integrated development Environment

IDE is a tool which is used now a days to write your programme.It has many components which helps us in writing our code easily.It has some prebuilt code and other faciliteis which helps in decreasing the real time of creating an application code.
Most commonly used IDE is eclipse and jdeveloper.However we will be using jdeveloper for illustration.Again covering jdeveloper is a vast topic so I will directly go inside programming concept.You can write the same code in notepad and save and compile it using your command prompt.


Programming

To Start with programming in java we first of all need to know what is an object and what is a class.

We will try to understand the concept with the following example.Let suppose we want to construct a house.We might be having lot of ideas in our mind but we can not go with the same idea to construct a real house as physically the implemetation will be very different.So we need to model an architecture for the building i.e we need to first create map which covers all the essential details like how much materila will be used,what will be the cost and all other important details.

In java the class does the same work.It is the blueprint which defines the object.So essentially a class contain several properties and methods.

Now once the blue print or map is ready one can go ahead with this and implement the map in to physical existence.

In java objects do the same work.They use the class to retain there structure and behaviour to perform the task.



Understanding variable and methods

Lets suppose we have a pen then what can be attribute and functionality of the pen.The attribute may be lead colour,brand name,ink quantity and the methods can be to write.

In a similar way a class have variable and methods which together defines the attributes and functionality of the class.

As we have seen an object is basically derived from class.The object must be referenced to work with it.In java we create an object using the new command.

So if we have a Movie class we can create a object of movie class by following method

Movie obj=new Movie();

Here obj is our object and the new operator is used to create an object for a class.The object “obj” contains the reference for the newly created object of the movie class.


Let suppose our movie class has some methods.

How one will execute this method.They have to be called from the object

So if we have a method called rating() in our movie class it can be invoked by the object in the following way.

Call method from object- obj.rating()

As we have discussed the object has a reference.Its values are stored in the memory as a hashcode value.We will check it once we will get in to the details of programming.

As we have seen in our real world example we need to have a map in order to construct a house then only physical implementation tooks place.So this map can be used to create many other physical implementation.It can be implemented in the similar way by some other or can be changed in some way by others.Similarly in java a class can have multiple instance(objects).So we got the following idea about the class and object.A class is a template for the objects.A class defines variables and methods for all the instances of the class.

Now we will check some important terminology and concepts of oops(object oriented programming langauge).Java is called as an object oriented programming langague.The reason I am covering these definiton later is that I wanted to present an idea of object before getting in to what an object oriented programming languge mean.

Encapsulation

Encapsulation allows you to ignnore the low level details of how the object is structured and how it works internally.Lets take example of a television.We are not bothered about how it works internally.We only need to know how to start it and close it that is through interfaces provided like remote but we are not at all bothered how the lcd of tv works how it gets signal from antenna.These low level details are not required by us.Lets suppose the television company changes the software internally but still the interfaces are same that is still remote is same.So encapsulation hides the internal structure and operation of an object behind an interface.In our example television is an object and remote is the interface.


Inheritance

We often come across words saying that guy has inherited most of his father’s style or something like that.What exactly it mean.It mean that both the father and the son have commonality in them.Similary in java one class can inherit the other class.The class which is inherited is called as superclass and the one who inherit it is called as subclass.
A subclass is a kind of superclass.Now lets dig more in to it in terms of java ,Lets suppose we have a class called “two wheeler” as clear from the name,This class contain variables like wheel,gear,brakes and methods run stop.Now any other classes like herohonda,yamaha should be a subclass for the “two wheeler” class as “two wheeler” class is the superclass which defines all the basic format for a two wheel vehicle so it does not depend whether it is a herohonda motorcycle or a yamaha ,they have to have the brakes,gears and methods to run ,stop.But herohonda or yamaha can have there extra variable and methods in addition to the methods and variables defined in super class,i.e.
Herohonda can implement its own quickstart method,yamaha can have its own lighting on-off mechanism.So a subclass object should have all the variables and methods of a superclass object and in addition it can have its own methods and variables.


Polymorphism


Polymorphism means many forms.It means one operation can be perfomed by different methods or different ways.Suppose we have three person A,B and C all of them go to office by their own convenient way.A prefers to walk ,B uses motorcycle and C uses a Car.One important requirement of polymorphism is that same operation should be called for all the objects.So in our case if we issue an operation go to office then for the three person A,B and C the operation will be same but the way of going to office is different.
So Essentially a polymorphism requires that an object should send same message to different objects,enabling different objects to repsond in their own way.Polymorphism requires that the different objects implementing the same operation must have same semantics.In java we use the concept of polymorphism in overloading and overriding.
For the time being overloading a method mean using the same semantics but with different parameters to call a method and over riding means the sub class defining the same method in its own term as in the superclass.Java does not support operator overloading .Opearator overloading is supported only for + operator.

We will be covering all these definition later also when we will start programming.

Java Package

In java certain classes are grouped together in to a package as per their functionality.For example

Java.lang –contains all language functions
Java.io-Interface for all input/output operation.

And many more

When we write any java programme the very first line in the code is the package name i.e which package does this programme belong to.This is done essentially to separate two different programmes from each other.It is sort of name space in xml.If two classes have same name they can be differentiated by their package name.A good programming practice is that we should have a package and should have two folders source and code for .java file and for .class file.I will suggest to download the java SE documentation to understand the various package interface classes and methods avaialable.

You can go to www.sun.java.com go to java documentation there and download the java se documentation.



Contents of a java file

A java file should essentially contains the following things

1>the first statement should be the package keyword followed by the package name.

2>zero or more import statement followed by the class name.

3>One or more class or interface defintion followed by the blocks defining them.


Programming in java


Now we will start with the concept of programming.We will write a simple java programme,will see what are the different fields in there and how does it compile and execute.

For this we need to write a class.To define a class we need to have following things

1>Access modifier.-It specifies the availablility of the class from other classes.
2>Class keyword.-It tells java that the following block of code makes a class.
3>Instance filelds.-Constants and variable that are used by the object of class.
4>Consrtuctor.It is a method which has the same name as the name of the class and it is used to control the initial state of the object of a class created.
5>Instance methods.-It is the method within the class to perform the action.
6>Class fields-Constants and variables which are shared by all objects of that class.
7>Class methods-Methods that are used to control the value of class fields.


Understanding main() Method

AS we have seen earlier an interpreter need a main method to start the programme.One class should have one main method to start its execution or we can say it in other words that main the entry point for interepreter to start it.We need define main programme when we are writing an application however when you are writing an applete you need not define a main method as the browser has its own way of starting.


Important points about a main method

1>A main method must exist within a class.

2>It should have the following format

(Access modifier ) (static keyword) (return type) (arguments)

then the block of the code.

So a common format of a main method will be

public static void main(String[] args)


here public is an access modifier,static is a keyword ,void is the rerturn type and String[] args is the argument type.

We have used a term Access modifier what does it mean.It mean the accessibility of the method.

Access modifier are of four type

1.>Public-Public methods can be used by any one.

2>Priavte-Private methods can be seen or used only by the methods within the class.

3>Protected-Protected methods can be accessed by all the classed within the same package and all the derived class(class which are inherited)

4>Default-If you do not specify any access modifier it mean it is of default type.A default method can be accessed only by the derivative and classes within that packageEven a derivative outside the package can not access this method.


Static Keyword-

If a method or variable is define as static it becomes a class method/class variable.
It means that it applies to the class of the object as a whole and not as individual objects hence it is shared by all the objects of the class.


Return Type

A return type is always required in a method.The return type defines the object type that is returned when a method is completed.It can stiring ,integer,object or void value.By default there is not return type in a method.


Arguments

Arguments are the parameters which are required for the method to perform its function.

Example programme

So far what all we have studied we will check them through programme.Hence I will write a simple programme to illustrate various parameters in a java code.Lets check this simple programme.

package practice;

public class Example {
static int phone;
int name;
String value;
public Example() {
}

public static void main(String[] args) {
Example exam = new Example();
System.out.println("This is the entry point for the interpreter");
System.out.println("Value of name =" + exam.name);
System.out.println("Class variable=" + phone);
}
}


Looking from the beginning.I have specified the name of the package.I am not importing any class so I have not used any import statement.

Public class example

Public is the access modifier class is the keyword for defining class and example is the name of my class.One very important point to note here is that the name of the programme should be same as the name of the class and it is case sensitive.So in our case the java code should be saved as Example.java and not example.java.

Next name and value parameter are instance varaibles they can be accessed by methods in a class through object of the class.However variable phone is a class variable and as we have discussed a class variable is present for all the object of the class.

Next is our main method
We are then creating an object for the class example.

Next is we have the system defined command to print the variable values.
If you look in to the code you will find a block called

public Example() {
}

This is the constructor block. And is called when we create a new object for the example class.If you have not defined a constructor the java will provide automatically a default constrructor for the programme.

The instance variables and class variable are assigned a default values as soon as we declare them as here int will have a default value of zero ,string will have a default value of null and so on.

Now look at the two print out statement we are accessing the instance variable name through an object of the class however we are accessing the class variable directly.This is because it is static variable and a static variable can be called directly within a method.

Now we will compile this project.

To compile you have just write

Javac Example.java

I believe you already have set your class path and path variable.This command will cause a .class file to generate in the same location where in where Example.java resides.

Now to run this .class file you need to issue the following command

Java Example

It will give you the following result

E:\jdeveloper\jdk\bin\javaw.exe -client -classpath E:\jdeveloper\jdev\mywork\Application1\Practice\classes practice.Example
This is the entry point for the interpreter
Value of name =0
Class variable=0


Since I am using the IDE Jdeveloper to run my program I am getting jdev jdk as my classpath.

Please check all my class files are generated within the practice package.


You can set the path and class path from command window also by using set command

Aslo during compile time you can provide the class path as follows

Javac –classpath -d path to the source.

So as example you have

Javac –classpath C:\labs\classes package.Example.java

Please check that while defining the path to source we are using the pacakge.java file name.This is the correct convention in java we have to navigate till the package name in command prompt and then we have to provide the code.

For example if your Example.java code is within another folder source which is inside pacakge folder then we should use the following command to compile it.


Javac –classpath C:\labs\classes package.source.Example.java

=================================================================


Now we will see how to define a method in a class.

A method should consist of a method declaration,method variables,method statement and a return type.

Lets see an example for a method

Public float getfee(String cust)

{

int number1=12;
float number2 = 45.0f;
float fee;

fee=number1*number2;

return fee;

}


Here Public float getfee(String cust) is the method declaration .The variables defined are called as member variables.There is an important point about method variables that they must be initialized with some values.Again fee=number1*number2; is the method statement and finally return fee; is the return statement.Variables which are defined within a block are discarded when the block is completed.

So now we will include the method in our java code and compile to check its functionality.So now our code will look like this.

package practice;

public class Example {
static int phone;
int name;
String value;

public float getfee(float cust) {

int number1 = 12;
float number2 = 45.0f;
float fee;
fee = number1 * number2;
return fee;

}

public Example() {
}

public static void main(String[] args) {
Example exam = new Example();
System.out.println("This is the entry point for the interpreter");
System.out.println("Value of name =" + exam.name);
System.out.println("Class variable=" + phone);
System.out.println("calling method" + exam.getfee(12));
}


}

check out we have defined a new method getfee() and we are calling this method from the main() method.

System.out.println("calling method" + exam.getfee(12));

We have to call this method through the object.The object is created by new command .the new operator performs the following taks.It allocates and initializes memory for the new object created ,calls a special initialization method in a class this method is called a s constructor method and it returns a reference to the new object.Since a argument is required to pass in to the method we are passing a float value 12 the out put of the method will be the return type that is the valued of fee.So it we will execute this code we will get the following result.

E:\jdeveloper\jdk\bin\javaw.exe -client -classpath E:\jdeveloper\jdev\mywork\Application1\Practice\classes practice.Example
This is the entry point for the interpreter
Value of name =0
Class variable=0
calling method540.0
Process exited with exit code 0.







Primitve data Types


Java provides eight primitive data types and a large number of operators to manipulate these types.

You can refer to java books for getting much idea on the details data types



here

* not used
** added in jdk 1.2
*** added in jdk 1.4
**** added in jdk 1.5


Operators

Operators are used to manipulate the values that are stored in the variables.

Java provides 44 different operators which changes the values in the variables in one way or other.

Casting data type.

Java automatically converts a value of one numeric type to other higher numeric type.

Like byte ---àshort/char---àint----àlong---àfloat--àdouble.

I will not abe covering more on these opeartors fields as these are specific to certification of java.They can be learned by going through them once.

We have the program flow which includes loops ,switch,continue ,break,if else,do while and many more which has simple logics and can be understood easily.


Object Variable

When we declare an object variable it creates a chunk of memory which holds the reference for the object.It can be considered as a pointer to an object.An object instance variable is initialized to null to indicate that it does not yet refer to an object.we use an assignment opearator to assign any object to the object variable or we use new operator to create an object varialbe of some class type.

So if we define an object for the movie class

Movie mov1;

Then it contains null value.We will assign it to some object by following way

Movie mov1=new Movie();

This will create an object mov1 of Movie class which will contain the reference for the new object created for the Movie class,so if we will try to print out the value of mov1 we will be using the following command.

System.out.println(mov1);

It will fetch us the result something like this

practice.Example@1e5e2c3

here practice is the package name ,example is the name of the class @ is the always there and some codes this values is called as hashcode value for the object.Thus an object is mapped to some hashcode value in the memory.

Accessing instance variables and methods

Public instant variables can be acccessed directly using a dot operator.

If an instance method is public it can be called from any where in the program as we have seen earlier.If you specify a method as private it can be only be ionvoked by other method in the same class.If no modifier is defined it is default modifier and then the method can be called from any method of any class in the same package.


Now we will see how a private method is called from any method within the class.

So we will further modify our class as

package practice;

public class Example {
static int phone;
int name;
String value;

private float getfee(float cust) {

int number1 = 12;
float number2 = 45.0f;
float fee;
fee = number1 * number2;
return fee;

}

public String invoke(String inv)

{
System.out.println("calling private method" + getfee(12));

return "arpit";
}

public Example() {
}

public static void main(String[] args) {
Example exam = new Example();
Example exam1;
System.out.println("This is the entry point for the interpreter");
System.out.println("Value of name =" + exam.name);
System.out.println("Class variable=" + phone);
System.out.println("calling method" + exam.getfee(12));
System.out.println(exam);
System.out.println("calling private method from a method in class" + exam.invoke("rahi"));

}


}

We have defined here one more method called invoke and from this method we are calling the private method getfee()

Check out the output of this programme.

E:\jdeveloper\jdk\bin\javaw.exe -client -classpath E:\jdeveloper\jdev\mywork\Application1\Practice\classes practice.Example
This is the entry point for the interpreter
Value of name =0
Class variable=0
calling method540.0
practice.Example@1e5e2c3
calling private method540.0
calling private method from a method in classarpit
Process exited with exit code 0.

So we have seen an example how a private method can be accessed within a method inside a class.

============

Specifying multiple arguments in a method.


We will modify our same example to include more than one arguments in the method and see how it works

So our program will be

package practice;

public class Example {
static int phone;
int name;
String value;

public float getfee(float cust,int numb) {

int number1 = numb;
float number2 = cust;
float fee;
fee = number1 * number2;
return fee;

}


public Example() {
}

public static void main(String[] args) {
Example exam = new Example();
Example exam1;
System.out.println("This is the entry point for the interpreter");
System.out.println("calling method" + exam.getfee(12,12));
System.out.println(exam);


}


}



Here we are defining two arguments in the getfee() method.
We are giving two arguments float cust and int numb in our method.We will call this method by providing the two variables in the method call.

As you can see in our example we are calling the method by following

System.out.println("calling method" + exam.getfee(12,12));

Here we are providing two values float 12 and int 12 as input for the method.
As defined in the method.

Float 12 value will be assigned to float number2;
Int 12 value will be assigned to int number1;

So we will get the result of the two numbers as return type so when we will run this program we will get the following result

E:\jdeveloper\jdk\bin\javaw.exe -client -classpath E:\jdeveloper\jdev\mywork\Application1\Practice\classes practice.Example
This is the entry point for the interpreter
calling method144.0
practice.Example@1e5e2c3
Process exited with exit code 0.


Encapsulation in java

In any project we define the instance variable as private.Private decouples the interface of the class from its internal operation.Only instance method can access the private variables there fore we have always getter and setter methods in a class which is used to get and set the values of private variables.

Lets see how we define a getter and setter method

package practice;

public class Example {
private int phone;
private int name;
private String value;


public Example() {
}


public void setPhone(int phone) {
this.phone = phone;
}

public int getPhone() {
return phone;
}

public void setName(int name) {
this.name = name;
}

public int getName() {
return name;
}

public void setValue(String value) {
this.value = value;
}

public String getValue() {
return value;
}



public static void main(String[] args) {

}

}

Here we have defined three privarte varialbes phone ,name and value.

Check the getter and setter method for them.Getter method is used to get the value of the variable and setter method is used to set the value of the variable.

Now we will see how a private variables can be accessed through getter and setter method.We will take two java program as example.

The first is our Example.java programme which contains the variables and their getter and setter method .

package practice;

public class Example {
private int phone;
private int name;
private String value;


public Example() {
}


public void setPhone(int phone) {
this.phone = phone;
}

public int getPhone() {
return phone;
}

public void setName(int name) {
this.name = name;
}

public int getName() {
return name;
}

public void setValue(String value) {
this.value = value;
}

public String getValue() {
return value;
}


}


Another is our Example1.java class from where I am trying to access these variables through the getter and setter method.Here we are using another Example1 class for calling the methods to set and get the values for the private variables.

package practice;


public class Example1 {

public Example1() {
}


public static void main(String[] args) {
Example example1 = new Example();
example1.setPhone(21);
System.out.println("getting method" + " " + example1.getPhone()) ;

}
}



Here we can see we are using

example1.setPhone(21); to set the value for the phone as 21 and then we are using the getter method to get the values

example1.getPhone()

This will give us the result of the phone value.Hence the output of the following programme will be

E:\jdeveloper\jdk\bin\javaw.exe -client -classpath E:\jdeveloper\jdev\mywork\Application1\Practice\classes practice.Example1
getting method21
Process exited with exit code 0.

Here as we can see we are not using main method in Example class ,we are using the main method in Example1 class because we want only one entry point for the class.



Constructor


We have seen the default constructor created by a class.Now we will see how do we define a parameterized constructor.


As we know constructor is nothing but another method which has the same name as the name of the class.It should have return type and arguments.We will see the example as how parameterized constructor is formed.We are again using two classes

First is Example.java

package practice;

public class Example {
private int phone;
private int id;
private String name;


public Example() {
}
public void Example(int tel,int fid,String value) {

this.phone=tel;
this.id=fid;
this.name=value;
}
}

here we can see there are two constructor one is the default constructor

public Example(){}

and another is parameterized constructor

public void Example(int tel,int fid,String value) {

this.phone=tel;
this.id=fid;
this.name=value;
}


Now we will be calling the parameterized construcor from another java code to set the value of the variables.I am using Example1.java for the same so my code will be

package practice;


public class Example1 {

public Example1() {
}


public static void main(String [] args) {
Example example1 = new Example();
example1.Example(12,12,"arpit");
System.out.println("the flows end here");

}
}

here we are using the object of the class Example to call the the constructor

example1.Example(12,12,"arpit");

The out put of this programme will be

E:\jdeveloper\jdk\bin\javaw.exe -client -classpath E:\jdeveloper\jdev\mywork\Application1\Practice\classes practice.Example1
the flows end here
Process exited with exit code 0.

The out put here shows that the compiler has set the value for the private variables.It is another method to set the private varaibles other than getter and setter method.

This concept is also known as overloading.That is depending on the parameter value the corresponding methods will be invoked.

We will see another example to get this concept more clearly because overloading is an important concept in java.


Now we will define three methods other than the default constructor .Here is our first java programme Example.java


package practice;

public class Example {
private int phone;
private int id;
private String name;


public Example() {
}
public void Example(int tel,int fid,String value) {

this.phone=tel;
this.id=fid;
this.name=value;
}


public void Example(int tele){
this.phone=tele;
}

public void Example(int telephone,int empid) {
this.phone=telephone;
this.id=empid;
}
}


Now we will define another class with main method to call these parameterized constructor.So we will define another java programme called Example1.java

package practice;


public class Example1 {

public Example1() {
}


public static void main(String [] args) {
Example example1 = new Example();
example1.Example(12,12,"arpit");
System.out.println("Calling with three parameters");
example1.Example(12);
System.out.println("Calling with one parameter");
example1.Example(12,12);
System.out.println("Calling with two parameter");

}
}


AS you can see we are here calling three methods

example1.Example(12,12,"arpit") will call the method

public void Example(int tel,int fid,String value) {

this.phone=tel;
this.id=fid;
this.name=value;
}

example1.Example(12) will call the method

public void Example(int tele){
this.phone=tele;
}


and

example1.Example(12,12) will call the method

public void Example(int telephone,int empid) {
this.phone=telephone;
this.id=empid;
}

As we can see we have define three method other than the default method(constructor)
And depending upon the parameters passed the corresponding method will be called.This concept of overloading the method is called as method overloading as methods are overloaded depending upon the parameters passed.


We have to take care of an important concept here called as “this”

This operator is used to point to the current object.This will be more clear with an example.

============================================

“this” reference can be used inside any method to point to the current object.The current object is the object in which method is called.Inside a method any unqualified reference to a instance varialbe and method is implicitly associated with “this” reference.

For eg.

Public void setValue(String id)
{
emp_id=id;
this.emp_id=id;
}
here emp_id is the instance variable.

Now we will see what is the importance of the “this” opeartor

Lets suppose instead of the

Public void setValue(String id) I would have defined it like

Public void setValue(String emp_id) i.e. the argument passed is same like the instance variable now how we will refer to the instance variable emp_id.By default inside a method the more preference will be given to the local variable.So if we want to refer to the instance variable emp_id we have to use this operator.


Now see this example it will very clear
Lets again take two java class

Example.java

package practice;

public class Example {
public int phone = 13;

public Example() {
}


public void setValue(int tele_no) {
this.phone = tele_no;
}

public int getValue() {
return phone;
}


}


and there is another java class Example1.java

package practice;

public class Example1 {
public Example1() {
}

public static void main(String[] args) {


Example exam = new Example();
Example exam1 = new Example();

System.out.println("calling instance value" + exam.getValue());

exam.setValue(12);

System.out.println("calling exam object" + exam.phone);
exam1.setValue(23);
System.out.println("calling exam1 object" + exam1.phone);

}
}


Now we will see the out put of this program and then we will try to understand what does the this operator implies.

E:\jdeveloper\jdk\bin\javaw.exe -client -classpath E:\jdeveloper\jdev\mywork\Application1\Practice\classes practice.Example1
calling instance value13
calling exam object12
calling exam1 object23
Process exited with exit code 0.


As you can see we have defined the instance variable as 13 then we are using setValue method to set the methods to set the value to 12 and then to 23

As you can observe we are first of all calling the getVaue() which is fetching us the result of default value for the instacne variable.Next we are setting it to a value of 12 by using the object exam.And then we are setting the value to 23.As you can see each object has its own reference point though we are changing the varaible using exam1 object but still the values remains the same for exam object.


There is one more important usages of this.A constructor can use this reference to call another constructor.This will again be more clear with an example.

Again we have two java code Example.java and Example1.java

Example.java

package practice;

public class Example {
private int phone = 13;

public Example() {
this(12);
}

public Example(int tele) {
this.phone = tele;
}


public void setPhone(int phone) {
this.phone = phone;
}

public int getPhone() {
return phone;
}
}


Example1.java

package practice;

public class Example1 {

public Example1() {
}

public static void main(String[] args) {
Example exam = new Example();

System.out.println("instance variable" + exam.phone);
System.out.println("call method" + exam.getPhone());

}
}


If you will run this programme you will get the following output

E:\jdeveloper\jdk\bin\javaw.exe -client -classpath E:\jdeveloper\jdev\mywork\Application1\Practice\classes practice.Example1
calling exam object12
instance variable12
call method12
Process exited with exit code 0.


Lets see now what exactly is going on here.If you will look at Example1.java coding .We are creating an object to call the instance variable.As we know as soon as we create an object internally it calls the constructor of the class to initiliazes its value.Here as soon as the jvm finds the following command

Example exam = new Example();

It goes to the constructor


public Example() {
this(12);
}


Here as you can see there is a reference of this .It says this(12);

This means internally it calls another overloaded constructor which takes one int as argument.We can have chain of this where in the next overloaded constructor may call another construcor which takes two parameter.So in our case this(12) will search for another construcor which take an int as input argument,which in our case is


public void setPhone(int phone) {
this.phone = phone;
}

so this take 12 as input and set this value to the instance variable.So that is the reason we are not getting the value of 13 which have defined while declaring the instance variable but we are getting the value of phone as 12 which is getting set by calling the constructor.

Garbage collection

When all references to an object are lost the object is marked for garbage collection.Thus it reclaims the memory which is used by the object.Garbage collection is automatic in java and we can not initiate it programmatically but we can give a hint to system.gc();
As we donot have any free() or delete() command in java.If you want to force an object to be marked for garbage collection you can do it by setting its reference to null.

If an object holds some resouces then it should be able to clean it up.You can provide a finalize() method in that class.The finalize() method is called just before the garbage collection.It tells the jvm to clean up the resources.The finalize method is called automatically when the jvm calls for garbage collection.



Inner Classes

Classes declared inside another class is called as nested class,one common type of nested class is called as inner class.
We can also say it in another way as nested classes which are defined within a class or method.There are four type of inner classes.

Class defined in a class
1>Static inner class
2>Member Inner class.

Define in a method
3>Local Inner Class.
4>Annonymous inner class.

Static Inner Classs

A static inner class is a class that is defined inside any other class and is marked as static.
An example of static inner class is like this.

Public class outer
{
private int phone;
….

Public static class inner{
Public void anyMethod()
{
}

}


}

Static inner class may contain its own variable and methods.
They can be instatiated like this

Outer.inner obj = new outer.inner();

Members of static inner class can access all the methods and variables of an innner class but they can access only the static members of the outer class.

This class when compiled create two class files.One class file is outer.class and the other class is outer$inner.class


Member Inner Class

Member inner class is again a class defined within another class.Here nesting is allowed.It can access members within its own class and any outer class.It can declare only final static method


Public class Calendar
{
….
class month{
class day{
}


}
}


Here the top level class calendar is being accessed and month class is the inner member class of the calendar class and day class is the member class of the month class.The month class will populate the dates class output and month class with return the result of days in a month to the calendar class.


Local Inner Class

Local inner class are the classes defined in a method.All final variables or parameters that are declared inside the block are accessible by the methods of inner class.

Public class Calendar{
Public void method(){
Class Date{…};
Date date=new Date();
}
}


Anonymous inner class

Annonymous inner class is defined within a method code block.IT can not have constructor and it lacks class ,extend and implement key words.Annonymous inner classes are the local inner classes with no class name.

Annonymous inner classes takes the following form

Class Outer{
InnerAnonymousClass ( new SuperClass(){

}

);

}

Anonymous inner classes are used to create a one time implementation class of an interface.


Strings in JAVA


The java API provides a string class to help you work with the strings of character data.String class represent an im mutalbe thing that is after creating a string object it can not be changed .If you want to modify the content of the string you must use the srtingbuffer class.


Strings can be defined in three possible ways.

1>As a double quoted string variable.

String style=”Action”;

2>Concatenate other strings

String empname= fname + lname;

3>Using a constructor

String name= new String(“arpit rahi”);

String class is a part of java.lang package which is automatically imported to all the java classes so you need not import the java.lang package explicitly.

The system.out.println automatically calls an object’s toString method when a refernce is passed to it.

It will be more clear with the following example

package practice;

public class Movie {


public String toString() {
return "arpit"+ "rahi";
}

public Movie() {
}

public static void main(String[] args) {
Movie mov=new Movie();

System.out.println("arpit");
System.out.println(mov);

}

}

Here if you will run the following code you will get the output as

E:\jdeveloper\jdk\bin\javaw.exe -client -classpath E:\jdeveloper\jdev\mywork\Application1\Practice\classes practice.Movie
arpit
arpitrahi
Process exited with exit code 0.


As you can see the out put when we are calling System.out.println(mov); is arpitrahi.

It is because the system.out.println internally calls the toString() method which is defined to return the value arpitrahi.

If we would not have declared a method toString the System.out.println(mov); would have returned a hash code value for the movie object.But here we are overriding the method toString.This is a very important concept in Java.The overridding method is getting precedence over the original toString method.We will look in to more details and example of over riding methods when we will study interfaces..



Stream

A stream is an abstraction for anything one can read from or write to.The algorythm for reading/writing is almost the same.

Open a stream
While more data
Read/write data
Close the stream.

The java.io package contains the collection of classes which support reading and writing to stream.So one must import this package before calling these classes.

Stream classes are divided into two class hierrarchy

1>Byte Stream and
2>Character Stream.


All classes that have to deal with input operations are inherited from inputStream classes and the classes that have to deal with outpur operations are inherited from outputStream classes.

Now we will check the most commonly used syntax in java i.e

System.out.println.

System is a class in the java.lang.package.

Out is a public final static variable.

Println is an overloaded method of printStream class.

Ptintstream is again a filteroutputStream that subclasses outputStream.

Scanner API


As we hav system.out.println for displaying the output in the console we have a new feature added from jdk 5 onwards.This allows us to read data from the system console or any data stream.



WE use the following format to read the input from the console.

Scanner s= new Scanner(Sytem.in);
String part=s.next();
s.close();

This coding allows us to take an input string from the console.

So our coding will be something like this

package practice;

import java.util.Scanner;

public class Movie {

public Movie() {
}

public static void main(String[] args) {
Movie mov=new Movie();

System.out.println("Enter the value");
Scanner s = new Scanner(System.in);
String type=s.next();
int value=s.nextInt();
s.close();
System.out.println("input value is " + type);

}

}


To use Scanner api we need to import a Scanner Class

import java.util.Scanner;


IF you are using a jdeveloper this code will compile but a wizard will not open to take the input so you need to set the following in order to take the input from jdeveloper.

Select the project and right click on the project.In the left pane select Run/Debug

IN the run configuration select the default and select the edit tab.






Select tool setting and allow program Input






Now if you will run the program it will ask for an input in the jdeveloper console.






Inheritance in JAVA

Inheritance is one of the special functionality of object oriented programming language.

The class which is getting inhertied is called as superclass and the class which inherit the superclass is called as subclass.A subclass is a specialized version of a super class and it inherits all of the instance variables and methods defined by the superclass and its own unique element.

Now we will write a simple java programme to check the functionality of the inheritance


Lets write a super class

package oracle.ws;

public class SuperClass {
int value;
String name;

public void getMethod() {
System.out.println("inheritance"+ " " + name);
}


public void setValue(int value) {
this.value = value;
}

public int getValue() {
return value;
}

public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}
}



and one subclass


package oracle.ws;

public class SubClass extends SuperClass {

String action;

void showMethod() {
System.out.println("value of name in super class is " + name);
}


public static void main(String[] args) {
SubClass subClass = new SubClass();

SuperClass superclass = new SuperClass();
superclass.name="nitin";
superclass.value=12;
subClass.getMethod();
superclass.getMethod();
System.out.println("calling to get the value" + " " +
subClass.getName());
subClass.setName("rahi");
System.out.println("getting the value" + " " + subClass.getName());
subClass.showMethod();

//superclass
superclass.name="nitin";
superclass.value=12;
System.out.println("getting the value" + " " + superclass.getName());

//subclass
subClass.name="ankit";
System.out.println("getting the value" + " " + superclass.getName());
System.out.println("getting the value" + " " + subClass.getName());

}
}

IF you will run this code you will get the following output

inheritance null
inheritance nitin
calling to get the value null
getting the value rahi
value of name in super class is rahi
getting the value nitin
getting the value nitin
getting the value ankit


Now as you can see we are able to access the methods and variables of the superclass it is because the supbclass is able to access the methods and variable of the super class.We can also set the value of superclass variable from sub class.As you can see from the output of the following code.The superclass method can be called by both superclass and subclass.The instance variable of superclass is set by both superclass and subclass instance and when we call the method to get the value using the object of superclass and subclass we get the corresponding value set by superclass object and subclass object.

One important point here to consider is that the class variable which has been declared as private will reamain private to its class.It is not accessible by any code outside its class including the subclasses.It can only be accessed through getters and setters method.

Use of super


Whenever a subclass needs to refer to its immediate superclass it can do so by using the keyword super.

Super has two uses.It can be either used to call a constructor method in superclass or it can be used to acess the members of superclass that has been hidden by the member of subclass.It will be more clear once we will see an example.We will first see how to use super to call a superclass constructor.

Let suppose we have a superclass as following

package oracle.ws;

public class SuperClass {
int l;
int b;
int h;

SuperClass() {
l = 10;
b = 11;
h = 12;
}

SuperClass(int x, int y, int z) {
this.l = x;
this.b = y;
this.h = z;

}

int volume() {
return (l * b * h);
}


}

and subClass as

package oracle.ws;

public class SubClass extends SuperClass {


SubClass() {
super();
}

SubClass(int x, int y, int z) {
super(x,y,z);

}

public static void main(String[] args) {


SubClass subclass = new SubClass();

System.out.println("Volume is " + subclass.volume());

SubClass subclass1 = new SubClass(2,3,4);

System.out.println("New Volume is "+ subclass1.volume());
}


}


Now if you will run this code you will get the output as

Volume is 1320
New Volume is 24


Now we will try to check what exaclty is going on here

IN the super class we have defined two constructor one is without any parameter which assign values 10,11 and 12 to the variables and another is a parameterized constructor which assigns the input provided as parameter to the instance variables.We have one method volume to compute the volume (product of length,breadth and height).

In our subclass we have a subclass construcor which defines a super()

And another subclass parameterized constructor which again has a parameterized super.

If you can see we are creating an instance of subclass at

SubClass subclass = new SubClass();

And then we are trying to display the volume and it fetches us the result 1320.
When ever we create an instance of the object the default constructor is called.So as soon as the JVM sees a new operator it calls its default constructor which is our case is


SubClass() {
super();
}

the only method in the construcor is super.As we know super refers to the superclass constructor the execution of program now goes to superclass constructor that is



SuperClass() {
l = 10;
b = 11;
h = 12;
}

As soon as this method is called all the values are set as per the method so when we call the volume method it displays the result.


Consider the next case when we create another object

SubClass subclass1 = new SubClass(2,3,4);

Again as soon as the jvm sees a new keyword it calls the defualt constructor and again the same process are followed as discussed earlier but here we are creating an object and calline the parameterized constructor.

new SubClass(2,3,4);

So compiler looks for the parameterized constructor

SubClass(int x, int y, int z) {
super(x,y,z);

}

IT encounters the super(x,y,z) this is again a call to the super class constructor but this time it is a call to parameterized constructor of the super class.

So the execution now goes to

SuperClass(int x, int y, int z) {
this.l = x;
this.b = y;
this.h = z;

}

This sets the values that we have provide in our method call to the variables so when we call the voulme method it returs the output with the values that we have provided in our parameter.



We will check another use of super.As we have discussed super is used to access the member of superclass which has been hidden by subclass,it mean if we have the same variable name in both super and subclass we can point to the superclass variable by using super .This will be more clear with an example.

SO our superclass will be

package oracle.ws;

public class SuperClass {
int value;

}


and we will write a subclass

package oracle.ws;

public class SubClass extends SuperClass {

int value;

SubClass(int a,int b) {
super.value=a;
value=b;
}

int area1()

{
return super.value;
}

int area2(){
return value;
}
public static void main(String[] args) {

SubClass subclass=new SubClass(10,12);
System.out.println("super class variable is" + " " +subclass.area1());
System.out.println("sub class variable is" +" " +subclass.area2());


}


}


Now we have the same variable in our both super and subclass.But as you can see we are accessing the superclass variable by using the command super.So the output of our programme will be

super class variable is 10
sub class variable is 12
Process exited with exit code 0.


Method Overriding

When a method in a subclass has same name and type as that of a superclass method then the method in the subclass is said to override the methods in the superclass.That is when ever a call is made for the method from the subclass it always point to the subclass method and the superclass method is hidden .We will see and example to check this out.


So we have our superclass as

package oracle.ws;

public class SuperClass {
void getValue() {
System.out.println("SuperClass");
}
}

and similarly we have our subclass as

package oracle.ws;

public class SubClass extends SuperClass {

void getValue() {
System.out.println("Subclass");
}

public static void main(String[] args) {

SubClass subclass = new SubClass();
subclass.getValue();
}
}


As you can see we have the same method getValue() in both the superclass and subclass so when ever we call the method from subclass it will always call the sub class method that is the superclass method is overrided here.So if you will run this programme you will get the following output

Subclass
Process exited with exit code 0.


Again as we have seen if you want to call the superclass varaible you have to use super variable similarly you can use super to to call the superclass method.



Using Abstract Class

There can be scenarios in which you want to have a class that declares the structure of any implementation and not exactly the full implementation of every method.In that case you will have your class as as abstarct class.Any class that contain any abstract method must be decalred as abstract class.the subclass which extend the abstract superclass must implement all the abstract method defined in the super class.An abstract class can have both an abstract and non abstract method.The abstract methods are basicallly the responsibility of the sub class.The subclass must override these methods by providing its own implementation.You might come up with a question why we need to have a class as abstract.Let supopse we have a super class FourWheeler and all company need to extend the fourwheeler class that is FourWheelere is the super class which will provide some abstract method decalaration that every fourwheeler like maruti ,honda city,scorpio has to define.Now it depends on each of the company how they define all the methods decalred in the super class but they have to implement all the methods declard in the super class.It is some kind of norm that who ever wants to design has to follow certain common rules like each four wheeler should have four wheels ,a steering ,brakes etc.So these can be the abstract methods in super class fourWheeler which all the companies has to implement.



We will check out an example to understand it.


So here is our super class

package oracle.ws;

abstract public class SuperClass {
void getValue() {
System.out.println("SuperClass");
}
abstract void callMe();
}

As you can see we have a method getValue() which is not abstract and other method which is abstract is callMe() so any class which extends the superclass must define the abstract method callMe().

So our sub class I am having is

package oracle.ws;

public class SubClass extends SuperClass {

void callMe() {
System.out.println("defining abstracct method of super class");
}

public static void main(String[] args) {

SubClass subclass = new SubClass();
subclass.getValue();
subclass.callMe();
}
}


Here we have defined the abstract method callMe().

You can check the error by not defining the method in the subclass.
So you will get the following output once you will run this programme.

SuperClass
defining abstracct method of super class
Process exited with exit code 0.


Now we will check how to use final variable to prevent overriding.Inheritance is one of the most important feature of Java but sometimes we don’t want some class or methods to be overridden to class not to be subclassed in that scenario we define the class as final class or method as final method.

Lert suppose in our super class we have a method getValue() as final method


package oracle.ws;

abstract public class SuperClass {
final void getValue() {
System.out.println("SuperClass");
}

}

Here if we define a sub class and try to override the getValue() method we will get error as method can not be over rided as the superclass method is a final method..

Same in case of a class if we define our class as

package oracle.ws;

final public class SuperClass {
void getValue() {
System.out.println("SuperClass");
}

}

then we can not subclass this superclass or in other words we can say that it can not be inherited.


===========================

Packages and Interfaces

Pcakage statement defines a name spcae in which classes are stored.If you don’t define the package name then the classes name are stored in default package which has no name.The gereneral form of package statement is

Package pkg;

In normal words we wrap up all the classes in a folder for reference.It is a sort of namespace.Because there can be many classes with the same name so in order to distinguish them with each other we need some name space ,interface provide that namespace.You can also create a hierrarchy of interfaces like

Package pck1.pck2.pck3;

It means that your classes are stored in the folder structure pck1/pck2/pck3.

So far we have seen many examples and we have used interfaces as the first statement it tells the location of the class files.


Importing of package

Java provides an import statement to bring certain classes or whole pacakge in to visibility.The best feature about it is that once a pacakge is imported you can call the class directly.The import statement structure is like

Import pck;

We will check its functioinality through an example.


So let suppose we have two packages

package pack1;

public class Class1 {
public void getValue() {
System.out.println("arpit");
}
}


and other is

package pack2;

public class Class2 extends pack1.Class1{
public Class2() {
}

public static void main(String[] args) {
Class2 class2 = new Class2();
class2.getValue();
}
}

Here as you can see you can inherit the class by using the pacakgae name and dot operator public class Class2 extends pack1.Class1.

Thus we are able to call the method getValue() of the package pack1 in our package pack2.SO we run our code it should fetch us the following result

arpit
Process exited with exit code 0.

There is one more method to get all the methods of the package one that is through import statement.So we can change our code as


So now our code will look like

package pack1;

public class Class1 {
public void getValue() {
System.out.println("arpit");
}
}


and

package pack2;

import pack1.Class1;
public class Class2 {
public Class2() {
}

public static void main(String[] args) {
Class1 class1= new Class1();
class1.getValue();
}
}

Here we are importing the class which is found within pack1 package.If pack1 happens to be containing more than one classes that we need for our porject then we could have used the following import statement

Import pack1.*;


As you can see we can directly access the class and we can create the instance of the class
Class1 class1= new Class1();

We can not directly access the methods of another package they have to be called from the class1 refernce only.Again this program will fetch us the same result that is

arpit
Process exited with exit code 0.


Interface

Interface is a keyword.As we have seen earlier if a user wants to interact with computer the keyboard and mouse are the interfaces to computer.In a similar way you can fully abstract a classs interface from its implementation.Interfaces are similar to classes but they lack instance variables and their methods are decalred without any body.i. e the methods are not defined.It is up to the end user who implement these methods.It support the concpet of polymorphism that is once a interface is defined you can have multiple methods definition to implement them.We have already seen abstrat identifier.The methods declared in the interfaces are by default abstract.We can also declare variables inside a interface,by default varaibles in an interface are final and static,they must be initialized with some value and they can not be changed by implementing the class.

Lets see an example for interface

package pack2;

interface Declaration {
void getValue(int value);
String getData(String name);
}

and the class implementing these interface is

package pack2;

public class Implementation implements Declaration {
public void getValue(int value) {

System.out.println("implementing class");
}

public String getData(String name) {
return "rahi";
}

public String getStatus(String status) {
return "yes";
}

public static void main(String[] args) {
Implementation implementation = new Implementation();
Declaration dec = new Implementation();

dec.getValue(12);
System.out.println(dec.getData("ram"));
implementation.getValue(21);
System.out.println(implementation.getData("raj"));
System.out.println(implementation.getStatus("yes"));


}


}


As you can see the Implementation class is implementing the Declaration class so it has to define all the abstract methods in the interface.So once we will run this programme we will get the folllowing output

implementing class
rahi
implementing class
rahi
yes
Process exited with exit code 0


A class can extend only one class however a classs can implement multiple interfaces.Another beautiful feature in interfaces in that one interface can extend another interface and in that case the class implementing the final interface should define all the methods that belong to prior interfaces.That is if there is an interface A which declares a method and there is another interface B which extends interface A and also it has two more methods then the class which will implement interface B will have to define all the three methods one of interface A and two of interface B.
==========================================

Exception Handling

An exception is an exceptional condition that can occur within a piece of code.In java exception is handled by five piece of code these are try ,catch,finally ,throw and throws we will check out the use of every one.

First of all we will see how try catch block works.In general we write our code which is suppose to give an exception within a try block and then we write the code to handle this exception in catch block.I will give an example which will make it more clear.

Lets suppose this programme.

package pack2;

public class Exception {

public static void main(String[] args) {
Exception exception = new Exception();
int a=0;
int d= 10/a;
System.out.println("displaying output");

}
}

If you will run this programme you will get the following output

Exception in thread "main" java.lang.ArithmeticException: / by zero
at pack2.Exception.main(Exception.java:8)
Process exited with exit code 1.


As you can see it is giving an Arithemetic exception this is because we are computing
int d= 10/a;

This will fetch us a result of infinity which is undefined so our programme is throwing an exception.As soon as the exception is occurred the programme skips and come out of the main method.It didn’t even displayed the output “displaying output”.

Now we will check this program with try catch block and try to understand the scenario in a better way.

Before that all the exceptions in java are subclass of build in class Throwable.throwable has two subclasses Exception and Error.Runtime Exception is again a subclass of Exception class which defines all the run time exception.

Ok now our new code with try and catch block.


package pack2;

public class Exception {

public static void main(String[] args) {
try {
int a = 0;
int d = 10 / a;
System.out.println("displaying output");
} catch (ArithmeticException e) {
System.out.println("Divide by zero error");
}
System.out.println("this is how we use try catch");

}
}

Now we have surrounded our code which is suppose to be giving the error in a try block and we have defined what to give output in our catch block.So once we will run the programme we willl get folowing output

Divide by zero error
this is how we use try catch
Process exited with exit code 0.

As you can see as soon as the exception is occurred the programme execution goes to catch block which says it is a divide by zero error and then the flow goes to next print statement.Thus it gives us the idea of how try catch is used and how is its functioanlity.


We can use multiple catch statement in our code if we have many exceptions in our code.the only thing to keep in mind is that when you define multiple catch statement the subclass should come first before any of their superclass.Lets check this with a programme.

package pack2;

public class Exception {

public static void main(String[] args) {
try {
int a = 0;
int d = 10 / a;
System.out.println("displaying output");
}
catch(Exception ee) {
System.out.println("Catching Exception");
}
catch (ArithmeticException e) {
System.out.println("Divide by zero error");
}


System.out.println("this is how we use try catch");

}
}

Here as you can see we have defined the Exception class prior to the ArithmeticException class.Exception class is the superclass of ArithmeticException
Subclass.So it handles all the exception of Arithmetic type and many more so our programme excectuion will never reach to the following code.


catch (ArithmeticException e)

As soon as it will encounter

catch(Exception ee)

it will handle the exception and come out of the catch block.

Now we will see how throw works in a java programmming.So far we have seen that are thrown by java run time environment.It is also possible to throw the exception explicity use throw command.The general format of throw is as follows

Throw throwableInstance;

Here throwableInstacne must be an object of type throwable or a subclass of throwable.This will be clear with an example


package pack2;
public class Exception {
public void getValue(){
try {
System.out.println("inside try block");
throw new ArithmeticException("arpit");
} catch (ArithmeticException e) {
System.out.println("Catch the new error and throw again");
throw e;
}
}
public static void main(String[] args) {
Exception exception= new Exception();

try{
exception.getValue();
}
catch (ArithmeticException e) {
System.out.println("CAught inside main" + e);
}
}
}

Consider this example ,We will start from the main programme.Here we are calling the method getValue() inside the try block of main method.It will reach the getValue() method and will again encounter a try and catch blockmhere we are first throwing a new ArithmeticException of type arpit in a try block once it will get a throw statement it will immediately look for the catch statement.The catch statement will print the output “Catch the new error and throw again” and will again throw the error now it’s the duty of the main program to handle this error,it will look for the catch block in the main method and will finally print the output in the main method.So if we will run this programme we will get the following output

inside try block
Catch the new error and throw again
CAught inside mainjava.lang.ArithmeticException: arpit
Process exited with exit code 0.

AS you can notice in the last statement it is throwing an ArithmeticException of type arpit.

Use of Throws

If a method might be throwing an exception which it does not handle,it should specify this behaviour so that the caller of this method can write their code to protect them against this exception.The throws command list the types of exception that a method might throw.Its general format is like

Method throws exception list

IT will be more clear with an example.

package pack2;
public class Exception {
public void getValue()throws ArithmeticException{

System.out.println("inside method");
throw new ArithmeticException("arpit");

}
public static void main(String[] args) {
Exception exception= new Exception();

try{
exception.getValue();
}
catch (ArithmeticException e) {
System.out.println("CAught inside main" + e);
}
}
}

Here as you can see our main method is calling the getValue method which may throw an ArithmeticException so our main class must have to define the safeguard for this exception that is it must have the catch block to catch the exception.So once we will execute this we will get output

inside method
CAught inside mainjava.lang.ArithmeticException: arpit
Process exited with exit code 0.


Finally block

Finally is a block of code which is executed after a try catch block.Finally is always called even if your programme doesn’t throw an exception.Finally is an optional block of code however a try block must have a catch or a finally block.

IN general the structure should look like this

Try{
}
catch{
}
finally{
}

lets see an example.


We will just modify our previous code to see this

package pack2;
public class Exception {
public void getValue()throws ArithmeticException{

System.out.println("inside method");
throw new ArithmeticException("arpit");

}
public static void main(String[] args) {
Exception exception= new Exception();

try{
exception.getValue();
}
catch (ArithmeticException e) {
System.out.println("CAught inside main" + e);
}

finally{
System.out.println("finally is called");
}
}
}


If you will execute this code you will get

\ inside method
CAught inside mainjava.lang.ArithmeticException: arpit
finally is called
Process exited with exit code 0.

We have discussed that even if a exception is caught or not the finally will be called so we will again make a small change to this code and check if finally is called.So new code is

package pack2;
public class Exception {
public void getValue()throws ArithmeticException{

System.out.println("inside method");
throw new ArithmeticException("arpit");

}
public static void main(String[] args) {
Exception exception= new Exception();

try{
exception.getValue();
}

finally{
System.out.println("finally is called");
}
}

It will give us the output

Exception in thread "main" java.lang.ArithmeticException: arpit
at pack2.Exception.getValue(Exception.java:6)
at pack2.Exception.main(Exception.java:13)
inside method
finally is called


As you can see even if the exception is not handled in the main it is callin the finally method so we can just make a point here that finally is always called.It is generally used to flush out the data or clear the cache.
===============================================================

Multithreaded Programming

A multithreaded programme contains two or more parts which can run concurrently.It enables you to write very efficient programme that makes maximu use of CPU.IN java multithreading is build upon thread class and its companion interface runnable.To create a new Thread you either have to extend the thread classs or implement the runnable interface.In an\y programme there is one main thread which start as soon as the programme start and it the last thread which ends because it performs various shutdown actions.The main thread is created automatically however you can control it through a thread object.To do so we should obtain the reference for the thread by calling the method currentThread().This method returns a reference to the thread in which it is called.This will be more clear with this example.The thread class and runnable interface contains lots of methods which you can get from java SE documentation.Go to google search and type java SE documentation and you will get it in the very first entry.


package pack2;

public class ThreadClass {
public static void main(String[] args) {
Thread t = Thread.currentThread();
try {
for (int i = 5; i > 0; i--) {
System.out.println(i);

Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("main Thread interuppted");
}
}

}


Here we have written a simple programme
And we are getting an object of the main thread by calling the method

Thread t = Thread.currentThread();

Now t here is an object of the main thread and we can use it for controlling the execution of the programme.

Again we are using a simple for loop to display values from 5 to 1 in reverese order ,we are just defining a method Thread.sleep(1000),this method is again define in thread class and the 1000 value is in milli second,this method tells the JVM to wait for 1second before printing the next value.This may throw and InterruptedException so we have locked it inside try and catch block.The exception may occur if some other thread might want to interrupt the sleeping thread,here we are talking about one thread but it will make more sense once we will go forward.

The output of this program will be

5
4
3
2
1
Process exited with exit code 0.

And each value will be displayed after a delay of one second.

We will check now how to create a Thread

As we know we have two methods to create a thread one is to implement a runnable interface and another is to extend the thread class.It is up to the user to use their own way of creating a thread but normally if you don’t want to override any other method other than run you should prefer to implement runnable.But here we will see example for each of them.First by implementing runnable interface.



package pack2;

public class ThreadClass implements Runnable {

Thread t;

void CreateThread() {
{
t = new Thread(this, "New Thread");
System.out.println("new thread" + t);
t.start();
}

}

public void run() {
try {
for (int i = 5; i > 0; i--) {
System.out.println("child thread" + i);

Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child Thread interuppted");
}
System.out.println("Child Thread exiting");
}


public static void main(String[] args) {

ThreadClass child = new ThreadClass();
//create a new thread
child.CreateThread();

try {
for (int i = 5; i > 0; i--) {
System.out.println("Main thread" + i);

Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main Thread interuppted");
}
System.out.println("Main Thread exiting");
}

}



Now we will check how this programme works.First of all we have defined a Thread object t.Then we are creating a Thread inside the CreateThread method.As you can see the thread object t is used to create a new thread and the mehod used is

Thread(Runnable threadObj,String threadName)

Here we are passing the values

Thread(this,”New Thread”)

Passing this as thread object mean you wanted the new thread to call the run method.
Now once the thread is create we need to start it which is done by the next statement

t.start();

As soon as the compiler finds the start() method it start looking for the run() method and exceution now goes inside the run().Inside run we are just using a loop to display the value with a time interval of .5 second.

Now lets check our main method.We are calling the CreateThread() method which in turn does all the work as I have explained earlier.At the same time it goes inside the main method and try running its for loop also thus we have two threads one is the main thread and other is the thread which we have created now.They will be using the CPU as per their requirement.The new thread has a time delay of .5 second before printing each value and the main thread has a value of 1 second.So now when you will run this programme you will get out put

new threadThread[New Thread,5,main]
Main thread5
child thread5
child thread4
Main thread4
child thread3
child thread2
child thread1
Main thread3
Child Thread exiting
Main thread2
Main thread1
Main Thread exiting
Process exited with exit code 0.



Please understand each time when you will run this code you may get different output depending upon the cpu usage and the execution of thread.As you can see there are two threads working in the same time.Since the child Thread has a less time interval it compelted early and main thread took long to complete.But the time during which both of them were active they were sharing the cpu and were running together as per time slot.


We just have seen how to create a Thread by implementing runnable interface now we will see the same example by extending Class Thread.


So our new programme is

package pack2;

public class ThreadClass extends Thread {

Thread t;

void CreateThread() {
{
super("New Thread");
System.out.println("new thread" + t);
t.start();
}

}

public void run() {
try {
for (int i = 5; i > 0; i--) {
System.out.println("child thread" + i);

Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child Thread interuppted");
}
System.out.println("Child Thread exiting");
}


public static void main(String[] args) {

ThreadClass child = new ThreadClass();
//create a new thread
child.CreateThread();

try {
for (int i = 5; i > 0; i--) {
System.out.println("Main thread" + i);

Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main Thread interuppted");
}
System.out.println("Main Thread exiting");
}


}


Check the difference in the coding here we have only changed

Implements Runnable to extends Thread

And in the CreateThread() method we are calling a super(“new Thread”).

The first point is clear to you automatically.

For using super as we know a subclass can call the superclass constructor.

In Thread super class we have several constructor one is Thread(String name)

This takes the String name as entry and create a thread so here we are using the property of super to call the super class constructor.However the earlier code will also hold gud for this programme also that is even if we do only one change in our earlier code

To change

Implements Runnable to extends Thread

The programme will work as usual so the out put again will be something like this

new threadThread[New Thread,5,main]
Main thread5
child thread5
child thread4
Main thread4
child thread3
child thread2
Main thread3
child thread1
Child Thread exiting
Main thread2
Main thread1
Main Thread exiting
Process exited with exit code 0.


As we know the main thread should finish last this is because it performs many clean up action so in our example presented above we have used the main thread with large time dealy so that it finishes last.But this is not a gud programming techinque so Thread class has given us two methods to know when does a thread ends.They are isAlive() and join().
IsAlive() method returns a boolean value whether thread is running or not.Join() method waits untill the thread on which it is called terminates.

Lets see one example first of all .


package pack2;

public class ThreadClass implements Runnable{

Thread t;

void CreateThread() {
{
t = new Thread(this, "New Thread");
System.out.println("new thread" + t);
t.start();
}

}

public void run() {
try {
for (int i = 5; i > 0; i--) {
System.out.println("child thread" + i);

Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child Thread interuppted");
}
System.out.println("Child Thread exiting");
}


public static void main(String[] args) {

ThreadClass child1 = new ThreadClass();
ThreadClass child2 = new ThreadClass();
ThreadClass child3 = new ThreadClass();
//create a new thread
child1.CreateThread();
child2.CreateThread();
child3.CreateThread();
try {
for (int i = 5; i > 0; i--) {
System.out.println("Main thread" + i);

Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main Thread interuppted");
}
System.out.println("Main Thread exiting");
}


}


Here in this example we are creating three threads and one main thread is there.As you can see we have again sleep in main method to tell the compile to take more time to complete the main thread and hence our main method is exiting at last .The out put of the code will be something like this.

new threadThread[New Thread,5,main]
new threadThread[New Thread,5,main]
new threadThread[New Thread,5,main]
Main thread5
child thread5
child thread5
child thread5
child thread4
child thread4
child thread4
child thread3
Main thread4
child thread3
child thread3
child thread2
child thread2
child thread2
child thread1
child thread1
Main thread3
child thread1
Child Thread exiting
Child Thread exiting
Child Thread exiting
Main thread2
Main thread1
Main Thread exiting
Process exited with exit code 0.


Now if I don’t want my main thread to wait unnecessarily to wait for such a long time and I want the thread completes as soon as the child thread completes I would do changes in my code something like this.


package pack2;

public class ThreadClass implements Runnable{

Thread t;

void CreateThread() {
{
t = new Thread(this, "New Thread");
System.out.println("new thread" + t);
t.start();
}

}

public void run() {
try {
for (int i = 5; i > 0; i--) {
System.out.println("child thread" + i);

Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child Thread interuppted");
}
System.out.println("Child Thread exiting");
}


public static void main(String[] args) {

ThreadClass child1 = new ThreadClass();
ThreadClass child2 = new ThreadClass();
ThreadClass child3 = new ThreadClass();
//create a new thread
child1.CreateThread();
child2.CreateThread();
child3.CreateThread();

System.out.println("Thread one state "+ child1.t.isAlive());
System.out.println("Thread two state "+ child2.t.isAlive());
System.out.println("Thread three state "+ child3.t.isAlive());
try {
child1.t.join();
child2.t.join();
child3.t.join();
}
catch (InterruptedException e) {
System.out.println("Main Thread interuppted");
}

System.out.println("Thread one state "+ child1.t.isAlive());
System.out.println("Thread two state "+ child2.t.isAlive());
System.out.println("Thread three state "+ child3.t.isAlive());
System.out.println("Main Thread exiting");
}


}



Now here you can see we are using the following statement
System.out.println("Thread one state "+ child1.t.isAlive());

To check the status of the thread if it is alive or dead.This method will return either true or false depending on the value if thread is running or not.

Again we are calling join() method which will wait till the thread it calls terminates so

Child1.t.join() will wait till thread 1 completes and so on thus we need not specify the sleep over here for our main method to wait for some indefinite period of time..As you can see we have again used isalive method in last to check the status if the threads are still alive.IT will be more clear with the result



new threadThread[New Thread,5,main]
new threadThread[New Thread,5,main]
new threadThread[New Thread,5,main]
Thread one state true
Thread two state true
Thread three state true
child thread5
child thread5
child thread5
child thread4
child thread4
child thread4
child thread3
child thread3
child thread3
child thread2
child thread2
child thread2
child thread1
child thread1
child thread1
Child Thread exiting
Child Thread exiting
Child Thread exiting
Thread one state false
Thread two state false
Thread three state false
Main Thread exiting
Process exited with exit code 0.


Synchronization
==================

When two or more threads tries to access a same resource at the same time then we need some method to ensure that the resources will be used by only one thread at a time.This can be done through synchronization.This will be more clear with an example first of all we will see what will happen it we will not synchronize the the threads and then we will check the results after synchornizing the threads.


package pack2;

public class Value {
public void getValues(String name) {
System.out.println("Hello " + name);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("INterrupted");
}
System.out.println("how r u?");
}

}



package pack2;

public class ThreadClass extends Thread {
Thread t;
String msg;
Value val;


public ThreadClass(Value reg,String a1) {
val=reg;
msg = a1;
t = new Thread(this);
t.start();
}

public void run() {
val.getValues(msg);
}


public static void main(String[] args) {
Value val = new Value();
ThreadClass child1 = new ThreadClass(val,"arpit");
ThreadClass child2 = new ThreadClass(val,"ankit");
ThreadClass child3 = new ThreadClass(val,"nitin");

try {
child1.t.join();
child2.t.join();
child3.t.join();
} catch (InterruptedException e) {
System.out.println("Main Thread interuppted");
}
System.out.println("Main Thread exiting");
}
}


So here is our programme.Here as you can see Value class has a method called getValue() which just prints the value passed to it and wait for 1 second.Our ThreadClass has a public constructor which creates the thread and call its start method.The start method in turn call the run method which calls the getValue() method of the Values class.So once we will execute this code we will get th output as

Hello arpit
Hello ankit
Hello nitin
how r u?
how r u?
how r u?
Main Thread exiting


But this is not what we have expected ,our requirement was each should be called and its method should complete and then should proceed for second thread.This happens because each thread compete with each other to complete its thread this is a race around condition,in order to avoid this race around condition we use the synchronization concept so we will make our getValue() method a synchronized method,this can be done by adding the synchronized key word in getValue() method.So our new programme will have everything same as preivous one except one.

Now our value class will look like this

package pack2;

public class Value {
synchronized void getValues(String name) {
System.out.println("Hello " + name);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("INterrupted");
}
System.out.println("how r u?");
}

}

Check here we have adde synchronized key word only.Now if you will run the programme.you will get the following output.


Hello arpit
how r u?
Hello ankit
how r u?
Hello nitin
how r u?
Main Thread exiting
Process exited with exit code 0.

This make much sense and also I believe you might have got the idea of synchronization now.



There are still some topics left in jave but i have discussed all the important concepts.