Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

do while loop question

 
prateek shaw
Ranch Hand
Posts: 32
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have one small doubt about do while loop.
As all of know that we can use do while like below


It is not mandatory to have {} with do if you are having one statement.



But above code does not compile.it will give below compile error.
error: variable declaration not allowed here
int p=10;

Before checking this point my understanding was if do have one and only one statement then we can omit the {}. But now i need to remember this as below
If do block has only one statement and this statement should not declare new variable then we can omit the {}.
However l liked this rule , because it does not make any sense do declare new variable if you can not able to use that.

Is my understanding is correct ?
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
prateek shaw wrote:Is my understanding is correct ?

Yes, you are correct!

Please note that this rule is not restricted to a do while statement. It also applies to other flow control statements like if, for, while,... too. Here are a few code snippets which don't compile

Hope it helps!
Kind regards,
Roel



 
Campbell Ritchie
Sheriff
Posts: 51436
87
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to look up the grammar to understand that. Look in the Java® Language Specification (=JLS), and it says:-
DoStatement:
    do Statement while ( Expression ) ;
That means that whatever goes after do and before while must fulfil the requirments to be a statement. Something like
int p = 10;
is not a statement, but a declaration and initialisation. Please work out what you can do with the declaration, and you shoul‍d find an explanation why the grammar doesn't allow declarations there. I think you will find the same if you look up if or while statements in the JLS, too.
 
prateek shaw
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for answering my question. However i know java specification document is there but i feel it is tough to understand.
 
Campbell Ritchie
Sheriff
Posts: 51436
87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a pleasure I am afraid the JLS can be very difficult to understand, yes.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic