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.

No comments: