This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes If-else matching question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "If-else matching question" Watch "If-else matching question" New topic

If-else matching question

Richard Boren
Ranch Hand

Joined: Mar 01, 2001
Posts: 233
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?

swarna dasa
Ranch Hand

Joined: Mar 15, 2007
Posts: 108
The case actually is

megha joshi
Ranch Hand

Joined: Feb 20, 2007
Posts: 206

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

Joined: Mar 01, 2001
Posts: 233
Thanks, I got it.

Don't get me started about those stupid light bulbs.
subject: If-else matching question