Total Pageviews

Saturday, 31 December 2011

BASICS OF THREAD

Before going into details of " multithreading" in java. Let us go through few terminology related to thread and how they are implemented in different fields of computer science.
Listening music on our desktop is a very good example to start with, We all love to listen music. Everyone have there own choice, and they love to play it as many times as possible. Well to play a music
file of .mkv format (video) we need to have a music player , which is nothing but a software. This software is basically a block of code which simplifies a complex process. This program is designed to do many task simultaneously like playing the visual part , audio part and makes the interface of the media player interactive
with the user. User can change the aspect ratio and do many more things while the song is being played.This is an example of multitasking.
Formally multitasking (or time sharing) means that the cpu executes more than one job by switching among them,but the switching is so frequently done that we can interact with each program while it is running.The term switching used above is nothing but context switching. Many of us are familiar with this term.We have studied it in operating system.
Switching the CPU to another process requires saving the state of the current process and loading the saved state for the new process.This task is known as context switching.(process is nothing but a block of code which is under execution  in CPU)
This defination can be simplified in this way. Whenever we are creating a process (say process A) ,a copy of process control block (PCB) is also generated, where various ingredients of a process is kept as a references. A PCB has many section like stack pointer (pointing towards a memory space) , program counter, process state, process id, block of code, cpu schedulling information,
memory management information and many more useful informations are stored. Now whenever a process wants to enter into cpu for its execution. Various informations mentioned above are stored in PCB . Now if context switching takes place while the process is executing, the cpu saves the current details of the process in the PCB and then the CPU updates its content with the ingredients of new process (say process B), After sometimes if the process A comes into existence then
it can start from the begining or start from where it was stopped. It is done by putting the saved contains of the PCB (of process A) into the CPU. And , the current information of process B is saved into its PCB copy , as it was done for process A.
So we come to a conclussion that a big task can be divided into smaller ones and they can be executed concurrently in the CPU by context switching, which increases the efficiency of CPU and helps us a lot.
Multitasking is of two types - (i) process based and, (ii) thread based.
Process based : in process based multitasking more than one  programs runs concurrently in our computer. for example :
 while doing facebook , we can play music in our media player.

Thread based : in thread based , a single program can perform more than one task . for example : we can write a mail at the same time we can change the format of the text. this is known as thread based multitasking.

How threads are better than process???

Threads are basically smallest unit of dispatchable codes. they are light weight  task that share same address space whereas each process takes its own address space. so, there is more utilization of memory in thread based and communication in between them are easier than processes.

Let us go back to the topic "threads in java". In java threads are very much useful , it makes the whole environment asynchronous and helps to increase the cpu efficiency. Now-a-days much emphasis is given on multithreading. It helps to remove the drawbacks of single thread environment like main loop/polling mechanism. In polling mechanism, other process are not allowed to get cpu cycle,
till it gets over.Threads can work concurretly without damaging others execution.
Threads exist in several states. A thread can be running. it can be ready to run as soon as it gets cpu. A running thread can be suspended, which temporarily suspends its activity. A suspended thread can be resumed.allowing it to pick up where it left off. A thread can be blocked when waiting for a resource. At anytime , a thread can be terminated, which halts its execution immediately.Once terminataed it cannot be resumed.

Implementation of multithreading needs priority of threads , synchronization and messaging facilities to communicate with the other threads and provide a asynchronous environment.

Priority of thread means , java assigns priority to the threads according to which they are executed.Thread priorities helps us to determine which thread will get the cpu cycle. Suppose a thread of lower priority occupies cpu , and another thread of higher priority request for cpu
cycle then context switching takes place and the higher priority takes the control over cpu cycle. There are two cases when this type of context switching takes place. (i) when the thread is fully executed and , (ii) when preemptation takes place i.e forcefully control over cpu cycles
are taken.
Java multi-threading creates a asynchronous environment where more than one thread can work properly without conflicting with other threads execution. To avoid such kind of situation where conflict occurs , we need a control mechanism which can take care of it. Monitor helps us
to overcome this problem. Monitor is basically a box kind off thing in which only one thread can exist at a time. So other threads are not allowed enter into this box till the thread which is inside gets completely executed, thus there execution is stopped for a while. In this way , execution
of more than one thread is not affected and they are synchronized properly.
We know that Java threads are light weighted dispatchable codes , and they are mainly a part of big process. So these small block of codes need to communicate with each other. This is done with the help of message .Message is something which helps to communicate between the threads.
Java's messaging system allows a thread to enter a synchronized method on an object , and then wait there until some other thread explicitly notifies it to come out.

