Win a copy of Succeeding with AI this week in the Artificial Intelligence and Machine Learning forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Junilu Lacar
Sheriffs:
  • Tim Cooke
  • Jeanne Boyarsky
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:
  • salvin francis
  • fred rosenberger
  • Frits Walraven

Code block with single statement

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My understanding was that if there is only statement in a code block, parentheses ({}) can be skipped. In the below code snippets, first 3 are working fine but last 2 was showing compiler error. This in not practical code but want to understand the concepts.

// #Code 1
if (true)  {
int i=4;
}

// #Code 2

if (true) {
int i;
}

// #Code 3

int i;
if (true)  
i=4;

// #Code 4
if (true)  
int i=4; //ERROR

// #Code 5
if (true)  //ERROR
int i;

 
Marshal
Posts: 69001
275
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Does this question come from a certification exam or book? If so, please supply details of the source. Please also use the code button. If you had done so, your code would have looked so much better (), like this:-It isn't so much a concept as a rule in the grammar. If you look in the Java┬« Language Specification (=JLS), you will find that a statement can be defined as a block or various kinds of statement. So { int i; } is a block, and so would {} be. By the way {} are braces (or curly brackets) not parentheses. But if you simply declare a variable (No 4 and 5) with or without initialisation, that is not defined as a statement, so you are writing a zero‑statement if. And the grammar doesn't allow that.

It is presumably because a declaration on its own inside an if or another control structure can never be used before it goes out of scope. The braces make such a useless declaration into a block, and that is permissible.
 
Danger, 10,000 volts, very electic .... tiny ad:
Two software engineers solve most of the world's problems in one K&R sized book
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic