• 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
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Floating Else does not compile (K&B7)

 
Greenhorn
Posts: 6
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,

When I took one of the tests in the OCA/OCP Java SE7 Programmer I and II Study Guide I came across the following question:



The question was about what happens next and the answer was that it does not compile for the following reason:

Without curly braces, the compiler makes the code 6 lines of code starting with the first if test a single block. That means the second else statement is floating without an if statement to call its own.



Straightforward enough. But then I took an Enthuware test where the following code was present:



Which to me, looked the same as the one in the other test. So I answered that it wouldn't compile. However this was incorrect. The correct answer was that it would compile and would print "False False" if passed false and "True False" if passed true.

I've tried both of these out by tying to compile them and both behave as each test says they will. The first example won't compile and the 2nd one will. It could be that I need to step away and come back later with fresh eyes but at the moment I can't see the difference between them. It looks like both of these have a 2nd floating else that does not correspond to an if. But the 2nd one clearly does correspond to an if. Can anyone shed any light?
 
Sheriff
Posts: 11604
178
Hibernate jQuery Eclipse IDE Spring MySQL Database AngularJS Tomcat Server Chrome Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Janet Smith wrote:I've tried both of these out by tying to compile them and both behave as each test says they will. The first example won't compile and the 2nd one will. It could be that I need to step away and come back later with fresh eyes but at the moment I can't see the difference between them. It looks like both of these have a 2nd floating else that does not correspond to an if. But the 2nd one clearly does correspond to an if. Can anyone shed any light?


Although both code snippets look exactly the same, there is one very, very, very important difference. And this difference is the reason why one code snippet compiles and the other gives a compiler error. Let's reduce both code snippets to the same form and see if you can spot the difference yourself (and explain why it doesn't compile). We only need the if statements. Here is the code snippet which compilesNow the second code snippet which will result in a compiler errorCan you spot the difference? And here is already one tip: you can ignore whitespace (indentation) and the text being printed, because that doesn't matter

Hope it helps!
Kind regards,
Roel
 
author
Posts: 23958
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Janet Smith wrote: I can't see the difference between them. It looks like both of these have a 2nd floating else that does not correspond to an if. But the 2nd one clearly does correspond to an if. Can anyone shed any light?



Basically, the "if" portion of the code is allowed a *single* Java statement. With the "curly braces" it becomes a block, which is considered as a Java statement. Without it, it must be only one statement (and not a declaration statement). If this sound complex, arguably, it kinda is -- you need to dive into the Java Language Specification. Anyway ...

In the first case, you have two statements -- the "if / then / else" combination, and the println() statement. In the second case, you only have the "if / then / else" combination.

Henry
 
Janet Smith
Greenhorn
Posts: 6
1
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ok, from both your comments looking at the code again. In the code snippet that does not compile we have more than one line of code after the first else statement. If we wanted this included in the else we’d surround that with curly braces.

I can then see if I add something similar to the code snippet that does compile I get the same issue.

And I can see if I surround the two lines beneath the else in curly braces both code snippets compile.

So in the code snippet that doesn’t compile does it take:


As one block. So the first if has no corresponding else, but the inner if does. Then it takes the rest:



As code that is executing after the if statement is complete so we then have an else that is floating around with no corresponding if?

If so that is a tricky one. I think once I got the first question I just had it in my head that any appearance of if else else would cause a compiler failure. So its interesting to come across this one.

Thanks for the help. I did a bit of googling and couldn’t come up with the answer so I’m not sure I would have figured that one out myself
 
Roel De Nijs
Sheriff
Posts: 11604
178
Hibernate jQuery Eclipse IDE Spring MySQL Database AngularJS Tomcat Server Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Janet Smith wrote:Ok, from both your comments looking at the code again. In the code snippet that does not compile we have more than one line of code after the first else statement. If we wanted this included in the else we’d surround that with curly braces.

I can then see if I add something similar to the code snippet that does compile I get the same issue.

And I can see if I surround the two lines beneath the else in curly braces both code snippets compile.


Exactly! Have a cow for spotting the statement which causes the code to fail to compile. If you remove (or comment) the statement which prints "c ", the code snippet will compile successfully as well.

Janet Smith wrote:As code that is executing after the if statement is complete so we then have an else that is floating around with no corresponding if?

If so that is a tricky one. I think once I got the first question I just had it in my head that any appearance of if else else would cause a compiler failure. So its interesting to come across this one.


Given both these code snippets, you immediately see the reason why you should always use curly braces, even if there is only one statement. It improves the readibility and maintainability of your code and therefore it is much easier to understand. But this (good) advice won't help you on the actual exam if you are facing such a question, because "you should use curly braces to improve readibility of the code" will definitely not be an answer option

So in order to know if the code compiles successfully and determine the output, you need to verify if the code is valid (and add the curly braces yourself). In order to do this, you need to know the following two important rules:
  • without curly braces the if clause (and the else clause of course too) must be only one statement (not a declaration statement); with curly braces it is a block and in this block you can have as many statements as you want
  • an else clause belongs to the innermost if to which it might possibly belong


  • So let's try adding curly braces to the successful compiling code snippet first.
    Step 1:Step 2:Each else clause has a matching if clause, so that's valid syntax and this code snippet will compile.

    Now let's do the same for the other code snippet which doesn't compile.
    Step 1:Step 2:Because no curly braces are used only one statement is part of the outermost if clause (the one with condition x < y). And that one statement is the innermost if (with condition x > 7). So the ending curly brace of the outermost if comes immediately after the ending curly brace of the innermost if. And now you clearly see the issue: you have a statement which prints "c " (and that's fine), but then you have an else clause and there is no if statement to match it with. So that's why this code snippet does not compile.
    If you delete that print statement, the else clause wll be part of the outermost if and you'll get this code snippetAnother alternative to make the code snippet compile, would be to move the else clause before the statement which prints "c ". This results in the following code snippetAnd finally another possibility is to add an if clause (with condition) just before the statement which prints "c ". Here is the accompanying code snippet

    And the first rule states you can't have a declaration statement if you don't have curly braces and it must be only one statement. Let's illustrate with two code snippets. In the first one there is a declaration statement but no curly braces are used, therefore this code snippet will not compileAnd in the second one a declaration statement is used within curly braces, which is allowed and thus the code snippet compiles successfully

    Hope it helps!
    Kind regards,
    Roel
     
    Tick check! Okay, I guess that was just an itch. Oh wait! Just a tiny ad:
    Smokeless wood heat with a rocket mass heater
    https://woodheat.net
    reply
      Bookmark Topic Watch Topic
    • New Topic