Thursday, 28 July 2011

Exception Handling

Java exception is an object which is created at the run time due to some error present in the piece of code.Whenever an exceptional condition occurs an object is created and it is thrown in the method that caused the error . The method may handle the object or pass it on.This objects are caught by another method and processed.The main cause behind the generation of exception(object) is due to syntactical error in the piece of code.It can also arise due to the violation of user defined condition in the program.
Java exception handling is nothing but a way to deal with the run time errors and how they can be corrected or skipped depending upon users choice.Exception handling is done with the help of five keywords try,catch,throw,throws and finally.
1.try - This keyword is used to check whether a block of code contains exception or not.
   try{
    //code;
      }
2. catch - If java finds any exception in the try block then it stops there itself and dose not executes further. Java shows an error message at the run time, so instead of getting compilers message we can use catch keyword to show our own message for making our program more user friendly.

   try{
    //code;   
       }catch(exception_type reference){
    //code;
      }
3. throw - system generated exception are automatically thrown by java run time sytem. To do this manually , throw keyword is used.

    throw throwable_instance;

4. throws - Any exception thrown out of a method is specified with the help of throws clause.
    type method_name(parameter_list) throws eception_type{
         //code;
     }
5. finally - Any code written under the finally is executed after the try block is over.It does not depends upon the exception present in the try block.
    try{
    //code;
    }catch(exception_type reference){
    //code;
    }
    finally{
    //code;
    }

example

import java.io.*;

//demonstrate multicatch system

class catch1 {
    public static void main(String arg[]){
        try{
            int a = arg.length;
            System.out.println("a =" +a);
            int b = 42/a;
            int c[] = {1};
            c[42]=99;
           }
                catch(ArithmeticException e)
                {
            System.out.println("divide c by 0:" + e);
                } catch(Exception e){
            System.out.println("array index oob : "+ e);
           }
                System.out.println("after try/catch blocks.");
         }
                }


explaination :Here we have created a class named as catch1 in which we have defined a static main class. The main method has a try block code contains two types of exception(error), (i) ArithemeticException and, (ii) ArrayOutOfBoundException . There are two catch blocks which will catch the two exceptions, the first one will catch ArithemeticException and the second will catch all kinds of exception(error) as "Exception"(class name) is the base class for all run time exception generated.

We have discussed about try and catch keyword , now lets deal with the other three keywords throw , throws and finally.
throw
Till now we were catching the exception at the run time. We can also throw exception explicitly from our program, with the help of throw keyword.
syntax
throw Throwable_instance;

throwable_instance is an object of type throwable class or sub-class of throwable.Primitive types like int , char and non-Throwable classes , such as string and object,cannot be used as exception.
There are two ways of creating a throwable object either by passing as a reference in the parameter of catch statement or with the help of new operator.


class demo{
   static void call(){
    try
    {
        throw new ArithmeticException("error"); //created a instance of type throwable
    }catch(ArithmeticException e){
        System.out.println("error found in call()");
        throw e; //rethrow the exception as a reference
    }
    }

public static void main(String args[]){
    try{
        call();
     }catch(ArithmeticException e){
         System.out.print("recaught :" + e);
     }
    }
}


