can anyone explain to me about what actually is a constructor?

Its a special method that is called when a new instance of a class is created. It's used to initialise anything that needs to be initialised for a new instance. Every class needs at least one, and if you don't supply one the compiler gives you a "default" constructor that does nothing. You can define constructors with different parameters, depending on how you want to initialise your new instance.

commented: very useful info +0

thanks for that help. can you give me an example through a small program?i will understand it better with an example..waiting for your reply!

Just have a look at any of the recent posts here - you'll find a constructor in most of the pieces of code. You can identify one because its name is the same as the name of the class, eg

class X{
   public x() { // this is a constructor
     // do some stuff
  }
}

take this example,

class Employee{
  int num;
  }
  public Employee(){ // this is constructor 
    num = 99; // the default values for num is set to 99
  }

This is not a main class , later in a program if you used this class in main class and didn't define any value for num the default value would be called from the constructor and the value will be automatically set to 99.
See this,

class Emp{
public static void main (String args[]){
Employee first = new Employee();
Employee second = new Employee();
first.num = 100;

Since no value for the num is defined for second , it will automatically set to 99 !

commented: very nice +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.