How Variable Initialization Takes place in Java ??

Variable Initialization in Java
Variable Initialization in Java

Initialization in Java

Java has implemented two important concepts. They are as follows:
  1. Initialization via constructor
  2. cleanup via Garbage collector and finalize method
If we have a separate method for initialization named initializer() for every class we create. Then we need to explicitly write that method for every class and that needs to be called before we create an object of the class and use.It is then a overhead for the coder. Java has come up with a simple concept called constructor.If we want to create an object of that class compiler just calls the constructor of the class. If we have a constructor, it is good otherwise compiler will provide us a default one and continue to construct an object during object creation process. This reduce the overhead from developers.

The naming concept:

If we give any name for the constructor , then the name may clash as the same method could be a member of the class itself.Again as the compiler is responsible for the call(to constructor),it must know the method name beforehand.

To resolve these issues,java has come up with the concept as the constructor name should be same as class name. So the same method will be called automatically on initialization.

class MyClass{
System.out.println("Default constructor and creating the class object ")
public class TestConstructor{
public static void main(String args[])
for(int i=0;i<100;i++)
new MyClass();

When an object is created using the new operator ,the storage is allocated and the constructor is called.This mechanism guarantees the object is properly initiated before we can work with it.
The traditional convention of making the method's first letter in lower case and first word of the subsequent words in upper case is ignored here as it has to match exactly with the class name.
Follow this link to get more details about the constructors.

Member Initialization:

Java guarantees that each variable is properly initialized before it is used.

Case-I for Local Variables:

If the variable is defined in a method and not initialized , compiler will throw an error stating the variable may not have been initialized.

void myFunc()
int i;
In this case compiler will throw an error for the line where we have mentioned int i.Compiler could have given a default value but as it is more likely a programmer's error. If compiler gives any value it may also produce different result in different time.Hence it forces the coder to produce an initial value.This reduces the potential bugs.

Case-II for primitive Variables:

If the variable is primitive and a member of the class,in that case,any method can use or initialize the data.So it may not be suitable to force the user to provide the initial value.It is also potentially unsafe to leave them with garbage value.So each primitive value if they are member of the class initialized with their default values.In this way they get an initial value.

public class TestInitialValues{

     public static void main(String []args){
      MyClass mc=new MyClass();
class MyClass{

    boolean t;
    char c;
    short s;
    float f;
    int i;
    double d;
    byte b;
    long l;
    Class obj;
void print(){
    System.out.println("Datatype-->InitialValue \n"+
The output of the code:
$java -Xmx128M -Xms16M TestInitialValues
Even if there is no value are specified,they automatically get initialized.At least there is no garbage value assigned to them .Even the class reference that is object is initialized to null

Specifying initial Values:

It may also happen that we need to specify the initial values sometimes.

Case-I: Direct value assignment:

We can directly provide or assign the values to the variables:

class MyClass{

    boolean t=false;;
    char c='x';
    short s=oxff;
    float f=3.14f;
    int i=44;;
    double d=3.1415;
    byte b=47;
    long l=1.0l;

Case-II: Direct value assignment for class object:

Myclass mc=new MyClass();
If we have not given any initial value and later if we try to use the same object we will get a null pointer Exception.As all object reference is initialized to null(refer case-I).

Case-III: Value assignment from a function:

We can use a function call to initialize the value of a variable.

class MyClass{
int i=MyFunction();
This method may also contain argument and those arguments can not be other class members that have not been initialized.
Allowed Case:

class MyClass{
int i=MyFunction();
int j=MyAnotherFunction(i);
The below written code snippet is not allowed:

class MyClass{
int j=MyAnotherFunction(i);
int i=MyFunction();
We will get an error message from compiler that i may have not initialized.Forward referencing is not possible in java.

Constructor Initialization:

The constructor as we discussed in the beginning of the post can be used to perform initialization . It given much more clarity and provides better flexibility among all the methods.It can assign the values.

class MyClass{
private int i;
private int j
In this case int i and j are initialized to 0 first and then to the respective output of the method calls.Compiler does not force us to initialize the elements here but may ask before they are used.
How Variable Initialization Takes place in Java ?? How Variable Initialization Takes place in Java ?? Reviewed by Animesh Chatterjee on December 27, 2018 Rating: 5

No comments:

Powered by Blogger.