Definite Variable Assignment

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
Sweetpin2
Posts: 27
Joined: Thu Feb 07, 2013 9:46 pm
Contact:

Definite Variable Assignment

Post 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

admin
Site Admin
Posts: 10066
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Definite Variable Assignment

Post 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.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 232 guests