mercredi 23 décembre 2015

The curious case of "if" in Java [duplicate]

This question already has an answer here:

While working on something, I stumbled upon this piece of code:

if(true) {
    String message = "Assignment possible";
}

if(true)
    String message = "Time to leave earth";  // error!

Why is there a compilation error in the second case when it is possible to write 'if' conditions in java without the braces ?

The error message doesn't seem to give a proper info:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
Syntax error, insert ":: IdentifierOrNew" to complete ReferenceExpression
Syntax error, insert "AssignmentOperator Expression" to complete Assignment
Syntax error, insert ";" to complete Statement
String cannot be resolved to a variable
message cannot be resolved to a variable

Am I missing something obvious here ? Can someone explain this.

Aucun commentaire:

Enregistrer un commentaire