Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come variables are initialized to their default values even if we have a constructor

i have a question regarding default constructors in java.
as much as i have read about constructors in java, a default constructor initializes all instance variables to their default values. but what if we define a constructor for a class, then how come variables are initialized to their default values if we want them to ?

suppose i have 2 files a.java

public class a
{
    int x;

    public a(int z)
    {
        if(z > 0)
        {
            x = z;
        }
    }

    public  void get()
    {
        System.out.println(x);
    }
} 

and b.java

public class b
{
    public static void main(String[] args)
    {
        a obj = new a(-4);

        obj.get();
    }
}

now here condition (z>0) fails, so x is initialized to zero. but what exactly does this as their is no default constructor in class a.

like image 937
Shashi Avatar asked Dec 11 '22 13:12

Shashi


1 Answers

Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type.

Source

That means that the compiler will do that for you when you build the program.

like image 60
juergen d Avatar answered Dec 14 '22 03:12

juergen d