Explaination :In the above program , we are handling the Arithmetic type exception in two ways , first in the call() method and second in the main() method.call() method has a try block in which a instance is generated of type ArithmeticException , and then it is thrown . The catch block in the call() method catches the Exception and then it enters the catch block for its execution, here in the catch block it is again the reference of ArithmeticException is thrown. Now in second case i.e in the main() method the call() method is being called within try block, and then it is passed to the catch block as normal try and catch.
The reference "e" thrown in the catch block of call() method creates another exception in the try block of main() method , then it is handled by the respective catch block giving "recaught : error" as output. "error" was passed as a argument in the ArithmeticException type instance.



throws
It is a kind of passing message to the caller of a function that a specific type of message can be generated by the called method , which the called method does not handle. So the callers can take care of the exception and proceed further. syntactically this throws clause is defined with the method declaration statement.

type method_name(parameter list) throws exception list{
//body of method;
}

Here exception list is a comma separated list of the exceptions that a method can throw.

finally
We know that exception causes abrupt execution of a program i.e whenever java finds any kind of exception it stops execution there itself . This can create problem in many cases.Let us take an example of a record file , you can perform many functions on it like update , delete etc. but at the end you have to close this file. In java if it finds any exception in the try block of deletion code it will throw that exception and stop , but your file remains open .The opened file need to be closed before proceeding further.This type of problems can be solved with the help of finally keyword.
finally keyword creates a block of code that will be executed after a try/catch block has completed and before the code following the try and catch block.The finally block will execute whether or not an exception is thrown.If an exception is thrown , the finally block will execute even if or not the catch block excepton matches with the thrown exception.However , finally block is optional and it does not delay the execution tome. It returns with the completion of try/catch block.

// demonstrate finally
class FinallyDemo{
static void procA(){
try{
System.out.println("inside procA");
throw new RuntimeException("demo");
}finally{
System.out.println("procA's finally");
}
}
static void procB(){
try{
System.out.println("inside procB");
return;
}finally{
System.out.println("procB's finally");
}
}
static void procC(){
try{
System.out.println("inside procC");
}finally{
System.out.println("procC's finally");
}
}

public static void main(String args[]){
try{
procA();
}catch(Exception e){
system.out.println("Exception caught");
}
procB();
procC();
}
}


Types of Exception

All the exception types are subclass of the built in class THROWABLE. Throwable is then sub classed into two distinct types i.e exception and error. The exception class is used for exceptional conditions that user should catch. There is an important subclass of exception called RuntimeException.Exception of this types are automatically defined for the program that we write and include things such as division by zero and array indexing.
Error is the second sub class of the throwable class, which defines exception that are not expected to be caught at normal circumstances by our program.Exception of type Error are used by the java run-time system to indicate errors having to di with the run-time environment itself.Stack overflow is an example of such an error.
Java built in exception are divided into two i.e. checked exception and unchecked exception.
checked exception are the compile time exception , i.e. the compiler forces us to handle this exception. eg: IOException
unchecked exception are those that are not forced by the compiler to handle the exception. eg : ArithmeticException.

Thursday, 7 July 2011

Interface

Interface is a keyword which helps us to create a pure abstract class. It consist of variables and a method without body. The syntax of abstract class and the interface are very similar , they both have variables and methods without body . Still there are some difference between them , the abstract class can consist of instance variables and both types of method i.e abstract method (without body ) and methods having body.Whereas , interface consist of variables that are treated as constant and consist of only abstract type methods i.e without body.

syntax :
for abstract class
abstract class class_name{
//access data type variables;
//access return type method_name();
//access return type method_name(parameter list){
//body of method;
}
}
for interface
interface class class_name{
//access final static data type variables;
//access return type method_name();
}

The variables declared in interface are treated as constant, they are declared with the helo of final and static keyword.Interface is very much helpful in creating multiple inheritance type relationship between the classes. This multiple inheritance cannot be achieved without the help of interface, as java dose not support multiple inheritance.

//creating interface
public interface rahul{
int age = 21 ;
public void show();
}
//implementing interface
class mohan implements rahul{
    public void show(){
        System.out.println("Hii my name is rahul.")
    }
    public void show2(){
         System.out.println("Hii my name is mohan.")
    }
}
class friends{
    public static void main(String args[]){
        mohan a1 = new mohan();
        a1.show();
        a1.show2();
    }
}

