5

The method below cannot be executed in Java because the variable i may remain uninitialized by the time of its use. Is this an issue of syntax or semantics?

public int odd( boolean b ){
    int i;
    if( b ){ i = 3;}
    return i;
}

I would've thought it would be semantics, but according to my instructor it is a syntax error. Is that correct, and why?

2
  • Well, why does it matter? Neither will get you working code. Commented Jan 10, 2012 at 13:08
  • 1
    It has to do with compiler optimization, the compliler finds possible unreachable code like
    – dov.amir
    Commented Jan 10, 2012 at 13:11

2 Answers 2

9

It's an error detected by the Java compiler, but it's not a syntax error; it's perfectly valid according to the Java grammar. It's detected in later stages of analysis, making it a semantic error.

That said, it sounds like your instructor wants to define any compiler error as a syntax error, and probably wants "semantic error" to mean something that goes wrong at runtime. Since the instructor grades the homework, you're forced to accept his definitions (even if they are completely wrong, as in this case ;) ).

0
0

Java has a strictly defined syntax for declaring local variables, and in your code sample you are not following it.

so in java, it becomes a syntax error.

refer this: http://c2.com/cgi/wiki?SyntaxVsSemantics

and this: http://wiki.answers.com/Q/What_are_the_Differences_between_syntax_and_semantic_error

7
  • What part of Java syntax is violated? Commented Jan 10, 2012 at 13:12
  • 1
    That has to be the worst page on c2 I've ever looked at. What gibberish! Commented Jan 10, 2012 at 13:12
  • 1
    From the c2 article- "You must be grateful that they forced the syntax of the English language on you, otherwise you'd be retarded."- Wow... that doesn't really speak to the credibility of this article.
    – Aaron
    Commented Jan 10, 2012 at 13:27
  • 2
    So a compiler can only find syntax errors?! That aside, the link disagrees with you: it's only because Java doesn't initialize local variables that this is an error--that's language semantics, not syntax. Commented Jan 10, 2012 at 13:28
  • 2
    (Note also that the assertion from that link states that int x = "five"; is a syntax error--that's only true if the grammar differentiates between declarations of different types, meaning there would need to be separate grammatical elements for each type declaration. Otherwise it's a type mismatch, also semantic.) Commented Jan 10, 2012 at 13:45

Your Answer

By clicking “Post Your Answer”, you agree to our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.