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.

Sunday, 26 June 2011

Method overloading, Parameters and Arguments

Method Overloading :
Method Overloading is an example of Polymorphism.As the name "method overloading" suggests that a method is overloaded to do more than one task. In java, we can define more than one methods within the same class that shares a common name. The only way to distinguish between them is by looking at the numbers and types of parameters passed into it.
example:

Class ShapeArea{
 int length, width, side;
 float radius;
 public static void area(int x , int y){
 length = x;
 width = y;
 int area1= length*width;
 System.out.println("length =" + length +"width =" + width);
 System.out.print("Area of the rectangle = " + area1);
}
public static void area(int z){
 side = z;
 int area2= side*side;
 System.out.println("side =" + side);
 System.out.print("Area of the square = " + area2);
}
public static void area(float r){
 radius = r;
 float area3 = 3.14*radius*radius;
 System.out.println("radius =" + radius);
 System.out.print("Area of the circle = " + area3);
}
}
Class AreaDemo{
 ShapeArea a1 = new ShapeArea();
 ShapeArea a2 = new ShapeArea();
 ShapeArea a3 = new ShapeArea();
public static void main(String args[]){
 a1.area(5,6);
 a2.area(4);
 a3.shape(2.5);
 System.out.println("Thank  you!! ");
}
explanation :
.In the above program , we can see that there are three methods defined within the ShapeArea class , and they share the same name "area" .At compile time the java compiler decides which method is being called by checking the number of arguments and the types of arguments passed into it.
above we can see that in main class we hve called the area method thrice. The first two i.e "a1.area(5,6)" and "a2.area(4), they both have the same integer type arguments but the number of arguments are different. So when the a2.area(4) is called the compiler refers to the method in which area of the square is written,as the parameters set for the area of square matches with that of the arguments. Now , the method defined for the area of circle and square , have same number of parameters but the types of parameter are different.So when area(2.5) , the compiler calls the area method (circle), as the argument passed is of float type.


Constructor Overloading


The theory behind constructor overloading is very much similar to method overloading, here we will deal with   constructor only.


Class area{
 int length, width;
 area(int x , int y){
 length = x;
 width = y;

}
 area(int z){
 length = z;
 width =z;
}
 public static void CalArea(){
 return length*width;
}
}
Class AreaDemo{
public static void main(String args[]){
 area a1 = new area(5,6);
 area a2 = new area(4);
 int p ;
 p = a1.CalArea();
 System.out.print("area of rectangle =" + a1);
 p = a2.CalArea();
 System.out.println("area of square =" + a2);
 System.out.println("Thank  you!! ");
}
}

expaination:
Here area is the constructor, and we have set parameters for both rectangle and square .The constructor for square will take only one integer type argument , whereas rectangle will take two integer type arguments. We are calling them by creating objects a1 and a2 for rectangle and square respectively.


Object as Parameter
Till now we have used various data types as a parameter.It is not compulsory that data types can only be the parameters for our methods or constructor. We can set objects as our parameter.The following program can solve your query that how we can use object as a parameter.

Class Dimension{
 Dimension{
 int length;
 int width;
 Dimension(Dimension Ob){
 length = ob.length;
  width = ob.width;
}
Dimension(int x,int y){
 length = x;
 width =y;
}
Dimension(int s){
length = s;
width =s;
}
public static void CalArea(){
return length*width;
}
}
Class ParameterOb{
public static void main(){
 Dimension a1 = new Dimension(5,6);
 Dimension a2 = new Dimension(4);
 Dimension copy = new Dimension(a2);
 int Area1,Area2,Area3 ;
 Area1 = a1.CalArea();
 System.out.println("area of rectangle =" + Area1);
 Area2 = a2.CalArea();
 System.out.println("area of rectangle =" + Area2);
 Area3 = copy.CalArea();
 System.out.println("area of rectangle =" + Area3);
 System.out.println("Thank You !!);
}
}

Arguments Passing
In java passing arguments in a subroutine(subroutine = It is a portion of code within a larger program that performs a specific task ) is very much similar to what we did in C. It is done in two ways , first way is call-by-value.In this approach copies the value of the argument into the formal parameters of a subroutine.Therefore, changes made to the parameters have no effects on the arguments.The second way is call-by-reference.In this approach , a reference to an argument is passed to the parameter.Inside the subroutine, this argument is used to access the actual argument specified in the call.
This means the change in parameter will affect the arguments used to call the subroutine.

//example of call-by-values
class DEmo{
void change(int x, inty){
i = i+j;
j = j*i;
}
System.out.println(thank you!!");
}
class show{
public static void main(){
DEmo b = new DEmo();
int x = 5, y =6;
System.out.println("x and y before and after change " + x +" " + y);
b.DEmo(5,6);
System.out.println("after change x and y are " + x + " " + y + " respectively" );
}
}

//example of call-by-reference
class test{
 int a, b;
 test(int i , int j){
 a = i;
 b = j;
}
//pass an object
void meth(test o){
o.a += 2;
o.b /= 2;
}
}
class Callbyreference{
 public static void main(){
 test ob = new test(15,20);
 System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b );
 ob.meth(ob);
 System.out.println("ob.a and ob.b after call : " + ob.a + " " + ob.b );
}
}
output:
 ob.a and ob.b before call: 15 20
 ob.a and ob.b after call: 30 40
explanation :
 We can see, in this case , the action inside meth() have affected the object used as an argument.
When an object reference is passed to a method , the reference is passed by use of call-by-value.However, since the value being passed refers to an object , the copy of that value will still refer to the same object that its corresponding argument does.


Returning an object
Theory is simple here, the method we will define returns an object of the class type.
//returning an object
class test{
 int x;
 test(int i){
 x = i;
}
test incrbyten(){
 test temp = new test(a + 10);
 return temp;
}
class returnob{
 public static void main(String args[]){
 test ob1 = new test(2);
 test ob2;
 ob2 = ob1.incrbyten();
 System.out.println("ob.a : " + ob1.a);
 System.out.println("ob.2 : " + ob2.a);
 ob2 = ob2.incrbyten();
 System.out.println("ob2.a after second increase : " + ob2.a);
 }
}
output:
 ob1.a : 2
 ob2.a : 12
explanation :
We can see , each time we call the inrbyten() method is invoked , a new object is created , and a reference to it is returned to the calling routine.Here we are using the new operator for allocating memory at run time, so we don't need to worry about the object going out of scope because the method keeps executing till the refernce is avaiilable to it.If there is no reference given then the object will be reclaimed by the garbage collector.

STATIC
Till now we were knowing that an object is the only way to communicate with a class members.But in java, we can communicate with a class member without creating an object.We can do this with the help of "static" keyword.When a class member is declared as static, it can be accessed before any objects of that class are created, and without reference to any object.The most common example of a static function is the main() function. main() is declared as static because it must be called efore any object exist.
Instance variables declared as static are, essentially , global variables.When objects of that class are declared, no copy of the static variable is made.Instead , all instance of the class share the same static variable.

Methods declared as static have several restriction :

* they can only call other static data.
* they must only access static data.
* they cannot refer to this and super in any way.

(this keyword is always a reference to an object on which the method was invoked.
super keyword is used for the superclass objects or constructor)

FINAL
A variable or a method can be declared as final.final is a keyword which helps us to declare a variable which cannot be modified further.It does not occupy any memory space per instance basis.Thus, it can be considered as a constant. However, a final method and final varables are not same, final method has different meaning which we will discuss latter in inheritance part.

Friday, 24 June 2011

Constructor and Garbage collection

CONSTRUCTORS
The concept behind constructor is very much similar to a method, but it's not a method. A constructor is a block of code which runs when we instantiate an object.A constructor shares a common name with the class in which it is defined.The only way to invoke a constructor is with the help of keyword "new".You can have a doubt from my earlier post on objects, there also I have used "new" operator to initialize the object .
Box mybox = new Box();
I have not mentioned the word constructor there. Actually , a default constructor is created by the compiler, whenever we create a "class".And ,We cannot inherit a constructor.
declaration:
//constructor
class ConstDemo{
    //instace variables
    public ConstDemo(){
    //creating a constructor
    }
    System.out.print("/./././");
 }
In the above syntax , there is a constructor "ConstDemo()" , which has the same name as the class name.Now a problem may arise in your mind that the syntax is very much similar to "method" then how it is different from method. The main difference between a method and the constructor is , the method has some return type but the constructor does not have any return type, not even void.We are going to deal with two types of constructor (i) parameterized constructor and (ii) non-parameterized constructor or default constructor.
parameterized constructors are those constructors in which we can pass one or more arguments and non-parameterized or default constructor are those in which we don't have to pass any arguments.
We cannot inherit a constructor.
//example of parameterized constructor
class Rectangle{
 int length , width ;
 Rectangle( int x , int y) //parameters passed in the constructor rectangle.
 {
   length = x;
   width = y ;
 }
 int rectArea()
 {
   return (length*width);
 }
}
class RectangleArea{
 public static void main(String args[])
 {
   Rectangle rect1 = new Rectangle(20,3);
   int area = rect1.RectArea();
   System.out.print("Area1 =" + area);
  }
}

//example of a non-parameterized or a default constructor.
class Rectangle{
 Rectangle(){ //no parameters are passed
 length = 5;
 breadth = 6;
 }
int rectArea(){
 return (length*width);
}
}
class RectangleArea{
 public static void main(String args[]){
 Rectangle rect2 = new Rectangle();
 int area = rect2.rectArea();
 System.out.print("Area2 = " + area);
}
}

Garbage Collection
While creating an object we use the "new operator to allocate memory for the object at run time. Suppose, we have created extra objects and we do not require few of them.So, we have to delete those useless objects. In C++ , the objects are removed manually with the help of destructor (~) , but here in java it is done by the JVM.
The JVM calls the garbage collector on an object, whenever the object is not accessed by any active thread( in short we can say that a thread is a code which performs some task).The programmers can forcefully try to call the garbage collector by using System.gc() method. However calling this method dosen't ensure us that the garbage collector is called, it is just a mere request. Apart from the objects that are not being accessed by the active thread, an object can be eligible for the garbage collection on the following cases like.
1. If an object is set to null;
 eg: Myclass mc = new Myclass();
     mc =  null;// object is set to null.
2.If an object is initialized by another reference of an object.
 eg: String str1 = new String("BIPLOV");
     String str2 = new String("PRADHAN");
     str1 =str2; //object us initialized by another reference of an object.

finalize() method
The finalize() method is used to define some specific task that will occur when an object is just about to be called by the garbage collector.The java run time calls the finalize method whenever it is about to delete an object of that class.The garbage collectors run periodically, and checks whether there is sum object to be destroyed or not. If it finds one of them , then the Java run time calls the finalize() method on the object and then the selected oobject is destroyed.

Syntax :
  protected void finalize()
 {
  // finalization code here;
 }
Here, we are using the keyword protected  is the access specifier that prevents access to finalize() by code defined outside its class.

Thursday, 23 June 2011

Class Objects And Methods

Let us take an example to understand what class actually means. Our college,we can call it as a class, it consist of different departments which have some functions, these departments are nothing but the methods.and there are many faculties, staffs and management in our college , they are  the variables which are assigned to do some work.There are many colleges in the world which bears the same characteristics, like NSEC ,IEM, HERITAGE etc, these are the objects of our class "college" . From the above example, i hope it is clear that Class is nothing but a blueprint\template which consist of methods and variables.An objects are the instance of a class.They are the base of all the Object oriented programmes.

A class is declared with the help of the "class" keyword. A simple definition of a class is shown here.
class classname{
  type instance-variable1;
  type instance-variable2;
  //...
  type instance-variableN;
  type methodname1(parameter-list){
  //body of method
  }
  type methodname2(parameter-list){
  //body of method
  }
  //...
  type methodname3(parameter-list){
  //body of method
  }
}//end of class.
The data, or variables defined in a class are the instance variables.They are called instance variable because each instance of that class i.e object contains its own copy of these variables.Thus , the data for one instance is separate and unique from the data from other . The code is within the block of the method.Collectively these methods and variables are known as the member of the class.

DECLARING OBJECTS
Obtaining an object is a two step process. First we have to declare a variable of that class. This variable doesnot define an object, it actually refers to an object. In second step , we have to create a physical copy of the object and assign it to that variable. We do this with the help of "new operator". This new operator help us to allocate memory at run time for an object and returns a reference to it.This reference is more or less the address in the memory of the object allocated by the new operator.This reference is then stored in the variable.Thus in java all class objects are "{dynamically allocated".

Declaration :

 Box mybox;  //declare reference to object
mybox = new Box(); //allocate a box object

Here, Box is the class and mybox is the variable.In the first step , we are creating a reference to an object of type Box.After the execution of first step, mybox contains null , which indicates that it dose not point to an object .Any attempt to access this at this point will give a compile time error.In second step, we are giving it a physical existence  by  allocating memory with the help of new operator.In reality the mybox simply holds the memory address of the actual Box object.
The above two statements can be combined together

 Box mybox = new Box();

In java an object reference is similar to a memory pointer but we cannot manipulate this references like we did in actual pointers.

Assigning Object Reference Variables

Box b1 = new Box();
Box b2 = b1;

In the above statements , b1 and b2 both refer to the same object.The assignment of b1 to b2 dose not allocate any memory space or copy any part of the original object as does b1.Thus , any changes made in b2 will affect to which b1 is referring , since they are the same object.Although b1 and b2 refers to the same object but they are not linked.For example :
Box b1 = new Box();
Box b2 = b1;
//..
b1 = null;
Here, b1 has been set to null but b2 still points the original object..

New Operator
A new operator helps to allocate memory at run time.Since there is a finite memory available to us.It may happen that there is insufficient memory space available, so at the run time the new operator cannot allocate memory. This will generate a run time exception.(Exception are the run time error generated due to erroneous input ,memory problem etc.)

Introduction Methods
Methods are nothing but the block of code defined within a class.A class without any methods doesnot have any life.It consist of the code block which executes to give a desired output.
The declaration of a Method:
  type methodname(parameter-list){
  //body of method
  }

a method declaration has 4 parts :
 1. type - the return type of the method like int , void etc.
 2. methodname- it is the valid identifier
 3.parameterlist - it is the number of parameters i.e the variables defined by the method that receives a value when method    is called.(note- arguments are the values that are passed to a method when it is called)
 4.body of method : it is the block which contains the code of the method.


Tuesday, 21 June 2011

DATA TYPES AND VARIABLES

JAVA is a strongly typed language .
 every declaration made in java that is variables and expressions have  a type and each type is strictly defined. The java compiler checks all the expression and parameters to ensure that type are compatible. Any mismatches an error that must be corrected before the compiler will finish compiling the class.

Primitve data types.
Data types specify the size and the type of data that can be stored. In java , there are eight primitive sata types  -- byte , short , int ,long , char , float , double and boolean.
 This eight primitve data types can be put in four groups.

1. INTEGER : This group consist of  byte , short , int and long.

byte   :    It is the simple integer type.This is signed 8-bit type, that has a range from -128-to-127. This data type are generally used for streams of data from a network or file.They are also useful when we are working with binary data that may not be directly compatible with java's other built-in types.

declaration :: byte b, c;

short : It is signed 16-bit type, and has a  range from -32,768 -to- 32,767. Generally they are not used in java.
declaration ::
short s;
short d;

int : it is signed 32-bit type, that has a range from -2,147,483,648 -to- 2,147,483,647 . Other than mathematical operation ,int type are also used for control loops and index arrays.
note : when the small data types i.e byte and short are operated then they are automatically promoted to int type when the expression is evaluated.

long :
it is signed 64-bit type, and lie in the range from -9,223,372,036,854,775,808 -to- 9,223,372,036,854,775,807. since they hava a wide range, so they are generally used for those programs where we need a large whole number and the requird number doesnt lie in the range of int.
declaration  ::  long XTz

Floating-point numbers : This group includes float and double. 

float : it is used where we require single precision , and occupy 32-bit of storage.It is not used when we require a high degree of precised value.
float HighTemp , LowTemp ;

Double
: it is used where double precision is required  , and uses 64 bit to store the value.
//example
public static void main(String args[])
{
doubloe pi , r, a;
r =10.8;
pi = 3.1416;
a = pi*r*r;
System.out.println("Area of circle is " + a);
}
}

CHARACTERS
It include char type to store character.However, c\c++ programmers beware char in java is not the same as char in c or c++. in c++, char is of 8-bits wide.This is  not the case in java, Instead , java uses unicode to represent character found in all human language , and the range of char is from 0 to 65,536 .There are no negative chars.The standard set of characters known as ASCII still ranges from 0 to 127 as always, and the extended 8 bit character set,ISO-Latin-1 ranges from 0 to 255.


//demonstrate char data type

class CharDemo{
 public static void main(String args[]){
char ch1 , ch2;
ch1 = 88;
ch2 = 'y';
System.out.print("ch1 is " + ch1);
System.out.println("ch2 is " + ch2);
}
}

output:
ch1 is x
ch2 is y

explaination :
 in this we have a taken two variables ch1 and ch2 , and declared it as  char type. Now , ch1 is assigned the value 88 and the other variable ch2  is assigned a single character 'y' . The output of ch1 will be the character whose ASCII value is 88 and the output of ch2 is 'y'..


//char variables behave like a integer,
class CharDemo{
public static void main (String args[]);
char ch;
ch='x';
System,out,println("ch contains :" + ch );
ch++;
System.out.printline(" ch is now " + ch);
}}

Variables
The variable is the basic unit of storage in a java program . A variable is defined by the combination of an identifier , a type and an optional initializer. In addition , all variables have a scope , which defines their visiblity , and a lifetime.,

Declaring a variable
In java, all variables must be declared before they are implemented in the program.
declaration :
 type identifier [= value][, identifier [=value]...];
in this way of declaration, we can declare only one data type. example :
int a , b, c;
int d=3,c,e=8; //here d and e are intialized.
byte z = 2;

Dynamic intialization
we can expain it with the help of an example .
//dynamic initalization
   class DynInit {
      double a = 3.0 , b =4.0
      double c = Math.sqrt(a*a + b*b );   // c is dynamically initalized
      System.out.println("Hypotenous = " + c );
    }
  }
In this example , we have declares three local variables a , b and c . a and b are initialized by constants . However c is initalized dynamically to the length of hypotenous.

The scope and lifetime of a variable .
Anything logical code , written within the parenthesis, is known as a block.The block defines the scope of a variable.The variables declared within a block can be accessed within the block only, we can not use it outside the block.
example :
//example
class scope {
   public static void main( String args[]){
   int x;
   x = 10;
   if(x == 10)
{
 int y =100;
 x= y*2;
}
System.out.print(" x = " + x);
}
}
expaination:Here we have declared two variables x and y. the variable x is intialized in the main block whereas , y is assigned within the if block. we cannot use y outside the block but x can be implemented anywhere in the main block.This tells us about the scope of the variables x and y. The output will be // x = 200 //.
The lifetime of a variable is limited to its block. The variables are created at the start of scope and it gets destroyed when the scope is closed.







Saturday, 18 June 2011

How to set a path for java?

Read all the instructions and install the .exe file present in the JDK folder.

CONFIGURING JAVA
once java is installed , we need to configure it by adding the java path to the environment variable.PATH to the java directory , we need to perform the following steps.

step 1 :
 right click on the my computer icon and select properties option from the dropdown menu.The System properties dialog box appears, as shown in the figure.









step 2:
 Select the advanced tab to display the advantage tab page, as shown in the figure.




step 3 :
 click the environment variable button to display the environment variable dialog box, as shown in  the fig .





step 4 :
 The environment variables dialog box is divided ito two section - user variable and system variable .Under the system variable section , select the Path option below the Variable coloumn and click the edit button. The edit System variable dialog box appears , as shown in the figure.





step 5 :
 By default, the Path variable is already set to multiple locations. To set the Java directory path to the Path variable, append the directory path in the variable value text box ,seperated by semi-colon, as shown in the figure.



step 6 :
 click OK to close Edit System variable dialog box.
 click OK to close Environment Variable dialog box.
 click OK to close System Properties dialog box and complete the process of configuring  java


compiling the program
To compile the program, we must run the java compiler javac , with the name of the source file on the command line .
example : javac NSEC.java
the compiler will automatically create a .class file and it contains the bytecode.
example : <classname>.class





JDK and basics of JAVA programs


JAVA DEVELOPMENT KIT
java development kit is the software kit provided by Javasoft that provides classes , packages , methods , etc. for developing Java applications.

JAVA RUN-TIME ENVIRONMENT
Each and every program written in any programming languages requires an environment to get executed. The environment provided by Java is JRE(java run-time environment). That consist of mainly the class loader and the java virtual machine.

CLASS LOADER :
 - while execution all the classes i.e pre-defined and the user defined classes both are loaded by it.

JAVA VIRTUAL MACHINE :
All the language compiler translates source code into machine code for a specific computer. JAVA also does the same thing. JAVA compiler i.e JAVAc produces an intermediate code known as bytecode for machine that does not exist.This machine is called as JVM and it exist only inside the computer memory.It is a simulated computer within the computer and does all the work of real computer.

                                      process of compilation

The virtual machine code is not machine specific.The machine specific code 9machine code) is generated by the Java interpreter by acting as a intermediatery between the virtual machine and the real machine.
note : interpreter is different for different computers