In the above program we have created an interface "rahul" in which we have declared one integer type variable , and a method show() without any body. Now this interface is implemented  by the class mohan by the use of implements keyword.

Interface can be extended.
One interface can also inherit resources from other interface by the use of extends keyword.The syntax is same as inheriting a class.

interface <name1>{
//access return type variables;
//access return type method();
}

interface <name2> extends interface <name1>{
//access return type variables;
//access return type method();
}

//example of a extending an interface
 interface apple{
    public int area();
    public void show();

}
 interface mango extends apple{
    public int volume();
    public void show2();
}
class input implements mango{
  public  int length, width ,height,orange,grapes;
   public input(int x, int y , int z ){
       length = x ;
       width = y ;
       height = z ;
   }
   public int area(){
   orange = length*width;
   return orange;
   }
   public void show(){
       System.out.println("Length = " + length +" width = " +width + " height = " +height);
       System.out.println(" area = " + orange);
     
   }
   public int volume(){
        grapes = length*width*height;
       return grapes;

   }
   public void show2(){
       System.out.println( " volume = " + grapes);
   }
}
class demo{
    public static void main(String args[]){
        input a1 = new input(4,6,8);
        a1.area();
        a1.show();
        a1.volume();
        a1.show2();
    }
}

Monday, 4 July 2011

Package

In simple words , we can say that package are the folders which contains many classes under one package(folder) name. Package is both naming and a visibility control mechanism.First let us deal with naming part , It creates a name space where classes are stored, and it helps us to resolve class name and method name ambiguity.Second part is the Visibility,the classes stored in the package, are inaccessible by the codes outside the package i.e the classes and the member classes are accessible by the members of the same  package only.
We use the package command to define a name space where classes are stored.If we don't use the package command then it is considered as a default package,which has no name.

package ABC;

Java uses file system directories to store the packages.In the above statement .class files of any class declared to be a part of package ABC must be stored in a directory called ABC.We can store more than one file under the same package name. The Package statement only tells us that the specified class belongs to that package.It dose not harm other files from being the part of that same package.

we can create hierarchy of packages.What we have to do is simply separate each package name by the use of period.
package abc[[.efg][.hij]];

example : java.awt.image;
A package declared above must be stored in the java\awt\image in a windows environment.

//create a package
package NSEC;

public class Fees{
String name;
public int roll , cls;
public Fees(String n,int x , int y){
name = n;
roll = x;
cls = y;
}
void show(){
System.out.println(" name " + name +  " class " + cls + " " + " roll_no " + roll );
}}
public class Depart extends Fees{
int months;
long pay;
public Depart(String n , int x, int y , int z, long p){
super(n, x, y );
months = z;
pay = p;
}
void show(){
System.out.println("your fees structure ");
System.out.println( " name " + name + "class " + cls + " " + " roll_no " + roll);
System.out.println("you have to pay " + pay +"$" + " for " + months + " months");
}
}
class accounts{
public static void main(String aregs[]){
Fees sem =  new Fees("BALA" ,46,6);
Depart cse = new Depart("Biplov " , 43, 5, 6 , 28760);
Fees ref;
ref =sem;
ref.show();
ref =cse ;
ref.show();
}
}
In the above program, we have created a package NSEC, and we have stored the .java and .class files in the NSEC directory.

Importing package.
We know that classes and member classes stored in a package are inaccessible outside the package.So, we have to call a package name to access the classes and other files stored in it. This can be done with the help of import statement.
import pkg1[.pkg2](.classname|*);






* is used to import the entire package.
All the standard classes are stored in package called java.The basic language functions are stored in a package inside of a java.lang. Whenever we create a java program ,the java compiler imports the java.lang package implicitly.

//importing the above NSEC package..
import NSEC.*;
class prac{
    public static void main(String args[]){
Depart  a2 = new Depart("biplov" , 43, 5, 6, 28760);
a2.show(); //using the show method defined in the Depart class , which is a part of NSEC package
    }
}







