constructor java program

Here constructor program in java, constructor is used to initialize the variable. Constructor name is same as the name of class name.

Non-parameterized constructor java program

Source Code:

class Code
{
  //constructor
  Code ()
  {
    System.out.println ("Hello From Constructor");
  }
}

public class Main
{
  public static void main (String s[])
  {
    Code ob = new Code ();
  }
}

Output:

Hello From Constructor

Parameterized constructor java program

Source Code:

//parameterized constructor java program
class Code
{
  //constructor
  Code (String name)
  {
    System.out.println ("Hello " + name);
  }
}

class Main
{
  public static void main (String s[])
  {
    Code ob = new Code ("xyz");
  }
}

Output:

Hello xyz

constructor overloading java program

Source Code:

//constructor overloading java program
class Code
{
  //constructor 1
  Code (String name)
  {
    System.out.println ("Hello " + name);
  }

  //constructor 2
  Code (String name1, String name2)
  {
    System.out.println ("Hello " + name1 + " and " + name2);
  }
}

class Main
{
  public static void main (String s[])
  {
    Code ob1 = new Code ("xyz");
    Code ob2 = new Code ("xyz", "abc");
  }
}

Output:

Hello xyz
Hello xyz and abc

For more java program click here.