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
Definite Variable Assignment
Moderator: admin
-
- Posts: 27
- Joined: Thu Feb 07, 2013 9:46 pm
- Contact:
-
- Site Admin
- Posts: 10066
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: Definite Variable Assignment
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.
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.
Who is online
Users browsing this forum: No registered users and 240 guests