Friday, 1 July 2011

Method overriding, Dynamic Method Dispatch ,Abstract Class

Method Overriding
When a method in the sub class have the same name and same type of signature as a method in super class, then the method in the sub class is said to overwrite method in super class. When a overridden method is called from within a sub class, it always refer to the method defined in the sub class.The method defined in the super class will be hidden , and we need super keyword to call the method present in the super class.

//example of method overriding
class father{
public int length ,width ;
public  father(int x , int y){
 length = x;
 width = y;
 }
 public void show(){
     System.out.println(" length : " + length + " " + "width : " +width);
 }
}
class son extends father{
    int height;
  son(int x , int y, int z){
  super(x,y);
  height = z;
  }
  public int volume(){
      return height*width*length ;
}
public void show(){
System.out.println("length :" + length + " " + "width :" + width + " " + "height : " + height);
System.out.println("overridden method");
}}
class see{
    public static void main(String args[]){
    son akash = new son(4,5,6);
    int p = akash.volume();
    System.out.println("volume :" + p );
    akash.show();
    }
}


Dynamic Method Dispatch
Dynamic Method Dispatch is an important mechanism in java which helps us to resolve an overridden method at run time, rather than compile time.This mechanism helps us to understand how run time polymorphism occurs.When an overridden method is called by the reference of superclass,Java decides which overridden method is to be executed by looking at the object referred by the superclass reference.


//example of dynamic method dispatch
class student{
   public int roll , marks  ;
   public student(int x, int y){
       roll = x;
       marks = y;
   }
 public void show(){
 System.out.println(" roll no : " + roll + " " + " marks " + marks);
 }}
class studentA extends student{
public int std;
studentA(int x , int y , int z){
  super(x,y);
  std = z;
}
public void show(){
 System.out.println("class " + std + " roll no : " + roll + " " + " marks " + marks);
}
}
class studentB extends student{
public int st;
studentB(int x , int y , int z){
  super(x,y);
  st = z;
}
public void show(){
 System.out.println("class " + st + " roll no : " + roll + " " + " marks " + marks);
}
}
class NewClass{
    public static void main(String args[]){
    student all = new student(12,59);
    studentA A = new studentA(32,95,5);
    studentB B = new studentB(36,96,8);
    student ref; //reference of student class
    ref = all;
    ref.show();
    ref = A ;
    ref.show();
    ref = B;
    ref.show();
}
}

output
roll no : 12 marks 59
class 5 roll no : 32 marks 95
class 8 roll no : 36 marks 95

explanation : Here we have taken a superclass reference "ref" .The superclass's reference is assigned by the objects of superclass and the sub-classes.This reference helps to invoke the show() method. So , the object referred will determine which method is to be executed.

Abstract Class

In the abstract class , we use to declare a generalized form of methods that will be shared by all its sub-classes, leaving it to each sub classes to fill in the details .In other words we can say that , we are just building an empty method in the superclass (abstract class) which will get filled by the methods with same name that are defined in the sub-classes.
syntax :
abstract class <class-name> {
//,,....
abstract void <method-name>();
//;;;
}

note :
# We use the abstract keyword in front of the class keyword to declare the class <class-name> as an   abstract type class.The abstract method declared in the abstract class (superclass) is defined in each sub-classes.
# We cannot create an object of abstract class.
# We can only create the object reference of abstract class because in java, superclass's reference is used to implement run time polymorphism.
# We cannot create abstract constructor and static methods.

//example of abstract class
abstract class student{
   public int roll , marks  ;
   public student(int x, int y){
       roll = x;
       marks = y;
   }
 abstract void show(); //abstract method without body
 }
class studentA extends student{
public int std;
studentA(int x , int y , int z){
  super(x,y);
  std = z;
}
public void show(){
 System.out.println("class " + std + " roll no : " + roll + " " + " marks " + marks);
}
}
class studentB extends student{
public int st;
studentB(int x , int y , int z){
  super(x,y);
  st = z;
}
public void show(){
 System.out.println("class " + st + " roll no : " + roll + " " + " marks " + marks);
}
}
class NewClass{
    public static void main(String args[]){
    studentA A = new studentA(32,95,5);
    studentB B = new studentB(36,96,8);
    student ref; //reference of student class
    ref = A ;
    ref.show();
    ref = B;
    ref.show();
}
}


