This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

If-else matching question

 
Richard Boren
Ranch Hand
Posts: 233
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

Based on K&B 1.5 p318 �...Java law decrees that an else clause belongs to the innermost if to which it might possibly belong(..., the closest preceding if that doesn�t have an else.)..."



I thought, the last else would belong to if ( x == 5 ) since it did not have an else, but compile error: �else� without �if� is given. The pattern is �if, if, else, if, else, else�, which I see indented as



Commenting out lines 6, 7, 10, and 11 which gives �if, if, else, else� pattern, will compile and run. Both cases have equal number of if�s and else�s. Which I see as:



Soooo why doesn�t line 10�s else match up with line 1�s if? Isn�t it the closest if without an else?

Richard
 
swarna dasa
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The case actually is

 
megha joshi
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,


If you dont have brackets....than as you know if statement ends with (

if ( x == 5 ) // 1
if ( x > 2 ) // 2
System.out.println( ">2" ) ; // 3 else // 4
System.out.println( "!>2" ) ; // 5

So line 2 and 3 are a if statement, line 4 and 5 are a else statement. Line 1 is the starting of this big if statement comprising of 2,3,4,5 . Line 1 can have a else without a bracket directly at line 6. But in your code it doesnt happen. A new if clause starts at line 6. So the if clause at line 1 doesnt get a else statement.

[ April 25, 2007: Message edited by: megha joshi ]
[ April 25, 2007: Message edited by: megha joshi ]
 
Richard Boren
Ranch Hand
Posts: 233
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, I got it.

Richard
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic