Satya
Satya

Reputation: 1021

Initialization of constructor through constructor produces unexpected result?

I was confusing since from last several days that how initialization of instance properties through constructor is being done.

Just consider this case

class Demo
{
    int a;
    int b;
    Demo(int a,int b)
    {
        this.a*=a;//this produces 0 here 
        this.b*=b;//this produces 0 here
    }
    public static void main(String[] args)
    {
        Demo d1=new Demo(20,30);
        d1.show();
    }
    public void show()
    {
        System.out.println(this.a);
        System.out.println(this.b);
    }
}

How this is initializing here. As i know constructor initialize a value once.assignments can be possible several times.

Upvotes: 0

Views: 58

Answers (5)

user3443914
user3443914

Reputation: 1

The initial value for an integer is 0. Your actual assignment is this:

a = 0 * 20

which will always return 0.

It's not always necessary to assign a value when a field is declared. 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. Relying on such default values, however, is generally considered bad programming style.

Upvotes: 0

arshajii
arshajii

Reputation: 129507

Integral fields are initialized to 0 by default (as per JLS §4.12.5), so multiplying this.a (0) and this.b (0) by a and b respectively will not change their value of 0. Zero times any number is still zero.

Upvotes: 2

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

The initial value for an integer is 0. Your actual assignment is this:

a = 0 * 20

which will always return 0.

Some documentation:

It's not always necessary to assign a value when a field is declared. 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. Relying on such default values, however, is generally considered bad programming style.

enter image description here

Upvotes: 3

JamesB
JamesB

Reputation: 7894

Because the default value of int is 0.

So the line

this.a*=a;

is equivalent to

0 * 20

which equals 0.

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Upvotes: 0

peter.petrov
peter.petrov

Reputation: 39457

Initially this.a (the class variable) is zero so it will produce zero when you multiply it by a (the argument). This is your problem here.

Upvotes: 0

Related Questions