• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

mystery with if loop ...

 
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
why the following code throws error on compliation
public class Numeric
{
public static void main(String[] args)
{
int i = 3;
//line 1
if(i==3)
//line 2
int p = 3;
}
}
whereas after inserting curly braces in line 1& 2 respectively(the following code) it gets compiled without any problem

public class Numeric
{
public static void main(String[] args)
{
int i = 3;
if(i==3)
{
int p = 3;
}
}
}
similar is the problem with the ques on "while loop mystery" in this forum.
Please help!
Lusha
 
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Reason for this is also same as for while loop.
if(i==3)
int p = 3;
compiler is unable to determine the scope of variable p.
if(i==3); This prefectly OK, since it has empty statement.
int p;
if(i==3) p = 4; This is also prefectly OK
Sujit
 
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Lusha, here's a thread about a very similar piece of code:
http://www.javaranch.com/ubb/Forum24/HTML/010059.html
 
reply
    Bookmark Topic Watch Topic
  • New Topic