Thursday, 30 June 2011

INHERITANCE

Inheritance is one of the basic concept of OOP paradigm.It helps us to reuse the resources that already exist, instead of creating them again and again.So we can say that, Inheritance is a mechanism of deriving new class from old class. The old class is known as the parent class , base class or super class and the new class obtained is known as child class or derived class.
There are four types of inheritance.
*single inheritance : only one super class.
*multilevel inheritance : derived from derived class
*multiple inheritance : more than one super class
*hierarchical inheritance : one super class and more than one derived classes.



             
In java , multiple inheritance is possible only with the help of interface
.We will discuss interface latter.

syntax :
class subclass_name extends super_class{
variable of the class;
methods of the class;
}

extends is a keyword ,which signifies that the propertise of the superclass_name is extended to subclass_name.

//example of inheritance
class employee{
public int emplono , basic ;
public employee(int x, int y){
emplono = x;
 basic = y;
 }
public void getdata(){
System.out.println(" Employee number : " + emplono );
System.out.println("basic : " + basic );}
}       
class total extends employee
{
    int days;
total(int x, int y, int z){       
super(x, y);
days = z;}
public int salary (){
return basic*days;   
}
}
class hiha{
public static void main(String args[]){

total a2 = new total(123,500,25);
a2.getdata();
int z = a2.salary();
System.out.println(" salary : " + z);
}}

super keyword
In java , there is a keyword called as super. Super keyword helps us in two ways , first to call the constructor of the super class.Second it helps the sub classes to access the private(access modifier) data members of the super class.The sub class cannot directly access the variables or other data members that are defined as private (access modifier) in the super class.
In the above program , " super(x, y); " is used to pass arguments in the superclass's constructor employee.

//example: to access the superclass
class start {
 int i;
}
class der extends start {
public  int i;
public  der(int x, int y){
  super.i = x;
  i = y;
}
public int area (){
return super.i*i;
}}

class star{
    public static void main(String args[]){
   der a1 = new der(12,5);
  int z = a1.show();
  System.out.println(" area of rectangle : " + z );

    }
}

Tuesday, 28 June 2011

Access Modifier and VARARGS.

ACCESS MODIFIER
Access modifier,
helps us to know the visibility of the variables and the member class, defined in a class .Here visibility means that whether we can accessed by other sub-classes and classes from different packages or not.There are four types of access modifier in java : public, protected ,private and default


Public: Any variable or methods declared as public can be accessed by any other code, within or outside the package in which it is defined.

Protected : The variable or method declare as protected , can be accessed by any class and sub classes in the same package but also to the subclasses in other package.

Private :  If we declare as private ,then they are accessible only with their own class. They cannot be inherited bu subclasses and therefore not accessible in subclasses . It behaves like a method declared as final. It prevents the method from being subclassed.

Default : In java , if we don't mention any access modifier then by default , it is marked as "default" access modifier .They can be accessed only and within the same package .

VARARGS:
variable represent variable length arguments in methods, which is one of the features introduced by J2SE 5.0 .
syntax :
 <access specifier> <static> void method-name(object...arguments)

In the above syntax, the method contains argument called varargs in which object is the type of a aregument, ellipsis(...) is the key to varargs and arguments is the name of the variable.
Varargs help us to build a method, in which we can pass arguments at the run time for an unspecified number of parameters.The arguments passed in varargs are of string type. This string type can be parsed into other types as per our requirement.

example :
//normal method declaration
public static void sample(String name , String location , String mailid){
//body of the method;
}
//using varargs
public static void sample( String...var_name);
//body of the method;
}
In the first case we have declared three parameters for our method but in the second case , we have declared only one parameter but it works similar to the first type, i.e we can pass all the three arguments as we did in the first type.