Page 1 of 1

Definite Variable Assignment

Posted: Wed Feb 20, 2013 5:20 pm
by Sweetpin2
Hi,

I am little confused with below two methods

static void definiteAssignmentMethod01(boolean flag)
{
int k;
if (flag) {

k = 3;
}
else
{
k =4;
}
System.out.println(k);

}

static void definiteAssignmentMethod02(boolean flag)
{
int k;
if (flag)
k = 3;
if (!flag)
k = 4;
System.out.println(k);

}

In definiteAssignmentMethod01 the println for k is not giving any compile error while in definiteAssignmentMethod02 the println for k is giving compile error "The local variable k may not have been initialized". Why so? Isn't the if(flag) else of definiteAssignmentMethod01 not same as if(flag), if(!flag) of definiteAssignmentMethod02

Re: Definite Variable Assignment

Posted: Wed Feb 20, 2013 5:42 pm
by admin
No, both are different. In the first case, you have one if/else statement, which cover both the possible paths of the boolean condition and in both the paths k is getting initialized.

In the second, even though you are using if(flag) and if(!flag), both the statements are not linked together. For the compiler, they are two separate if statements and they do not cover all the paths that the execution may take and so the compiler doesn't accept that k will be initialized in all the cases.

HTH,
Paul.