Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty constructor but instance variable still initialized?

I am new to java and I have a doubt about object initialization.

What I currently know:

Constructors are used to initialize the instance variables and if we don't explicitly code the constructor, default constructor is provided that automatically provides the default values to the instance variables like 0 for int, etc.

My Question: How did the following code work(I didn't initialized the instance variable)?

I tried a basic code as follows:

public class hello{

int i;   //Instance variable
         public hello()
         {
         //Constructor is empty!!!
        }


public static void main(String args[])
    {

  System.out.println(new hello().i);


}
}

And the result was 0, but how? I didn't did anything in the constructor and since I explicitly coded the constructor the default constructor shouldn't be invoked(I know I am having a wrong concept in my mind, so please correct me).

How did the above code worked, please clear my doubt. Thank You!

like image 883
Kaushal Jain Avatar asked Dec 06 '22 22:12

Kaushal Jain


2 Answers

The default constructor does not initialize anything. It is empty. Field level variables are automatically initialized to some default values (like 0 for int types) regardless of constructor.

Other default values are

boolean -> false
double -> 0.0D
[any object reference incl. String] -> null
like image 81
Kon Avatar answered Jun 04 '23 09:06

Kon


You might be confusing instance variables and local variables. Local variables are the ones that must be initialized before use, otherwise you get a compile error. int i in this case is an instance variable, which can be left uninitialized without causing the compiler to complain. int instance variables are 0 by default.

like image 41
zxgear Avatar answered Jun 04 '23 10:06

zxgear