BYTECODE:
It is a set of a highly optimized set of instruction designed to be executed by the java run time system,which         is called the java virtual machine.


JAVA PROGRAMS
Java programs are a collection of whitespace , identifiers, literals , comments, operators, seperators and keywords.

whitespace :
In java , whitespace is a space, tab or newline.

identifiers :
Identifiers are used for class name , method name and variables name. An identifier can be any descriptive sequence of uppercase and lowercase letters, numbers or the underscore and dollar sign characters. They must note begin with a number, lest they will be confused with a numeric literals.
NOTE : Java is a case sensitive, so in java "BIPLOV is different identifier than biplov."

literals :
A constant value in java is created by using a literal representation of it.
example : 100 is a integer
 98.6 is a floating-point value.
 "X" is a variable.
 "biplov pradhan" is a string.

comments :
three types of comments are used in java.
- single line : only one single statement is given as a comment with the help of "//" symbols.
example : // input of the person is taken.

-multiline : more than ine statements are given as a comment with the help of "/* " " */ " symbols.
example : /* thanx for visiting my blog. hope you will like it - biplov pradhan */
-documentation comment : this type of comment are used for HTML file that documents your program. The documentation comment begins with a "/** " and ends with a " */ ".

seperators :
In java there are few charaters used as seperators.here are the list of few



