Java Object Declaration and Initialization

In the previous tutorial, you have learned how to create an object in java. In this tutorial, we are going to learn Java object declaration and initialization with example programs.

We will also learn different ways to initialize value or data of the state of object inside a class. We will cover the following topics under this chapter.

Object Declaration in Java


The process of defining variable along with its data type and name is called the declaration of state of an object. In other words, it is also called declaration of variable.

For example, If we declare name and city as variables with data type String, these variables are called instance variables in Java.

class College
 { 
// Declaration of Instance variables. 
     String name; 
     String city; 
 }

Object Initialization in Java


The process of assigning value of the variable is called initialization of state of an object. In other words, Initialization is the process of storing data into an object.

In the below example, we have initialized variables name and city with “PIET” and “Nagpur” respectively.

class College 
 { 
// Initialize the value of variables. 
     String name = "PIET"; 
     String city = "Nagpur"; 
 }

How to Initialize State of Object in Java?


There are three ways by which we can initialize state of an object. In other words, we can initialize value of variables in Java by using three ways. They are as follows:


1. By using constructor
2. By using a reference variable
3. By using a method. 
Object initialization in java

Let’s see one by one with example programs step by step.

Object Initialization in Java by using Constructor


A constructor in Java is a block of code within a class that is used to initialize objects of class. In other words, a constructor is used to initializing the value of variables.

The constructor should not have any return type even void also because if there is return type then JVM would consider as a method, not a constructor.

So, let’s create a program where we will store data into an object using constructor.
Program source code 1:

package objectPrograms; 
 public class Student 
 { 
// Step 1: Declaration of instance variables i.e state of objects. 
     String name; 
     int rollNo; 
     int age; 

// Step 2: Declaration of a default constructor. The constructor name must be the same as the class name. 
     Student()
     { 
// Step 3: Values initialization of state of objects i.e values of variables. 
       name = "Shubh"; 
       rollNo = 05; 
       age = 22; 
    } 
// Step 4: Declare an instance method and print values of instance variables. 
      void display()
      { 
         System.out.println("Student's name:" +name); // Since this is instance area. That's why, we can directly call the instance variables. 
         System.out.println("Student's roll no: " +rollNo); 
         System.out.println("Student's age:" +age); 
     } 
// Step 5: Declare the main method. It is a static method. So, it is a static area. 
     public static void main(String[] args) 
     { 
// Step 6: Create an object of the class. 
     Student st = new Student(); // It will call the default constructor. 

// Step 7: Now, call display method using object reference variable st because we cannot call non-static members directly in the static region. 
      st.display(); 
    } 
  }
Output: 
        Student's name: Shubh 
        Student's roll no: 5 
        Student's age:22

Object Initialization in Java by using Reference variable


We can also initialize the value of objects through the reference variable. So, let’s make a program where we will initialize value of variables using object reference variable. 


Program source code 2:
package objectPrograms; 
  public class Marks 
  { 
// Declare instance variables. This is an instance area or region. 
     String subject1; 
     int sub1Marks; 
     String subject2; 
     int sub2Marks; 

// Declare main method. This is a static region. 
     public static void main(String[] args) 
     { 
// Create an object of the class. 
       Marks mk = new Marks(); 

// Initialize values of objects through object reference variable. 
       mk.subject1 = "Science"; 
       mk.sub1Marks = 90; 
       mk.subject2 = "Maths"; 
       mk.sub2Marks = 99; 

// Now, we are adding total marks with data type int. 
      int totalMarks = 90 + 99; 
// Now call marks using object reference variable and print values. 
      System.out.println("Marks in Science:" +mk.sub1Marks); 
      System.out.println("Marks in Maths:" +mk.sub2Marks); 
      System.out.println("Total Marks: " +totalMarks); 
    } 
 }
Output: 
       Marks in Science: 90 
       Marks in Maths: 99 
       Total Marks: 189
In the preceding example program, we have called variables using object reference variable “mk” and initialized them.

Object Initialization in Java by using Method


A method in java is a set of code used to write the logic of application which perform some specific task or operation. When a method is called, it returns value to the caller. It can also perform a task without returning any value. It can be called from anywhere. Therefore, we can initialize value of an object by using method.

Let’s create a program where we will create two objects of the Rectangle class and initialize value to these objects by calling perValue() method.

Besides it, we will display state (data/value) of the objects by calling calculate() method using object reference variable because we cannot call directly non-static member into the static region.
Program source code 3: 

package objectPrograms; 
 public class Rectangle 
 { 
     int length; 
     int breadth; 
// Declare an instance method and initialize parameters l and b with data type int. 
    void perValue(int l, int b)
    { 
// Here, we are setting name of parameter different from name of the variable because we are not using this reference. 
      length = l; 
      breadth = b; 
   } 
void calculate()
 { 
    int perimeter = 2*(length + breadth); 
    System.out.println("Perimeter of the Rectangle:" +perimeter); 
 } 
public static void main(String[] args)
  {
 // Create the first object of the class. 
      Rectangle rt = new Rectangle(); 
      rt.perValue(20,30); 

// It will call perValue method and initialize values. After that, it will be automatically initialized to the instance variables. 
      rt.calculate(); // it will call calculate() method to display the output. 

// Create the second object of the class. 
    Rectangle rt2 = new Rectangle(); 
      rt2.perValue(50,50); 
      rt2.calculate(); 
   } 
 }
Output: 
       Perimeter of the Rectangle:100 
       Perimeter of the Rectangle:200

Program source code 4: 
In this example program, we will calculate square and perimeter of a value 45 but we will initialize value of variable inside the constructor. We will declare two methods calArea() and calPerimeter() where we will write logic for calculation of area and perimeter. Let’ see the following source code. 

package squareProgram; 
 public class Square 
 { 
    int side; 
    Square()
    { 
       side = 45; // Initialization of value of the instance variable. 
} 
void calArea()
{ 
  int area = side * side; 
  System.out.println("Area: " +area); 
} 
void calPerimeter()
{ 
  int perimeter = 4 * side; 
  System.out.println("Perimeter: " +perimeter); 
 } 
public static void main(String[] args) 
{ 
  Square sq = new Square(); 
   sq.calArea(); 
   sq.calPerimeter(); 
 } 
}
Output: 
       Area: 2025 
       Perimeter: 180

In all the above example programs, we declared the main() method inside class. Now, let’s see another example in which we will define the main() method outside class. 

It is a better approach than previous example because we create several classes in real-time project development and use it from another class. So, let’s see the following source code.

Program source side 5: 

package circleProgram; 
 public class Circle 
 { 
   int radius; 
   void area(int r)
   { 
    radius = r; 
   } 
void calArea()
{ 
  double area = 3.14 * radius * radius; 
  System.out.println(" Area of circle: " + area); 
} 
void calCircumference()
{ 
   double circum = 2 * 3.14 * radius; 
   System.out.println("Circumference of circle: " +circum); 
 } 
}

package circleProgram; 
 public class CircleTest 
 { 
// Declaration of main method outside the class. 
    public static void main(String[] args) 
    { 
      Circle cr = new Circle(); 
      cr.area(30); 
      cr.calArea(); 
      cr.calCircumference();
    } 
}
Output: 
       Area of circle: 2826.0 
       Circumference of circle: 188.4

Final words 
Hope that this tutorial has covered all concepts related to object declaration and initialization in java with various example programs. We have also learned three ways to initialize state of an object using constructor, reference variable, and method. 
Thanks for reading!!!
Next ➤ Life cycle of object in Java⇐ Prev
Next ⇒ 

Leave a Comment