Object Declaration and Initialization in Java
In this tutorial, we will learn object declaration and initialization in Java with the help of examples.
We will learn different ways to initialize value or data of the state of an object inside a class. We will cover the following topics under this chapter.
- Object declaration in Java
- Object initialization in Java
- Ways to initialize states of an object in Java
So, let’s understand each topic one by one.
Object Declaration in Java
The process of defining a variable along with its data type and name is called the declaration of state of an object. It is also called declaration of variable.
For example, we have created a class containing two variables “name” and “city” of 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 a 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 string values “PIET” and “Nagpur” respectively.
class College
{
// Initialize the value of variables.
String name = "PIET";
String city = "Nagpur";
}
Ways 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 the value of variables in Java by using three ways. They are as follows:
- By using constructor
- By using a reference variable
- By using a method.
Let’s understand one by one with the help of example programs step by step.
Object Initialization 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.
Let’s take an example program in which we will store data into an object using constructor.
Example 1:
package objectPrograms;
public class Student
{
// Declaration of instance variables, i.e. states of an object.
String name;
int rollNo;
int age;
// Declaration of a default constructor. The constructor name must be the same as the class name.
Student()
{
// Initialize states of an object, i.e. values of variables.
name = "Shubh";
rollNo = 05;
age = 22;
}
// Declare an instance method.
void display()
{
// Displaying the values of variables.
// This is an instance area. Therefore, we can directly call the instance variables.
System.out.println("Student's name:" +name);
System.out.println("Student's roll no: " +rollNo);
System.out.println("Student's age:" +age);
}
// Declare the main method. It is a static method. So, it is a static area.
public static void main(String[] args) {
// Create an object of the class.
Student st = new Student(); // It will call the default constructor.
// 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 by using Reference variable
We can also initialize the value of objects through the reference variable. Let’s take an example program where we will initialize the value of variables using an object reference variable.
Example 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 variables through object reference variable and dot notation.
mk.subject1 = "Science";
mk.sub1Marks = 90;
mk.subject2 = "Maths";
mk.sub2Marks = 99;
// Adding total marks and storing into a variable named totalMarks.
int totalMarks = 90 + 99;
// Call marks using object reference variable.
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 this example, we have created a class named “Marks”. Then, we have declared four instance variables. Inside the main method, we have called instance variables using object reference variable “mk” and initialized them with values.
Object Initialization by using Method
A method in Java is a set of code used to write the logic of application which performs 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 take an example program in which we will create two objects of the Rectangle class and initialize values 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.
Example 3:
package objectPrograms;
public class Rectangle
{
int length;
int breadth;
// Declare an instance method with parameters l and b of data type int.
void perValue(int l, int b)
{
// Here, we are setting the name of parameters different from the name of the variables.
// Because we are not using this reference.
length = l;
breadth = b;
}
void calculate()
{
int perimeter = 2 * (length + breadth);
System.out.println("Perimeter of rectangle: " +perimeter);
}
public static void main(String[] args)
{
// Create the first object of class.
Rectangle rt = new Rectangle();
// This statement will call perValue method and initialize values to the instance variables.
rt.perValue(20, 30);
// This statement will call calculate() method and display the output.
rt.calculate();
// Create the second object of class.
Rectangle rt2 = new Rectangle();
rt2.perValue(50, 50);
rt2.calculate();
}
}
Output: Perimeter of rectangle: 100 Perimeter of rectangle: 200
Let’s take an example program in which we will calculate square and perimeter of a value 45, but we will initialize the 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. Look at the following example code.
Example 4:
package squareProgram;
public class Square
{
// Declaring a variable.
int side;
// Declaring instance methods.
Square()
{
side = 45; // Initialization of value of an 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)
{
// Creating an object of class Square.
Square sq = new Square();
// Calling methods.
sq.calArea();
sq.calPerimeter();
}
}
Output: Area: 2025 Perimeter: 180
In this example, we have declared the main() method inside the class. Let’s take another example in which we will define the main() method outside the 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.
Example 5:
package circleProgram;
public class Circle
{
// Declaring an instance variable.
int radius;
// Declaring an instance method with a parameter r of type int. This is a local variable.
void area(int r)
{
radius = r;
}
// Declaring instance methods.
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.
public static void main(String[] args)
{
// Creating an object of class Circle from outside the class.
Circle cr = new Circle();
cr.area(30);
cr.calArea();
cr.calCircumference();
}
}
Output: Area of circle: 2826.0 Circumference of circle: 188.4
Key Points to Remember:
There are three key points for object declaration and initialization in Java that you should keep in mind. They are as:
1. Declaration of a variable with data type and name is called declaration of the state of an object (declaration of variable).
2. Assigning value to a variable is called initialization of the state of an object. Initialization of variable means storing data into an object.
3. We can assign the value of variables in three ways: by using constructor, reference variable, and method.