java keywords
Keywords are explicitly reserved identifiers and cannot be used as names for the program variable or other user defined program elements.

There are 50 keywords currently defined in java language.These keywords combined with the syntax of the operators and seperators, form the foundation of the java language.The keyword const and goto are reserved as keywords but they are not used. In early days of java ,several other keywords were reserved for future possible use.
In addition to these keywords , Java reserves the following :"true ,false and null " .These are the values defined by java.We cannot use them as names for program varriables , classes anf so on.


THE JAVA CLASS LIBRARIES
The java environment relies on several built-in class classes that consist of many built-in methods that provide support for such things as I\o , String handling, networking and graphics.



 A SIMPLE JAVA PROGRAM
//simple java program Example.java

import java.io.*;
    class Example
{
   public static void main( String arg[])
          {
int num;
num = 100 ;
System.out.println("This is num : " + num );
num = num * 2;
  System.out.print("the value of num*2 is " );
System.out.println(num);
 }
}

OUTPUT :
    This is num : 100
    The value of num*2 is 200

EXPANATION :
 in this program we are simply taking a variable num, in which we are assigning a value i.e. 100. now , num is multiplied by 2 to give the desiered output.
 Here there are few terms like System , String should begin with uppercase alphabet as java is case sensitive and these are java built in classes.

"public" is the access specifier
static " is the non access specifier
"void" is the return type.

Thursday, 16 June 2011

An Overview OF Java.

 By the end of the 1980's ,object oriented programing using c++ took hold. Indeed, for brief moment it seemed as if programmers had finally found the perfect language.Because C++ blended the high efficiency and stylish elements of c with the object oriented paradigm, it was a language that could be used to create a wide range programs. However , just as in the past ,forces were brewing that would ,once again drive,once again drive computer language evolution forward. Within a few years, the World Wide Web and the Internet would reach critical mass. This event would precipitate another revolution in programming.


# How  JAVA  differs from C and C++.


                       Java is a lot like c but the major difference between java and c is that java is an object oriented language and has a mechanism to define a classes and objects.Java doesnot include some features that are available in c.

=> java does not include the c unique statement keywords sizeof, and typedef.
=> java does not contain the data types struct and union.
=> java does not define the type modifiers keywords auto,             externs,register,signed, and unsigned.
=> java does not support an explicit pointer type.
=> java does not have a preprocessor and therefore we cannot use #define, #include,       and #ifdef statement.
=> java requires that the functions with no arguments must be declared with empty paarenthesis and not with the void keywords done in c.

OBJECT ORIENTED PROGRAMMING PARADIGM 

The major motivating factor in the invention of object-oriented approach is to remove some of the flaws encountered in the procedural approach. OOP treats data as a critical element in program development and does not allow it to flow freely around the system.It ties data and more closely to the function that operate on it , and protect it from accidental modification from outside function. OOP allows decomposition of a program into many entities objects and there builds data and function around this objects. The data of an object can be accessed only by the functions associated with that object. However function of one object can use another the funtion of other objects.
                                   We define " object oriented programming as an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules " .

