Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

If loop  RSS feed

 
Sujatha Rangarajan
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when compile the following program,
public static void main(String[] args)
{

int i,j=1;
if(j==1)
i=1;
else if(j==2)
i=2;
else
i=2;
System.out.println(i);

}
it compiles but if modified as follws it gives compilation error i not initialized..
public static void main(String[] args)
{

int i,j=1;
if(j==1)
i=1;
else if(j==2)
j=2;
else
i=2;
System.out.println(i);

}
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If j equals 2, i is never initialized. Remember that localc variables are not initialized.
 
Srinivas Kalvala
Ranch Hand
Posts: 257
Firefox Browser Hibernate Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Java compiler assumes that, a variable may not be initilized in the condition logic as it will not run it at compile time. So the compiler thinks that the variable may not be initialized in if condition. Thats the reason why you get error.

Explore this one with Compiler Parsing.

All the best.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!