Some of the striking features of OOPs are : 
* Emphasis is given on data rather than procedure.
* Programs are divided into what are known as objects.
* Data structures are designed such that they characterize the objects.
* Data is hidden and cannot be accessed by external functions.
* Objects may communicate with each other through functions.
* New data and functions can be easily added whenever necessary.


BASIC CONCEPTS OF OBJECT-ORIENTED PROGRAMMING
some of the concepts used in oops are :
   1. Object
   2. Classes
   3. Data abstraction and encapsulation
   4. Inheritance
   5. Polymorphism
   6. Data binding
   7. Message passing

1. OBJECTS : 
 - Objects are the basic runtime entities in an object oriented system.
 - programming problem is analyzed in terms of objects and the nature of communication between them.
 - objects take up space in memory and have associated address like a structure in c.
 - objects can interact without having to know details of each other's data or code. It is sufficient to know the type of message accepted, and the type of reponse returned by the objects.

2. CLASSES : 
 - The entire set of data and code of an object can be made a user defined data type with the help a class.
 - objects are the variable of type class. Once a class has been defined we can create any number of objects belonging to that class.

Example :  we can say, the word " fruit" is a class , which is nothing but a blue print / template representing a group of objects like apple ,orange, banana etc having similar characteristics.







3. DATA ABSTRACTION AND ENCAPSULATION : 
- The wrapping up of data and function into a single unit (called class) is known as encapsulation.
 - These function provide the interface between the object's data and the program.This insulation of the data from direct access by the program is called data hiding /information hiding.
 - Abstraction refers to the act of representing essential features without including the background details or explanations.

Example : a company A and company B are engaged in transaction with each other but it is not necessary for the company B to know what is the salary of the manager of the company A is getting to run the transaction smoothly.
company B only requires the knowledge regarding the business transaction for further processing.


4. INHERITANCE : 
 - Inheritance is the process by which objects of one class acquire the properties of the objects of another class.
suppose we are having a class , and  due to some reasons we have to update the software as per our requirement.So to solve this problem , we have to make a derived class of the previous class which contains all the changes required.This new class will have the combined features of both the classes.
 NOTE : java dose not support multi-inheritance.






5. POLYMORPHISM : 
 - polymorphism , a greek term, means ability to take more than one form. Polymorphism plays an important role in allowing objects having different internal structures to share the same external interfaces . This means that a general class of operation may be accessed in the same manner even though specific actions associated with each operations may differ. Polymorphism is extensively used in implementing inheritance.


There are mainly two types of polymorpism :
*  compile time polymorphism - which is being implemented by the use of super keyword.
*  run time polymorphism - it is implemented by using the base class reference and passing the derived  class object reference to the base class reference. 



6. DYNAMIC BINDING :
 - Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic Binding(late binding) means that the code associated with a given procedure call is not known untill the time of call at run-time.It is associated with polymorphism and inheritance.

7. MESSAGE PASSING : 
 - An oop consist of a set of objects that communicate with each other. The pocess of programming in an object-oriented language, therefore , involves the folloeing basic steps :

1. Creating classes that define objects and their behaviour,
2. Creating objects from class defination, and
3. establishing communicating objects.

Objects communicate with one another by sending and receiving information much the same way as people pass message to one another. A message for an object is a request for execution of a procedure, and therefore will invoke a function in the receiving object that generates the desired results. Message passing involves specifying the name of the object , the name of the function and the information to be sent,